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

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
GO
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS  WHERE  TABLE_NAME='aApprovalTransactions' AND COLUMN_NAME='interfaceid')
BEGIN
	ALTER TABLE [aApprovalTransactions] ADD [interfaceid] int  NULL
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
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

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--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

USE [adminv2]
GO

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

alter table LosGoodsReturnNoteDetail alter  COLUMN GRNDPackTypeId INT NOT NULL

End

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: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


------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--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


------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--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


----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------
--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

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

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




------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--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: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: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: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: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
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Missing column for inventory active directory login
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Go

USE [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumWithAdvance]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSumWithAdvance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSumWithAdvance]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumDetailed]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSumDetailed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSumDetailed]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerAdvanceAsOnDate]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerAdvanceAsOnDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerAdvanceAsOnDate]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerSettlement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerSettlement]
GO
/****** Object:  StoredProcedure [dbo].[spVendorAdvanceasonDate]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spVendorAdvanceasonDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spVendorAdvanceasonDate]
GO
/****** Object:  View [dbo].[vwcustomersummaryasdate]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomersummaryasdate]'))
DROP VIEW [dbo].[vwcustomersummaryasdate]
GO
/****** Object:  StoredProcedure [dbo].[SPPopulateShopInvoiceDetails_vw]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPPopulateShopInvoiceDetails_vw]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SPPopulateShopInvoiceDetails_vw]
GO
/****** Object:  StoredProcedure [dbo].[spTotalInventory]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTotalInventory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTotalInventory]
GO
/****** Object:  View [dbo].[vwtotalinventory]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalinventory]'))
DROP VIEW [dbo].[vwtotalinventory]
GO
/****** Object:  View [dbo].[vwGdnInventoryValue]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnInventoryValue]'))
DROP VIEW [dbo].[vwGdnInventoryValue]
GO
/****** Object:  StoredProcedure [dbo].[spDepUsed]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDepUsed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDepUsed]
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayendReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayendReport]
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_BackupAsOn_22032011]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayendReport_BackupAsOn_22032011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayendReport_BackupAsOn_22032011]
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_Sonee]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayendReport_Sonee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayendReport_Sonee]
GO
/****** Object:  StoredProcedure [dbo].[spDayendReportBackupAsOn07062011]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayendReportBackupAsOn07062011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayendReportBackupAsOn07062011]
GO
/****** Object:  StoredProcedure [dbo].[spgetgodownstockasondate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgetgodownstockasondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spgetgodownstockasondate]
GO
/****** Object:  StoredProcedure [dbo].[spIssueStockBlock]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spIssueStockBlock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spIssueStockBlock]
GO
/****** Object:  View [dbo].[vwgodownwisevalue]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownwisevalue]'))
DROP VIEW [dbo].[vwgodownwisevalue]
GO
/****** Object:  View [dbo].[vwPandCInquiryGodownStock]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryGodownStock]'))
DROP VIEW [dbo].[vwPandCInquiryGodownStock]
GO
/****** Object:  View [dbo].[vwVendorSummary]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSummary]'))
DROP VIEW [dbo].[vwVendorSummary]
GO
/****** Object:  View [dbo].[vwVendorSummaryAsDate]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSummaryAsDate]'))
DROP VIEW [dbo].[vwVendorSummaryAsDate]
GO
/****** Object:  StoredProcedure [dbo].[spWeekSales]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spWeekSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spWeekSales]
GO
/****** Object:  StoredProcedure [dbo].[spWeekSalesShopWise]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spWeekSalesShopWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spWeekSalesShopWise]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCustomerOpeningBalance]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCustomerOpeningBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateCustomerOpeningBalance]
GO
/****** Object:  StoredProcedure [dbo].[spopeningCustomerbalancewithAge]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spopeningCustomerbalancewithAge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spopeningCustomerbalancewithAge]
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquirygodownstock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquirygodownstock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sppandcinquirygodownstock]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerLedger]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerLedger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerLedger]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerArriveExDiff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerArriveExDiff]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff_ServerBackup]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerArriveExDiff_ServerBackup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerArriveExDiff_ServerBackup]
GO
/****** Object:  StoredProcedure [dbo].[spcustomerbalanceasondate]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomerbalanceasondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spcustomerbalanceasondate]
GO
/****** Object:  View [dbo].[vwnetcreditsales]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnetcreditsales]'))
DROP VIEW [dbo].[vwnetcreditsales]
GO
/****** Object:  View [dbo].[vwCreditorAgeSum]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditorAgeSum]'))
DROP VIEW [dbo].[vwCreditorAgeSum]
GO
/****** Object:  View [dbo].[vwstockout]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstockout]'))
DROP VIEW [dbo].[vwstockout]
GO
/****** Object:  View [dbo].[vwTotalInvoiceReceiptAmount]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotalInvoiceReceiptAmount]'))
DROP VIEW [dbo].[vwTotalInvoiceReceiptAmount]
GO
/****** Object:  View [dbo].[vwtotalreceivable]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalreceivable]'))
DROP VIEW [dbo].[vwtotalreceivable]
GO
/****** Object:  View [dbo].[vwtotalreceivablecustwise]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalreceivablecustwise]'))
DROP VIEW [dbo].[vwtotalreceivablecustwise]
GO
/****** Object:  StoredProcedure [dbo].[spMonthSales]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMonthSales]
GO
/****** Object:  StoredProcedure [dbo].[spMonthsalesall]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthsalesall]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMonthsalesall]
GO
/****** Object:  StoredProcedure [dbo].[spMonthSalesShopWise]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthSalesShopWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMonthSalesShopWise]
GO
/****** Object:  View [dbo].[vwinquirygodownstockalllocation]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinquirygodownstockalllocation]'))
DROP VIEW [dbo].[vwinquirygodownstockalllocation]
GO
/****** Object:  View [dbo].[vwInquirygodownStockDatewise]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquirygodownStockDatewise]'))
DROP VIEW [dbo].[vwInquirygodownStockDatewise]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPriceSummary]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCostingMethodPriceSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateCostingMethodPriceSummary]
GO
/****** Object:  View [dbo].[vwInquiryGodownStockSummary]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryGodownStockSummary]'))
DROP VIEW [dbo].[vwInquiryGodownStockSummary]
GO
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinDespatch]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinDespatch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCorrectCostPriceinDespatch]
GO
/****** Object:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 10/06/2012 14:17:29 ******/
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
/****** Object:  StoredProcedure [dbo].[splocalpurchasecosting]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocalpurchasecosting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[splocalpurchasecosting]
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryTotalstock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquiryTotalstock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sppandcinquiryTotalstock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPrice]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCostingMethodPrice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateCostingMethodPrice]
GO
/****** Object:  View [dbo].[vwcurrentstocksonee]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrentstocksonee]'))
DROP VIEW [dbo].[vwcurrentstocksonee]
GO
/****** Object:  View [dbo].[VWDailyItemSalesWithStock]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWDailyItemSalesWithStock]'))
DROP VIEW [dbo].[VWDailyItemSalesWithStock]
GO
/****** Object:  View [dbo].[vwItemDetailsForStockReordering]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailsForStockReordering]'))
DROP VIEW [dbo].[vwItemDetailsForStockReordering]
GO
/****** Object:  View [dbo].[vwstock]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstock]'))
DROP VIEW [dbo].[vwstock]
GO
/****** Object:  View [dbo].[vwtmpstock]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtmpstock]'))
DROP VIEW [dbo].[vwtmpstock]
GO
/****** Object:  View [dbo].[vwinvoicesettleformis]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoicesettleformis]'))
DROP VIEW [dbo].[vwinvoicesettleformis]
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingGodownWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingGodownWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockBalancingGodownWise]
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeTransactions]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeTransactions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSummarizeTransactions]
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeGodownTransactions]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeGodownTransactions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSummarizeGodownTransactions]
GO
/****** Object:  StoredProcedure [dbo].[spTotalTax]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTotalTax]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTotalTax]
GO
/****** Object:  View [dbo].[vw_Report_service_CustomerLedger]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_service_CustomerLedger]'))
DROP VIEW [dbo].[vw_Report_service_CustomerLedger]
GO
/****** Object:  View [dbo].[vwtotalpayable]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalpayable]'))
DROP VIEW [dbo].[vwtotalpayable]
GO
/****** Object:  View [dbo].[vwtotalpayablevedorwise]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalpayablevedorwise]'))
DROP VIEW [dbo].[vwtotalpayablevedorwise]
GO
/****** Object:  View [dbo].[vwtotalbillpaidamount]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalbillpaidamount]'))
DROP VIEW [dbo].[vwtotalbillpaidamount]
GO
/****** Object:  View [dbo].[vwbillspaymentformis]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillspaymentformis]'))
DROP VIEW [dbo].[vwbillspaymentformis]
GO
/****** Object:  View [dbo].[vwbookservinvoicesettle]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservinvoicesettle]'))
DROP VIEW [dbo].[vwbookservinvoicesettle]
GO
/****** Object:  View [dbo].[vwDebtorAge]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebtorAge]'))
DROP VIEW [dbo].[vwDebtorAge]
GO
/****** Object:  View [dbo].[vwPORequestFlow]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPORequestFlow]'))
DROP VIEW [dbo].[vwPORequestFlow]
GO
/****** Object:  View [dbo].[vwSalesAnalysisByYear]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByYear]'))
DROP VIEW [dbo].[vwSalesAnalysisByYear]
GO
/****** Object:  View [dbo].[vwsalesyearmonthdaywise]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesyearmonthdaywise]'))
DROP VIEW [dbo].[vwsalesyearmonthdaywise]
GO
/****** Object:  View [dbo].[vwshipmentwisestock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwisestock]'))
DROP VIEW [dbo].[vwshipmentwisestock]
GO
/****** Object:  View [dbo].[vwnetcashinflow]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnetcashinflow]'))
DROP VIEW [dbo].[vwnetcashinflow]
GO
/****** Object:  View [dbo].[vwcreditinvoicesettlecommision]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditinvoicesettlecommision]'))
DROP VIEW [dbo].[vwcreditinvoicesettlecommision]
GO
/****** Object:  View [dbo].[vwCreditSales]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditSales]'))
DROP VIEW [dbo].[vwCreditSales]
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionDay]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailySalesCollectionDay]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailySalesCollectionDay]
GO
/****** Object:  View [dbo].[vwHQserinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQserinvandrecamount]'))
DROP VIEW [dbo].[vwHQserinvandrecamount]
GO
/****** Object:  View [dbo].[vwimportqty]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwimportqty]'))
DROP VIEW [dbo].[vwimportqty]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningstockondate]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningstockondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningstockondate]
GO
/****** Object:  StoredProcedure [dbo].[spopeningvendorbalanceperiod]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spopeningvendorbalanceperiod]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spopeningvendorbalanceperiod]
GO
/****** Object:  StoredProcedure [dbo].[spULshopGoodsArrival]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopGoodsArrival]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopGoodsArrival]
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendorarriveexdiff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spvendorarriveexdiff]
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff_BackUp]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendorarriveexdiff_BackUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spvendorarriveexdiff_BackUp]
GO
/****** Object:  StoredProcedure [dbo].[spVendorLedger]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spVendorLedger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spVendorLedger]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateVendorOpeningBalance]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateVendorOpeningBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateVendorOpeningBalance]
GO
/****** Object:  View [dbo].[vwArrivalGdnToshop]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwArrivalGdnToshop]'))
DROP VIEW [dbo].[vwArrivalGdnToshop]
GO
/****** Object:  View [dbo].[vwspecialinvrecamount]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvrecamount]'))
DROP VIEW [dbo].[vwspecialinvrecamount]
GO
/****** Object:  View [dbo].[vwadvancepaidtoretrive]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidtoretrive]'))
DROP VIEW [dbo].[vwadvancepaidtoretrive]
GO
/****** Object:  View [dbo].[vwAdvancePaidToRetriveCustomer]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAdvancePaidToRetriveCustomer]'))
DROP VIEW [dbo].[vwAdvancePaidToRetriveCustomer]
GO
/****** Object:  View [dbo].[purchasecostingtracking]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchasecostingtracking]'))
DROP VIEW [dbo].[purchasecostingtracking]
GO
/****** Object:  View [dbo].[vwGoodReqDespArrDtls]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodReqDespArrDtls]'))
DROP VIEW [dbo].[vwGoodReqDespArrDtls]
GO
/****** Object:  View [dbo].[vwGoodReqDespArrDtlsPurReq]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodReqDespArrDtlsPurReq]'))
DROP VIEW [dbo].[vwGoodReqDespArrDtlsPurReq]
GO
/****** Object:  View [dbo].[vwreexportinvoicesettled]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportinvoicesettled]'))
DROP VIEW [dbo].[vwreexportinvoicesettled]
GO
/****** Object:  View [dbo].[vwSalesAnalysisByMonth]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByMonth]'))
DROP VIEW [dbo].[vwSalesAnalysisByMonth]
GO
/****** Object:  View [dbo].[vwSalesAnalysisByWeek]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByWeek]'))
DROP VIEW [dbo].[vwSalesAnalysisByWeek]
GO
/****** Object:  View [dbo].[vwServiceDetailsForCommision]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceDetailsForCommision]'))
DROP VIEW [dbo].[vwServiceDetailsForCommision]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum_tem]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSum_tem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSum_tem]
GO
/****** Object:  StoredProcedure [dbo].[sp_ssrsreptotaltax]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ssrsreptotaltax]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ssrsreptotaltax]
GO
/****** Object:  View [dbo].[vwcustomeradvance]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomeradvance]'))
DROP VIEW [dbo].[vwcustomeradvance]
GO
/****** Object:  View [dbo].[vwCustomerLedger]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerLedger]'))
DROP VIEW [dbo].[vwCustomerLedger]
GO
/****** Object:  View [dbo].[vwGdnBinCardForGdnReport]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardForGdnReport]'))
DROP VIEW [dbo].[vwGdnBinCardForGdnReport]
GO
/****** Object:  View [dbo].[vwGdnBinCardWithOpening]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardWithOpening]'))
DROP VIEW [dbo].[vwGdnBinCardWithOpening]
GO
/****** Object:  View [dbo].[vwShopCreditInvRecAmount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCreditInvRecAmount]'))
DROP VIEW [dbo].[vwShopCreditInvRecAmount]
GO
/****** Object:  View [dbo].[vwShopSerInvAndRecAmount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSerInvAndRecAmount]'))
DROP VIEW [dbo].[vwShopSerInvAndRecAmount]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockArrival]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockArrival]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateShopStockArrival]
GO
/****** Object:  View [dbo].[vwShopSerSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSerSettlementDetails]'))
DROP VIEW [dbo].[vwShopSerSettlementDetails]
GO
/****** Object:  View [dbo].[vwshopcustomercreditnotes]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopcustomercreditnotes]'))
DROP VIEW [dbo].[vwshopcustomercreditnotes]
GO
/****** Object:  View [dbo].[newss]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[newss]'))
DROP VIEW [dbo].[newss]
GO
/****** Object:  StoredProcedure [dbo].[spCurrentShopStock]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCurrentShopStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCurrentShopStock]
GO
/****** Object:  View [dbo].[vwarrivaldistributedetails]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwarrivaldistributedetails]'))
DROP VIEW [dbo].[vwarrivaldistributedetails]
GO
/****** Object:  View [dbo].[vwDistributeWriteoff]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDistributeWriteoff]'))
DROP VIEW [dbo].[vwDistributeWriteoff]
GO
/****** Object:  View [dbo].[vwShopBincardAudit_new]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit_new]'))
DROP VIEW [dbo].[vwShopBincardAudit_new]
GO
/****** Object:  View [dbo].[vwShopBinCardAuditCustWise]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAuditCustWise]'))
DROP VIEW [dbo].[vwShopBinCardAuditCustWise]
GO
/****** Object:  View [dbo].[vwLocalPurchaseInvoiceDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseInvoiceDetails]'))
DROP VIEW [dbo].[vwLocalPurchaseInvoiceDetails]
GO
/****** Object:  StoredProcedure [dbo].[spFindItemsRateNotFixed]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFindItemsRateNotFixed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFindItemsRateNotFixed]
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryValueAsOnDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInventoryValueAsOnDate]
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate_TransWise]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryValueAsOnDate_TransWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInventoryValueAsOnDate_TransWise]
GO
/****** Object:  View [dbo].[vwQuantityUnprocessed_Inv]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuantityUnprocessed_Inv]'))
DROP VIEW [dbo].[vwQuantityUnprocessed_Inv]
GO
/****** Object:  StoredProcedure [dbo].[spItemFlowAnalysis]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemFlowAnalysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spItemFlowAnalysis]
GO
/****** Object:  StoredProcedure [dbo].[spItemStockDepartmentWise]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemStockDepartmentWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spItemStockDepartmentWise]
GO
/****** Object:  StoredProcedure [dbo].[splocationwise]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocationwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[splocationwise]
GO
/****** Object:  StoredProcedure [dbo].[splocupdatestock]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocupdatestock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[splocupdatestock]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningCompanyStockOnDate]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningCompanyStockOnDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningCompanyStockOnDate]
GO
/****** Object:  StoredProcedure [dbo].[spPurchaseandSalesItemwise]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPurchaseandSalesItemwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPurchaseandSalesItemwise]
GO
/****** Object:  StoredProcedure [dbo].[spPurchaseAndStock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPurchaseAndStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPurchaseAndStock]
GO
/****** Object:  StoredProcedure [dbo].[spShipmentWiseItemFlow]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShipmentWiseItemFlow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShipmentWiseItemFlow]
GO
/****** Object:  StoredProcedure [dbo].[AdvanceReceiptsNotSettled]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AdvanceReceiptsNotSettled]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[AdvanceReceiptsNotSettled]
GO
/****** Object:  View [dbo].[vwGdnBinCardSummary]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardSummary]'))
DROP VIEW [dbo].[vwGdnBinCardSummary]
GO
/****** Object:  StoredProcedure [dbo].[spupdatestockproblem]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spupdatestockproblem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spupdatestockproblem]
GO
/****** Object:  View [dbo].[vwCompanyBinCardAudit]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyBinCardAudit]'))
DROP VIEW [dbo].[vwCompanyBinCardAudit]
GO
/****** Object:  View [dbo].[vwDeparmentBinCardAudit]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDeparmentBinCardAudit]'))
DROP VIEW [dbo].[vwDeparmentBinCardAudit]
GO
/****** Object:  View [dbo].[vwItemsinTransaction]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsinTransaction]'))
DROP VIEW [dbo].[vwItemsinTransaction]
GO
/****** Object:  StoredProcedure [dbo].[spEditGodownStock]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spEditGodownStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spEditGodownStock]
GO
/****** Object:  View [dbo].[vwCashInflow]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCashInflow]'))
DROP VIEW [dbo].[vwCashInflow]
GO
/****** Object:  View [dbo].[vwCustomerSettlementDetails]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSettlementDetails]'))
DROP VIEW [dbo].[vwCustomerSettlementDetails]
GO
/****** Object:  View [dbo].[vwDailySalesCollection]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection]'))
DROP VIEW [dbo].[vwDailySalesCollection]
GO
/****** Object:  View [dbo].[vwDespatchArrival]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchArrival]'))
DROP VIEW [dbo].[vwDespatchArrival]
GO
/****** Object:  View [dbo].[vwDespatchOutQty]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchOutQty]'))
DROP VIEW [dbo].[vwDespatchOutQty]
GO
/****** Object:  View [dbo].[vwdespatchtoshop]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdespatchtoshop]'))
DROP VIEW [dbo].[vwdespatchtoshop]
GO
/****** Object:  StoredProcedure [dbo].[spLeadTimeForPurchase]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeadTimeForPurchase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLeadTimeForPurchase]
GO
/****** Object:  View [dbo].[vwcashsalestruncated]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashsalestruncated]'))
DROP VIEW [dbo].[vwcashsalestruncated]
GO
/****** Object:  StoredProcedure [dbo].[spDayendReportUserWise]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayendReportUserWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayendReportUserWise]
GO
/****** Object:  StoredProcedure [dbo].[spInventoryforcat_adv]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryforcat_adv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInventoryforcat_adv]
GO
/****** Object:  View [dbo].[vwsettlements]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsettlements]'))
DROP VIEW [dbo].[vwsettlements]
GO
/****** Object:  View [dbo].[vwshopdrcrinvandrecamount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopdrcrinvandrecamount]'))
DROP VIEW [dbo].[vwshopdrcrinvandrecamount]
GO
/****** Object:  View [dbo].[vwShopInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvoiceSettlementNo]'))
DROP VIEW [dbo].[vwShopInvoiceSettlementNo]
GO
/****** Object:  View [dbo].[vwShopInvSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvSettlementDetails]'))
DROP VIEW [dbo].[vwShopInvSettlementDetails]
GO
/****** Object:  View [dbo].[vwShopSplSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplSettlementDetails]'))
DROP VIEW [dbo].[vwShopSplSettlementDetails]
GO
/****** Object:  View [dbo].[vwRequestIssueDesptachArrival]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestIssueDesptachArrival]'))
DROP VIEW [dbo].[vwRequestIssueDesptachArrival]
GO
/****** Object:  View [dbo].[vwreexportsettlements]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportsettlements]'))
DROP VIEW [dbo].[vwreexportsettlements]
GO
/****** Object:  View [dbo].[vwpurchasebilltracking]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchasebilltracking]'))
DROP VIEW [dbo].[vwpurchasebilltracking]
GO
/****** Object:  View [dbo].[vwRecSettlementDetails]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRecSettlementDetails]'))
DROP VIEW [dbo].[vwRecSettlementDetails]
GO
/****** Object:  View [dbo].[vwgoodsreturnamount]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgoodsreturnamount]'))
DROP VIEW [dbo].[vwgoodsreturnamount]
GO
/****** Object:  View [dbo].[vwhqpaymentinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqpaymentinvandrecamount]'))
DROP VIEW [dbo].[vwhqpaymentinvandrecamount]
GO
/****** Object:  View [dbo].[vwHQAccPaidBills]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccPaidBills]'))
DROP VIEW [dbo].[vwHQAccPaidBills]
GO
/****** Object:  View [dbo].[vwHQDNSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQDNSettlementDetails]'))
DROP VIEW [dbo].[vwHQDNSettlementDetails]
GO
/****** Object:  View [dbo].[vwhqdrcrinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqdrcrinvandrecamount]'))
DROP VIEW [dbo].[vwhqdrcrinvandrecamount]
GO
/****** Object:  View [dbo].[vwadvancepaidpaymentsamounts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidpaymentsamounts]'))
DROP VIEW [dbo].[vwadvancepaidpaymentsamounts]
GO
/****** Object:  View [dbo].[vwadvancepaidreceiptsamounts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidreceiptsamounts]'))
DROP VIEW [dbo].[vwadvancepaidreceiptsamounts]
GO
/****** Object:  View [dbo].[vwspecialreturninvoicetosettle]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialreturninvoicetosettle]'))
DROP VIEW [dbo].[vwspecialreturninvoicetosettle]
GO
/****** Object:  View [dbo].[vwUtitilityBillSettlementNo]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUtitilityBillSettlementNo]'))
DROP VIEW [dbo].[vwUtitilityBillSettlementNo]
GO
/****** Object:  View [dbo].[vw_Report_service_SupplierLedger]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_service_SupplierLedger]'))
DROP VIEW [dbo].[vw_Report_service_SupplierLedger]
GO
/****** Object:  View [dbo].[vwAccInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccInvoiceSettlementNo]'))
DROP VIEW [dbo].[vwAccInvoiceSettlementNo]
GO
/****** Object:  View [dbo].[vwaccountinvsettledamount]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccountinvsettledamount]'))
DROP VIEW [dbo].[vwaccountinvsettledamount]
GO
/****** Object:  View [dbo].[vwadvancepaidCreditsAmounts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidCreditsAmounts]'))
DROP VIEW [dbo].[vwadvancepaidCreditsAmounts]
GO
/****** Object:  View [dbo].[vwariivaltoshoppendinglist]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwariivaltoshoppendinglist]'))
DROP VIEW [dbo].[vwariivaltoshoppendinglist]
GO
/****** Object:  View [dbo].[vwApartmentBillSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwApartmentBillSettlementNo]'))
DROP VIEW [dbo].[vwApartmentBillSettlementNo]
GO
/****** Object:  StoredProcedure [dbo].[spUlInvDespToShop]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvDespToShop]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlInvDespToShop]
GO
/****** Object:  StoredProcedure [dbo].[spUnsettledAccBills]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUnsettledAccBills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUnsettledAccBills]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopRecover]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopRecover]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopRecover]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownStock]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGodownStock]
GO
/****** Object:  StoredProcedure [dbo].[spRemineVendordueDate]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemineVendordueDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRemineVendordueDate]
GO
/****** Object:  View [dbo].[vwavgmonthlysale]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwavgmonthlysale]'))
DROP VIEW [dbo].[vwavgmonthlysale]
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemsold]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomeritemsold]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spcustomeritemsold]
GO
/****** Object:  View [dbo].[vwHQPurchaseBillsPaid]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPurchaseBillsPaid]'))
DROP VIEW [dbo].[vwHQPurchaseBillsPaid]
GO
/****** Object:  View [dbo].[vwshipmentwiseshopstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwiseshopstock]'))
DROP VIEW [dbo].[vwshipmentwiseshopstock]
GO
/****** Object:  View [dbo].[vwShopPurchaseBillsPaid]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPurchaseBillsPaid]'))
DROP VIEW [dbo].[vwShopPurchaseBillsPaid]
GO
/****** Object:  View [dbo].[vwCreditorAge]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditorAge]'))
DROP VIEW [dbo].[vwCreditorAge]
GO
/****** Object:  View [dbo].[vwShopAccInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopAccInvoiceSettlementNo]'))
DROP VIEW [dbo].[vwShopAccInvoiceSettlementNo]
GO
/****** Object:  View [dbo].[vwsalesSumYearWise]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesSumYearWise]'))
DROP VIEW [dbo].[vwsalesSumYearWise]
GO
/****** Object:  View [dbo].[vwshipmentwisegodownstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwisegodownstock]'))
DROP VIEW [dbo].[vwshipmentwisegodownstock]
GO
/****** Object:  View [dbo].[vwPOBillCostingDespatchArrival]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPOBillCostingDespatchArrival]'))
DROP VIEW [dbo].[vwPOBillCostingDespatchArrival]
GO
/****** Object:  View [dbo].[vwSellingPrice]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingPrice]'))
DROP VIEW [dbo].[vwSellingPrice]
GO
/****** Object:  View [dbo].[vwSalesImportProdWise]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesImportProdWise]'))
DROP VIEW [dbo].[vwSalesImportProdWise]
GO
/****** Object:  View [dbo].[vwSalesImportProdWiseGSTSeparately]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesImportProdWiseGSTSeparately]'))
DROP VIEW [dbo].[vwSalesImportProdWiseGSTSeparately]
GO
/****** Object:  View [dbo].[vwDebitNoteSettlementNo]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitNoteSettlementNo]'))
DROP VIEW [dbo].[vwDebitNoteSettlementNo]
GO
/****** Object:  View [dbo].[vwBookServiceSettlementNo]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBookServiceSettlementNo]'))
DROP VIEW [dbo].[vwBookServiceSettlementNo]
GO
/****** Object:  View [dbo].[vwbookservicesettlements]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesettlements]'))
DROP VIEW [dbo].[vwbookservicesettlements]
GO
/****** Object:  View [dbo].[vwDailySalesCollection_shopwise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection_shopwise]'))
DROP VIEW [dbo].[vwDailySalesCollection_shopwise]
GO
/****** Object:  View [dbo].[vwDailySalesCollection_shopwiseGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection_shopwiseGSTSeparately]'))
DROP VIEW [dbo].[vwDailySalesCollection_shopwiseGSTSeparately]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionDet]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDet]'))
DROP VIEW [dbo].[vwDailySalesCollectionDet]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionDetGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDetGSTSeparately]'))
DROP VIEW [dbo].[vwDailySalesCollectionDetGSTSeparately]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately]'))
DROP VIEW [dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionGSTSeparately]'))
DROP VIEW [dbo].[vwDailySalesCollectionGSTSeparately]
GO
/****** Object:  View [dbo].[vwTotalTax]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotalTax]'))
DROP VIEW [dbo].[vwTotalTax]
GO
/****** Object:  View [dbo].[vwSupplierLedger]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSupplierLedger]'))
DROP VIEW [dbo].[vwSupplierLedger]
GO
/****** Object:  StoredProcedure [dbo].[spSalesPersonInvandSettled]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesPersonInvandSettled]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesPersonInvandSettled]
GO
/****** Object:  View [dbo].[VwItemSalesGrouped]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwItemSalesGrouped]'))
DROP VIEW [dbo].[VwItemSalesGrouped]
GO
/****** Object:  View [dbo].[vwinvoices]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoices]'))
DROP VIEW [dbo].[vwinvoices]
GO
/****** Object:  View [dbo].[vwShopSplInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplInvoiceSettlementNo]'))
DROP VIEW [dbo].[vwShopSplInvoiceSettlementNo]
GO
/****** Object:  View [dbo].[vwIssueNote]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwIssueNote]'))
DROP VIEW [dbo].[vwIssueNote]
GO
/****** Object:  View [dbo].[vwissuenoteGodown]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwissuenoteGodown]'))
DROP VIEW [dbo].[vwissuenoteGodown]
GO
/****** Object:  View [dbo].[vwInterdivBillSettlementNo]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInterdivBillSettlementNo]'))
DROP VIEW [dbo].[vwInterdivBillSettlementNo]
GO
/****** Object:  View [dbo].[vwItemSalesRate]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSalesRate]'))
DROP VIEW [dbo].[vwItemSalesRate]
GO
/****** Object:  View [dbo].[vwItemDetailedSales]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailedSales]'))
DROP VIEW [dbo].[vwItemDetailedSales]
GO
/****** Object:  StoredProcedure [dbo].[spItemDetailedSalesForecastment]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemDetailedSalesForecastment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spItemDetailedSalesForecastment]
GO
/****** Object:  View [dbo].[vwItemDetailedSalesForecastment]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailedSalesForecastment]'))
DROP VIEW [dbo].[vwItemDetailedSalesForecastment]
GO
/****** Object:  StoredProcedure [dbo].[spSeasonalSalesPrediction]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSeasonalSalesPrediction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSeasonalSalesPrediction]
GO
/****** Object:  View [dbo].[vwItemsoldCustomerwise]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsoldCustomerwise]'))
DROP VIEW [dbo].[vwItemsoldCustomerwise]
GO
/****** Object:  View [dbo].[vwItemShipmentPrice]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemShipmentPrice]'))
DROP VIEW [dbo].[vwItemShipmentPrice]
GO
/****** Object:  View [dbo].[vwTableBlock]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTableBlock]'))
DROP VIEW [dbo].[vwTableBlock]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMargin]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMargin]'))
DROP VIEW [dbo].[vwDailySalesCollectionWithMargin]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginAsOn10062011]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginAsOn10062011]'))
DROP VIEW [dbo].[vwDailySalesCollectionWithMarginAsOn10062011]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginDet]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginDet]'))
DROP VIEW [dbo].[vwDailySalesCollectionWithMarginDet]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginDetWithOutGST]'))
DROP VIEW [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST]
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginGSTSeparately]'))
DROP VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately]
GO
/****** Object:  View [dbo].[vwDailySalesUserWise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesUserWise]'))
DROP VIEW [dbo].[vwDailySalesUserWise]
GO
/****** Object:  View [dbo].[vwBillSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillSettlementNo]'))
DROP VIEW [dbo].[vwBillSettlementNo]
GO
/****** Object:  View [dbo].[vwposBillsettlementpay]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposBillsettlementpay]'))
DROP VIEW [dbo].[vwposBillsettlementpay]
GO
/****** Object:  View [dbo].[vwFANDBInvoice]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwFANDBInvoice]'))
DROP VIEW [dbo].[vwFANDBInvoice]
GO
/****** Object:  View [dbo].[vwSalesMarginAndPerc]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesMarginAndPerc]'))
DROP VIEW [dbo].[vwSalesMarginAndPerc]
GO
/****** Object:  View [dbo].[vwSalesMarginAndPercGSTSeparately]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesMarginAndPercGSTSeparately]'))
DROP VIEW [dbo].[vwSalesMarginAndPercGSTSeparately]
GO
/****** Object:  View [dbo].[vwsalesandcostvalue]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesandcostvalue]'))
DROP VIEW [dbo].[vwsalesandcostvalue]
GO
/****** Object:  View [dbo].[VwpendingControlAccTrans]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwpendingControlAccTrans]'))
DROP VIEW [dbo].[VwpendingControlAccTrans]
GO
/****** Object:  View [dbo].[vwPopulateUserSignatures]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPopulateUserSignatures]'))
DROP VIEW [dbo].[vwPopulateUserSignatures]
GO
/****** Object:  View [dbo].[vwSalesRegister]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesRegister]'))
DROP VIEW [dbo].[vwSalesRegister]
GO
/****** Object:  View [dbo].[vwshipmentcostprice]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentcostprice]'))
DROP VIEW [dbo].[vwshipmentcostprice]
GO
/****** Object:  View [dbo].[vwCreditNoteSettlementNo]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditNoteSettlementNo]'))
DROP VIEW [dbo].[vwCreditNoteSettlementNo]
GO
/****** Object:  View [dbo].[vwConfirmedLocalPurchaseBill]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwConfirmedLocalPurchaseBill]'))
DROP VIEW [dbo].[vwConfirmedLocalPurchaseBill]
GO
/****** Object:  View [dbo].[vwCosting]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCosting]'))
DROP VIEW [dbo].[vwCosting]
GO
/****** Object:  View [dbo].[vwmonthwiseproductsales]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmonthwiseproductsales]'))
DROP VIEW [dbo].[vwmonthwiseproductsales]
GO
/****** Object:  View [dbo].[vwpurchasetransflow]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchasetransflow]'))
DROP VIEW [dbo].[vwpurchasetransflow]
GO
/****** Object:  View [dbo].[vwPurchaseOrderVendorWise]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderVendorWise]'))
DROP VIEW [dbo].[vwPurchaseOrderVendorWise]
GO
/****** Object:  View [dbo].[vwPurchaseOrderVendorWisePre]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderVendorWisePre]'))
DROP VIEW [dbo].[vwPurchaseOrderVendorWisePre]
GO
/****** Object:  View [dbo].[vwrebatePO]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrebatePO]'))
DROP VIEW [dbo].[vwrebatePO]
GO
/****** Object:  View [dbo].[vwreceiptlisting]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptlisting]'))
DROP VIEW [dbo].[vwreceiptlisting]
GO
/****** Object:  View [dbo].[vwReceiptSettlementNo]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptSettlementNo]'))
DROP VIEW [dbo].[vwReceiptSettlementNo]
GO
/****** Object:  View [dbo].[vwHqPurchasePayments]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchasePayments]'))
DROP VIEW [dbo].[vwHqPurchasePayments]
GO
/****** Object:  View [dbo].[vwLPBillVendrPayments]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLPBillVendrPayments]'))
DROP VIEW [dbo].[vwLPBillVendrPayments]
GO
/****** Object:  View [dbo].[vwshoppurchasePayments]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchasePayments]'))
DROP VIEW [dbo].[vwshoppurchasePayments]
GO
/****** Object:  View [dbo].[vwshoppurchasePayments_OLD]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchasePayments_OLD]'))
DROP VIEW [dbo].[vwshoppurchasePayments_OLD]
GO
/****** Object:  View [dbo].[vwshopsaleinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopsaleinvoicereceipt]'))
DROP VIEW [dbo].[vwshopsaleinvoicereceipt]
GO
/****** Object:  View [dbo].[vwImportRegister]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwImportRegister]'))
DROP VIEW [dbo].[vwImportRegister]
GO
/****** Object:  StoredProcedure [dbo].[spDailyItemSales]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailyItemSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailyItemSales]
GO
/****** Object:  StoredProcedure [dbo].[spDailyItemSalesFandB]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailyItemSalesFandB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailyItemSalesFandB]
GO
/****** Object:  View [dbo].[vwHQPBillVendrPayments]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPBillVendrPayments]'))
DROP VIEW [dbo].[vwHQPBillVendrPayments]
GO
/****** Object:  View [dbo].[vwhqposbillsettlementdetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqposbillsettlementdetails]'))
DROP VIEW [dbo].[vwhqposbillsettlementdetails]
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecastingMailAlert]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReorderLevelForecastingMailAlert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReorderLevelForecastingMailAlert]
GO
/****** Object:  View [dbo].[vwAverageSalesQtyItemWise]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAverageSalesQtyItemWise]'))
DROP VIEW [dbo].[vwAverageSalesQtyItemWise]
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWiseForecasting]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOutCompanyWiseForecasting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockOutCompanyWiseForecasting]
GO
/****** Object:  View [dbo].[vwAverageSalesQtyOfAllShopsItemWise]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAverageSalesQtyOfAllShopsItemWise]'))
DROP VIEW [dbo].[vwAverageSalesQtyOfAllShopsItemWise]
GO
/****** Object:  StoredProcedure [dbo].[spRemoveTillHeader]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemoveTillHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRemoveTillHeader]
GO
/****** Object:  StoredProcedure [dbo].[spRebateApproval]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebateApproval]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRebateApproval]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetvariance]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetvariance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetvariance]
GO
/****** Object:  StoredProcedure [dbo].[sPBasketSalesAnalysis]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sPBasketSalesAnalysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sPBasketSalesAnalysis]
GO
/****** Object:  StoredProcedure [dbo].[spUlSplInv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlSplInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlSplInv]
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItems]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAlreadyIssuedItems]'))
DROP VIEW [dbo].[vwAlreadyIssuedItems]
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItemsReport]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAlreadyIssuedItemsReport]'))
DROP VIEW [dbo].[vwAlreadyIssuedItemsReport]
GO
/****** Object:  View [dbo].[vwAnalysisItems]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAnalysisItems]'))
DROP VIEW [dbo].[vwAnalysisItems]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillBalance]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateTillBalance]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPayments]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersPayments]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersReceipts]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersReceipts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersReceipts]
GO
/****** Object:  View [dbo].[vwadvancepaidDebitsAmounts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidDebitsAmounts]'))
DROP VIEW [dbo].[vwadvancepaidDebitsAmounts]
GO
/****** Object:  View [dbo].[vwAdvancePaidPayments]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAdvancePaidPayments]'))
DROP VIEW [dbo].[vwAdvancePaidPayments]
GO
/****** Object:  View [dbo].[vwVendorSettlementDetails]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSettlementDetails]'))
DROP VIEW [dbo].[vwVendorSettlementDetails]
GO
/****** Object:  View [dbo].[vwAccVendrPayments]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccVendrPayments]'))
DROP VIEW [dbo].[vwAccVendrPayments]
GO
/****** Object:  View [dbo].[vwaccBillsettlementpay]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccBillsettlementpay]'))
DROP VIEW [dbo].[vwaccBillsettlementpay]
GO
/****** Object:  View [dbo].[vwaccbillvs]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccbillvs]'))
DROP VIEW [dbo].[vwaccbillvs]
GO
/****** Object:  View [dbo].[vwspecialinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvoicereceipt]'))
DROP VIEW [dbo].[vwspecialinvoicereceipt]
GO
/****** Object:  View [dbo].[vwadvancepaidreceipts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidreceipts]'))
DROP VIEW [dbo].[vwadvancepaidreceipts]
GO
/****** Object:  View [dbo].[vwHQinvoicereceipt]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQinvoicereceipt]'))
DROP VIEW [dbo].[vwHQinvoicereceipt]
GO
/****** Object:  View [dbo].[vwHQIssueDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQIssueDetails]'))
DROP VIEW [dbo].[vwHQIssueDetails]
GO
/****** Object:  View [dbo].[vwHQLCPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQLCPaidDetails]'))
DROP VIEW [dbo].[vwHQLCPaidDetails]
GO
/****** Object:  View [dbo].[vwHQAccPayments]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccPayments]'))
DROP VIEW [dbo].[vwHQAccPayments]
GO
/****** Object:  View [dbo].[vwHQAccinterdevbillPayments]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccinterdevbillPayments]'))
DROP VIEW [dbo].[vwHQAccinterdevbillPayments]
GO
/****** Object:  View [dbo].[vwItemSplitCosting]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSplitCosting]'))
DROP VIEW [dbo].[vwItemSplitCosting]
GO
/****** Object:  View [dbo].[vwHQPBillPaymentDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPBillPaymentDetails]'))
DROP VIEW [dbo].[vwHQPBillPaymentDetails]
GO
/****** Object:  View [dbo].[vwhqpbillsettlementdetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqpbillsettlementdetails]'))
DROP VIEW [dbo].[vwhqpbillsettlementdetails]
GO
/****** Object:  View [dbo].[vwHQBillPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQBillPaidDetails]'))
DROP VIEW [dbo].[vwHQBillPaidDetails]
GO
/****** Object:  View [dbo].[vwHQCNSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQCNSettlementDetails]'))
DROP VIEW [dbo].[vwHQCNSettlementDetails]
GO
/****** Object:  View [dbo].[vwPayments]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayments]'))
DROP VIEW [dbo].[vwPayments]
GO
/****** Object:  View [dbo].[vwpaymentsusedincoasting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentsusedincoasting]'))
DROP VIEW [dbo].[vwpaymentsusedincoasting]
GO
/****** Object:  View [dbo].[vwpaymentsusedincosting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentsusedincosting]'))
DROP VIEW [dbo].[vwpaymentsusedincosting]
GO
/****** Object:  View [dbo].[vwHQAccBillPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccBillPaidDetails]'))
DROP VIEW [dbo].[vwHQAccBillPaidDetails]
GO
/****** Object:  View [dbo].[vwPurchaseBillSettlementNo]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillSettlementNo]'))
DROP VIEW [dbo].[vwPurchaseBillSettlementNo]
GO
/****** Object:  View [dbo].[vwreexportvendorsettle]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportvendorsettle]'))
DROP VIEW [dbo].[vwreexportvendorsettle]
GO
/****** Object:  View [dbo].[vwReceiptVoucherDetails]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptVoucherDetails]'))
DROP VIEW [dbo].[vwReceiptVoucherDetails]
GO
/****** Object:  View [dbo].[vwpaymentvoucher]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentvoucher]'))
DROP VIEW [dbo].[vwpaymentvoucher]
GO
/****** Object:  View [dbo].[vwshopvendordebitnotes]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopvendordebitnotes]'))
DROP VIEW [dbo].[vwshopvendordebitnotes]
GO
/****** Object:  View [dbo].[vwServiceInvoice]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoice]'))
DROP VIEW [dbo].[vwServiceInvoice]
GO
/****** Object:  View [dbo].[vwRequestremark]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestremark]'))
DROP VIEW [dbo].[vwRequestremark]
GO
/****** Object:  View [dbo].[vwSalesAnalysisByItem]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByItem]'))
DROP VIEW [dbo].[vwSalesAnalysisByItem]
GO
/****** Object:  StoredProcedure [dbo].[spGetPurchaseRequestStatus]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetPurchaseRequestStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetPurchaseRequestStatus]
GO
/****** Object:  StoredProcedure [dbo].[spAnalysisofItemSalesByWeek]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAnalysisofItemSalesByWeek]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAnalysisofItemSalesByWeek]
GO
/****** Object:  StoredProcedure [dbo].[spAnalysisofItemSalesByWeekGSTSeparately]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAnalysisofItemSalesByWeekGSTSeparately]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAnalysisofItemSalesByWeekGSTSeparately]
GO
/****** Object:  StoredProcedure [dbo].[spAdvancePaymentsNotSettled]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAdvancePaymentsNotSettled]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAdvancePaymentsNotSettled]
GO
/****** Object:  StoredProcedure [dbo].[spAssetDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssetDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAssetDetails]
GO
/****** Object:  View [dbo].[vwcashtallied]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashtallied]'))
DROP VIEW [dbo].[vwcashtallied]
GO
/****** Object:  View [dbo].[vwCollectedSalesTax]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectedSalesTax]'))
DROP VIEW [dbo].[vwCollectedSalesTax]
GO
/****** Object:  View [dbo].[vwCollectionBrandWise]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectionBrandWise]'))
DROP VIEW [dbo].[vwCollectionBrandWise]
GO
/****** Object:  View [dbo].[vwcollectionbrandwisegraph]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcollectionbrandwisegraph]'))
DROP VIEW [dbo].[vwcollectionbrandwisegraph]
GO
/****** Object:  View [dbo].[vwCollectionCategoryWise]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectionCategoryWise]'))
DROP VIEW [dbo].[vwCollectionCategoryWise]
GO
/****** Object:  View [dbo].[vwcashreceipt]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashreceipt]'))
DROP VIEW [dbo].[vwcashreceipt]
GO
/****** Object:  View [dbo].[vwCAshSales]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales]'))
DROP VIEW [dbo].[vwCAshSales]
GO
/****** Object:  View [dbo].[vwCAshSales_BackUp_22032011]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_BackUp_22032011]'))
DROP VIEW [dbo].[vwCAshSales_BackUp_22032011]
GO
/****** Object:  View [dbo].[vwCAshSales_Sonee]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_Sonee]'))
DROP VIEW [dbo].[vwCAshSales_Sonee]
GO
/****** Object:  View [dbo].[vwCAshSales_woutsplinvoicecreditsale]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_woutsplinvoicecreditsale]'))
DROP VIEW [dbo].[vwCAshSales_woutsplinvoicecreditsale]
GO
/****** Object:  View [dbo].[vwCAshSalesAsOn07062011]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesAsOn07062011]'))
DROP VIEW [dbo].[vwCAshSalesAsOn07062011]
GO
/****** Object:  View [dbo].[vwCAshSalesDet]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDet]'))
DROP VIEW [dbo].[vwCAshSalesDet]
GO
/****** Object:  View [dbo].[vwCAshSalesDetAsOn15062011]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDetAsOn15062011]'))
DROP VIEW [dbo].[vwCAshSalesDetAsOn15062011]
GO
/****** Object:  View [dbo].[vwCAshSalesDetGSTSeprately]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDetGSTSeprately]'))
DROP VIEW [dbo].[vwCAshSalesDetGSTSeprately]
GO
/****** Object:  View [dbo].[vwCAshSalesGSTSeparately]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesGSTSeparately]'))
DROP VIEW [dbo].[vwCAshSalesGSTSeparately]
GO
/****** Object:  StoredProcedure [dbo].[spLedgersPreview]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLedgersPreview]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLedgersPreview]
GO
/****** Object:  View [dbo].[vwdespatchestogodown]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdespatchestogodown]'))
DROP VIEW [dbo].[vwdespatchestogodown]
GO
/****** Object:  View [dbo].[vwdummyreceipts]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyreceipts]'))
DROP VIEW [dbo].[vwdummyreceipts]
GO
/****** Object:  View [dbo].[vwCustomerSettlementHeader]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSettlementHeader]'))
DROP VIEW [dbo].[vwCustomerSettlementHeader]
GO
/****** Object:  View [dbo].[vwCustomerSales]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSales]'))
DROP VIEW [dbo].[vwCustomerSales]
GO
/****** Object:  View [dbo].[vwCustomerSalesByitem]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesByitem]'))
DROP VIEW [dbo].[vwCustomerSalesByitem]
GO
/****** Object:  View [dbo].[vwCustomerSalesmonthwise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesmonthwise]'))
DROP VIEW [dbo].[vwCustomerSalesmonthwise]
GO
/****** Object:  StoredProcedure [dbo].[spFastMovingItem]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFastMovingItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFastMovingItem]
GO
/****** Object:  View [dbo].[vwUnConfirmedTransactions]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnConfirmedTransactions]'))
DROP VIEW [dbo].[vwUnConfirmedTransactions]
GO
/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnPostedShopTransactions]'))
DROP VIEW [dbo].[vwUnPostedShopTransactions]
GO
/****** Object:  StoredProcedure [dbo].[SpPopulateAccountsBills]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpPopulateAccountsBills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpPopulateAccountsBills]
GO
/****** Object:  View [dbo].[vwGodownIssuedItems]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownIssuedItems]'))
DROP VIEW [dbo].[vwGodownIssuedItems]
GO
/****** Object:  View [dbo].[vwadvancepaidReturnAmounts]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidReturnAmounts]'))
DROP VIEW [dbo].[vwadvancepaidReturnAmounts]
GO
/****** Object:  StoredProcedure [dbo].[spFixedAssetRpt]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedAssetRpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFixedAssetRpt]
GO
/****** Object:  StoredProcedure [dbo].[sp_FBCashSummary]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_FBCashSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_FBCashSummary]
GO
/****** Object:  View [dbo].[vwshopcreditinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopcreditinvoicereceipt]'))
DROP VIEW [dbo].[vwshopcreditinvoicereceipt]
GO
/****** Object:  View [dbo].[vwlocalpurchasebill]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlocalpurchasebill]'))
DROP VIEW [dbo].[vwlocalpurchasebill]
GO
/****** Object:  View [dbo].[vwLocalPurchaseBillSettlementNo]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseBillSettlementNo]'))
DROP VIEW [dbo].[vwLocalPurchaseBillSettlementNo]
GO
/****** Object:  View [dbo].[vwLocalPurchaseCosting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseCosting]'))
DROP VIEW [dbo].[vwLocalPurchaseCosting]
GO
/****** Object:  View [dbo].[vwShopItemSalesDecimalQty]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesDecimalQty]'))
DROP VIEW [dbo].[vwShopItemSalesDecimalQty]
GO
/****** Object:  StoredProcedure [dbo].[spGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[spReverseGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseGodownTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReverseGodownTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[spGITDifference_GL]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGITDifference_GL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGITDifference_GL]
GO
/****** Object:  View [dbo].[vwShopItemSalesFandB]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesFandB]'))
DROP VIEW [dbo].[vwShopItemSalesFandB]
GO
/****** Object:  View [dbo].[vwShopItemSalesforSeasonalPrediction]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesforSeasonalPrediction]'))
DROP VIEW [dbo].[vwShopItemSalesforSeasonalPrediction]
GO
/****** Object:  View [dbo].[vwShopItemSalesGstSeparately]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesGstSeparately]'))
DROP VIEW [dbo].[vwShopItemSalesGstSeparately]
GO
/****** Object:  View [dbo].[vwshopitemsalesWithActualPrice]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemsalesWithActualPrice]'))
DROP VIEW [dbo].[vwshopitemsalesWithActualPrice]
GO
/****** Object:  View [dbo].[vwShopItemSalesWithCustomerAndPack]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesWithCustomerAndPack]'))
DROP VIEW [dbo].[vwShopItemSalesWithCustomerAndPack]
GO
/****** Object:  View [dbo].[vwShopItemSales]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSales]'))
DROP VIEW [dbo].[vwShopItemSales]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownVerification]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownVerification]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownWriteOff]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownWriteOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownWriteOff]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGTransGodownStock]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGTransGodownStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGTransGodownStock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetdepreciation]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetdepreciation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAssetdepreciation]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetDisposal]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetDisposal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAssetDisposal]
GO
/****** Object:  View [dbo].[vwForeignShipWiseCostPrice]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwForeignShipWiseCostPrice]'))
DROP VIEW [dbo].[vwForeignShipWiseCostPrice]
GO
/****** Object:  StoredProcedure [dbo].[spGodownLocationTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownLocationTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownLocationTotalStockVerification]
GO
/****** Object:  View [dbo].[vwKeyPerformanceIndexes]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwKeyPerformanceIndexes]'))
DROP VIEW [dbo].[vwKeyPerformanceIndexes]
GO
/****** Object:  StoredProcedure [dbo].[sp_FandBCancelEdit]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_FandBCancelEdit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_FandBCancelEdit]
GO
/****** Object:  View [dbo].[vwLcReferredInPayments]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLcReferredInPayments]'))
DROP VIEW [dbo].[vwLcReferredInPayments]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockExchange]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockExchange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockExchange]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockGReturn]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockGReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockGReturn]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockLP]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockLP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockLP]
GO
/****** Object:  View [dbo].[vwfixedassetbills]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfixedassetbills]'))
DROP VIEW [dbo].[vwfixedassetbills]
GO
/****** Object:  View [dbo].[vwfixedassetsconvertedfromstock]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfixedassetsconvertedfromstock]'))
DROP VIEW [dbo].[vwfixedassetsconvertedfromstock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockSplInvRet]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockSplInvRet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockSplInvRet]
GO
/****** Object:  View [dbo].[vwshopSalesAccountWise]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopSalesAccountWise]'))
DROP VIEW [dbo].[vwshopSalesAccountWise]
GO
/****** Object:  View [dbo].[vwshopCreditInvoice]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopCreditInvoice]'))
DROP VIEW [dbo].[vwshopCreditInvoice]
GO
/****** Object:  View [dbo].[vwshopservicesales]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopservicesales]'))
DROP VIEW [dbo].[vwshopservicesales]
GO
/****** Object:  StoredProcedure [dbo].[SP_MONTHLYCREDIT]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MONTHLYCREDIT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MONTHLYCREDIT]
GO
/****** Object:  StoredProcedure [dbo].[sp_audittool_ledger]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_audittool_ledger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_audittool_ledger]
GO
/****** Object:  StoredProcedure [dbo].[sp_audittool_trans_details]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_audittool_trans_details]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_audittool_trans_details]
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedBillDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SelectedBillDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SelectedBillDetails]
GO
/****** Object:  View [dbo].[TestView]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TestView]'))
DROP VIEW [dbo].[TestView]
GO
/****** Object:  View [dbo].[vwGdnBinCardBadQtySummary]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardBadQtySummary]'))
DROP VIEW [dbo].[vwGdnBinCardBadQtySummary]
GO
/****** Object:  View [dbo].[vwGodownIssueArrivalLocationWise]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownIssueArrivalLocationWise]'))
DROP VIEW [dbo].[vwGodownIssueArrivalLocationWise]
GO
/****** Object:  View [dbo].[vwGodownDamageClearing]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownDamageClearing]'))
DROP VIEW [dbo].[vwGodownDamageClearing]
GO
/****** Object:  View [dbo].[vwGetSlNoWarrantyDetails]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGetSlNoWarrantyDetails]'))
DROP VIEW [dbo].[vwGetSlNoWarrantyDetails]
GO
/****** Object:  StoredProcedure [dbo].[spFixedAssetopeningBalance]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedAssetopeningBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFixedAssetopeningBalance]
GO
/****** Object:  View [dbo].[vwCustomerSalesQtyWise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesQtyWise]'))
DROP VIEW [dbo].[vwCustomerSalesQtyWise]
GO
/****** Object:  View [dbo].[vwCashInvoices]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCashInvoices]'))
DROP VIEW [dbo].[vwCashInvoices]
GO
/****** Object:  View [dbo].[vwDailyCounterSales]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailyCounterSales]'))
DROP VIEW [dbo].[vwDailyCounterSales]
GO
/****** Object:  View [dbo].[vwDiscountGiven]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountGiven]'))
DROP VIEW [dbo].[vwDiscountGiven]
GO
/****** Object:  View [dbo].[vwDespatchArrivalDiff]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchArrivalDiff]'))
DROP VIEW [dbo].[vwDespatchArrivalDiff]
GO
/****** Object:  View [dbo].[vwGodownStockVerification]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownStockVerification]'))
DROP VIEW [dbo].[vwGodownStockVerification]
GO
/****** Object:  View [dbo].[vwGodownToGodownTransfer]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownToGodownTransfer]'))
DROP VIEW [dbo].[vwGodownToGodownTransfer]
GO
/****** Object:  View [dbo].[vwGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownTotalStockVerification]'))
DROP VIEW [dbo].[vwGodownTotalStockVerification]
GO
/****** Object:  View [dbo].[vwediPO]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwediPO]'))
DROP VIEW [dbo].[vwediPO]
GO
/****** Object:  View [dbo].[vwExchangeSales]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwExchangeSales]'))
DROP VIEW [dbo].[vwExchangeSales]
GO
/****** Object:  View [dbo].[vwgodownlocationstock]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownlocationstock]'))
DROP VIEW [dbo].[vwgodownlocationstock]
GO
/****** Object:  View [dbo].[vwGodownLocationWiseStock]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownLocationWiseStock]'))
DROP VIEW [dbo].[vwGodownLocationWiseStock]
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsBillFullyDelivered]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_IsBillFullyDelivered]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_IsBillFullyDelivered]
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsInvoiceFullyDelivered]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_IsInvoiceFullyDelivered]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_IsInvoiceFullyDelivered]
GO
/****** Object:  View [dbo].[vwchartofaccounts]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwchartofaccounts]'))
DROP VIEW [dbo].[vwchartofaccounts]
GO
/****** Object:  StoredProcedure [dbo].[spAssetDetailsuptoDate]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssetDetailsuptoDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAssetDetailsuptoDate]
GO
/****** Object:  StoredProcedure [dbo].[spComplimentaryItemValue]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spComplimentaryItemValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spComplimentaryItemValue]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDepNew]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDepNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheetDepNew]
GO
/****** Object:  StoredProcedure [dbo].[spCommissiONInvoice]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCommissiONInvoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCommissiONInvoice]
GO
/****** Object:  StoredProcedure [dbo].[spCommissiONInvoiceItemDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCommissiONInvoiceItemDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCommissiONInvoiceItemDetails]
GO
/****** Object:  StoredProcedure [dbo].[spDaySalesAndBankPosition]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDaySalesAndBankPosition]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDaySalesAndBankPosition]
GO
/****** Object:  StoredProcedure [dbo].[spDayWiseAvgQtySalesRpt]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDayWiseAvgQtySalesRpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDayWiseAvgQtySalesRpt]
GO
/****** Object:  View [dbo].[vwShopgrn]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopgrn]'))
DROP VIEW [dbo].[vwShopgrn]
GO
/****** Object:  View [dbo].[vwPosServiceInvoiceDetails]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosServiceInvoiceDetails]'))
DROP VIEW [dbo].[vwPosServiceInvoiceDetails]
GO
/****** Object:  View [dbo].[vwPrePurchaseOrderTracking3]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPrePurchaseOrderTracking3]'))
DROP VIEW [dbo].[vwPrePurchaseOrderTracking3]
GO
/****** Object:  View [dbo].[vwPurchaseBillDetail]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetail]'))
DROP VIEW [dbo].[vwPurchaseBillDetail]
GO
/****** Object:  View [dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]'))
DROP VIEW [dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]
GO
/****** Object:  View [dbo].[vwPurchaseBillDetailGSTSeparately]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetailGSTSeparately]'))
DROP VIEW [dbo].[vwPurchaseBillDetailGSTSeparately]
GO
/****** Object:  View [dbo].[vwReceiptVoucherHeader]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptVoucherHeader]'))
DROP VIEW [dbo].[vwReceiptVoucherHeader]
GO
/****** Object:  View [dbo].[vwRefundedSalesTax]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRefundedSalesTax]'))
DROP VIEW [dbo].[vwRefundedSalesTax]
GO
/****** Object:  View [dbo].[vwPurchaseBillPackQty]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillPackQty]'))
DROP VIEW [dbo].[vwPurchaseBillPackQty]
GO
/****** Object:  View [dbo].[vwguraranteesales]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwguraranteesales]'))
DROP VIEW [dbo].[vwguraranteesales]
GO
/****** Object:  View [dbo].[vwpaymentswithcontrolaccs]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentswithcontrolaccs]'))
DROP VIEW [dbo].[vwpaymentswithcontrolaccs]
GO
/****** Object:  View [dbo].[vwitemsplitDetail]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemsplitDetail]'))
DROP VIEW [dbo].[vwitemsplitDetail]
GO
/****** Object:  View [dbo].[vwShopInvoices]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvoices]'))
DROP VIEW [dbo].[vwShopInvoices]
GO
/****** Object:  View [dbo].[vwAccountsInvolved]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccountsInvolved]'))
DROP VIEW [dbo].[vwAccountsInvolved]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReserveItem]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReserveItem]'))
DROP VIEW [dbo].[vwSpecialInvoiceReserveItem]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReturn]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReturn]'))
DROP VIEW [dbo].[vwSpecialInvoiceReturn]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReturnReport]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReturnReport]'))
DROP VIEW [dbo].[vwSpecialInvoiceReturnReport]
GO
/****** Object:  View [dbo].[vwspecialinvoiceamount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvoiceamount]'))
DROP VIEW [dbo].[vwspecialinvoiceamount]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceDetails]'))
DROP VIEW [dbo].[vwSpecialInvoiceDetails]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceDiffGodown]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceDiffGodown]'))
DROP VIEW [dbo].[vwSpecialInvoiceDiffGodown]
GO
/****** Object:  View [dbo].[vwSpecialInvoiceItemStatus]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceItemStatus]'))
DROP VIEW [dbo].[vwSpecialInvoiceItemStatus]
GO
/****** Object:  View [dbo].[vwSpecialInvoicePopulate]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoicePopulate]'))
DROP VIEW [dbo].[vwSpecialInvoicePopulate]
GO
/****** Object:  View [dbo].[vwTransferOUT]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOUT]'))
DROP VIEW [dbo].[vwTransferOUT]
GO
/****** Object:  View [dbo].[vwVendorSettlementHeader]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSettlementHeader]'))
DROP VIEW [dbo].[vwVendorSettlementHeader]
GO
/****** Object:  StoredProcedure [dbo].[dataExist]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dataExist]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[dataExist]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgerspandcCosting]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgerspandcCosting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgerspandcCosting]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillStatus]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateTillStatus]
GO
/****** Object:  View [dbo].[vwAssetDisposal]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetDisposal]'))
DROP VIEW [dbo].[vwAssetDisposal]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopPurchase]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopPurchase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopPurchase]
GO
/****** Object:  StoredProcedure [dbo].[spULshopServiceInv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopServiceInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopServiceInv]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownItemSplit]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownItemSplit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownItemSplit]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownDamageClearing]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownDamageClearing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownDamageClearing]
GO
/****** Object:  StoredProcedure [dbo].[spUlInvGdnToGdnTransfer]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvGdnToGdnTransfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlInvGdnToGdnTransfer]
GO
/****** Object:  StoredProcedure [dbo].[spULinvGoodsArrival]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULinvGoodsArrival]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULinvGoodsArrival]
GO
/****** Object:  StoredProcedure [dbo].[spulInvAssetConv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulInvAssetConv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulInvAssetConv]
GO
/****** Object:  StoredProcedure [dbo].[spUlInvSv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvSv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlInvSv]
GO
/****** Object:  StoredProcedure [dbo].[spULInvSWO]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvSWO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULInvSWO]
GO
/****** Object:  StoredProcedure [dbo].[spULExchange]    Script Date: 10/06/2012 14:17:32 ******/
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
/****** Object:  StoredProcedure [dbo].[spulGodownPurchReturn]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulGodownPurchReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulGodownPurchReturn]
GO
/****** Object:  StoredProcedure [dbo].[spUL_FandB_Bill]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUL_FandB_Bill]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUL_FandB_Bill]
GO
/****** Object:  StoredProcedure [dbo].[spULShopGR]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopGR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopGR]
GO
/****** Object:  StoredProcedure [dbo].[spulShopConsumptionReturn]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopConsumptionReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulShopConsumptionReturn]
GO
/****** Object:  StoredProcedure [dbo].[spBankUsed]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankUsed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankUsed]
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]
GO
/****** Object:  StoredProcedure [dbo].[spShopTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]
GO
/****** Object:  StoredProcedure [dbo].[spRemoveTillDetails]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemoveTillDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRemoveTillDetails]
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]
GO
/****** Object:  StoredProcedure [dbo].[spShopSalesByHour]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopSalesByHour]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopSalesByHour]
GO
/****** Object:  View [dbo].[vwBasketSales]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBasketSales]'))
DROP VIEW [dbo].[vwBasketSales]
GO
/****** Object:  View [dbo].[vwBillOtherCharges]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillOtherCharges]'))
DROP VIEW [dbo].[vwBillOtherCharges]
GO
/****** Object:  StoredProcedure [dbo].[spLocalPurchaseSerilNumer]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLocalPurchaseSerilNumer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLocalPurchaseSerilNumer]
GO
/****** Object:  StoredProcedure [dbo].[spHPDebtorAgeRecivableDifference]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPDebtorAgeRecivableDifference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPDebtorAgeRecivableDifference]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSDetail]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertPOSDetail]
GO
/****** Object:  View [dbo].[vwReceiptDetailsDebit]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptDetailsDebit]'))
DROP VIEW [dbo].[vwReceiptDetailsDebit]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTillDetail]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertTillDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertTillDetail]
GO
/****** Object:  View [dbo].[vwAsstdisposalTransdetail]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAsstdisposalTransdetail]'))
DROP VIEW [dbo].[vwAsstdisposalTransdetail]
GO
/****** Object:  View [dbo].[vwImportShortageExcess]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwImportShortageExcess]'))
DROP VIEW [dbo].[vwImportShortageExcess]
GO
/****** Object:  View [dbo].[vwshopsaleinvoiceamount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopsaleinvoiceamount]'))
DROP VIEW [dbo].[vwshopsaleinvoiceamount]
GO
/****** Object:  View [dbo].[vwshoplocationstock]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoplocationstock]'))
DROP VIEW [dbo].[vwshoplocationstock]
GO
/****** Object:  View [dbo].[vwShopLocationWiseStock]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopLocationWiseStock]'))
DROP VIEW [dbo].[vwShopLocationWiseStock]
GO
/****** Object:  View [dbo].[VwMaintenceContractOutletDtls]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwMaintenceContractOutletDtls]'))
DROP VIEW [dbo].[VwMaintenceContractOutletDtls]
GO
/****** Object:  View [dbo].[VWLOSSPECIALINVOICEDETAIL]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWLOSSPECIALINVOICEDETAIL]'))
DROP VIEW [dbo].[VWLOSSPECIALINVOICEDETAIL]
GO
/****** Object:  View [dbo].[vwreceiptswithcontrolaccs]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptswithcontrolaccs]'))
DROP VIEW [dbo].[vwreceiptswithcontrolaccs]
GO
/****** Object:  View [dbo].[vwReceiptsCheckList]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptsCheckList]'))
DROP VIEW [dbo].[vwReceiptsCheckList]
GO
/****** Object:  View [dbo].[vwreceiptCLbankwise]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptCLbankwise]'))
DROP VIEW [dbo].[vwreceiptCLbankwise]
GO
/****** Object:  View [dbo].[vwquotationtracking3]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking3]'))
DROP VIEW [dbo].[vwquotationtracking3]
GO
/****** Object:  View [dbo].[vwCostingDifference]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostingDifference]'))
DROP VIEW [dbo].[vwCostingDifference]
GO
/****** Object:  View [dbo].[vwCostSheet]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostSheet]'))
DROP VIEW [dbo].[vwCostSheet]
GO
/****** Object:  View [dbo].[vwCostSheet_summery]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostSheet_summery]'))
DROP VIEW [dbo].[vwCostSheet_summery]
GO
/****** Object:  View [dbo].[vwCreditInvoice_BillWise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditInvoice_BillWise]'))
DROP VIEW [dbo].[vwCreditInvoice_BillWise]
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking3]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking3]'))
DROP VIEW [dbo].[vwPurchaseOrderTracking3]
GO
/****** Object:  View [dbo].[vwshipmentexpense]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentexpense]'))
DROP VIEW [dbo].[vwshipmentexpense]
GO
/****** Object:  View [dbo].[vwSelingPriceAfterEachShipment]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSelingPriceAfterEachShipment]'))
DROP VIEW [dbo].[vwSelingPriceAfterEachShipment]
GO
/****** Object:  View [dbo].[vwpdcreceipts]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpdcreceipts]'))
DROP VIEW [dbo].[vwpdcreceipts]
GO
/****** Object:  View [dbo].[vwsalesdetail]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesdetail]'))
DROP VIEW [dbo].[vwsalesdetail]
GO
/****** Object:  View [dbo].[vwSalesHistory]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesHistory]'))
DROP VIEW [dbo].[vwSalesHistory]
GO
/****** Object:  View [dbo].[vwsalespersonperformance]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalespersonperformance]'))
DROP VIEW [dbo].[vwsalespersonperformance]
GO
/****** Object:  View [dbo].[vwPosExchangeDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetails]'))
DROP VIEW [dbo].[vwPosExchangeDetails]
GO
/****** Object:  View [dbo].[vwPosExchangeDetailsGSTSepartely]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsGSTSepartely]'))
DROP VIEW [dbo].[vwPosExchangeDetailsGSTSepartely]
GO
/****** Object:  View [dbo].[vwPosExchangeDetailsWithMargin]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsWithMargin]'))
DROP VIEW [dbo].[vwPosExchangeDetailsWithMargin]
GO
/****** Object:  View [dbo].[vwPosExchangeDetailsWithMarginWithOutGST]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsWithMarginWithOutGST]'))
DROP VIEW [dbo].[vwPosExchangeDetailsWithMarginWithOutGST]
GO
/****** Object:  View [dbo].[vwposgrnamount]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposgrnamount]'))
DROP VIEW [dbo].[vwposgrnamount]
GO
/****** Object:  View [dbo].[vwTransactionList]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransactionList]'))
DROP VIEW [dbo].[vwTransactionList]
GO
/****** Object:  View [dbo].[vwTransactionListAson15062011]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransactionListAson15062011]'))
DROP VIEW [dbo].[vwTransactionListAson15062011]
GO
/****** Object:  View [dbo].[vwbillpopulategrid]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillpopulategrid]'))
DROP VIEW [dbo].[vwbillpopulategrid]
GO
/****** Object:  View [dbo].[vwBills]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBills]'))
DROP VIEW [dbo].[vwBills]
GO
/****** Object:  View [dbo].[vwTill]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTill]'))
DROP VIEW [dbo].[vwTill]
GO
/****** Object:  View [dbo].[vwTillhistory]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTillhistory]'))
DROP VIEW [dbo].[vwTillhistory]
GO
/****** Object:  View [dbo].[vwtoolsallocation]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtoolsallocation]'))
DROP VIEW [dbo].[vwtoolsallocation]
GO
/****** Object:  View [dbo].[vwTotallcpayable]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotallcpayable]'))
DROP VIEW [dbo].[vwTotallcpayable]
GO
/****** Object:  View [dbo].[vwItemSplit]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSplit]'))
DROP VIEW [dbo].[vwItemSplit]
GO
/****** Object:  StoredProcedure [dbo].[spSalesMarginReport]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesMarginReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesMarginReport]
GO
/****** Object:  StoredProcedure [dbo].[spTillEndPriceSegment]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndPriceSegment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTillEndPriceSegment]
GO
/****** Object:  StoredProcedure [dbo].[spTillEndReport]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTillEndReport]
GO
/****** Object:  StoredProcedure [dbo].[spSalesQuantityValueReport]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesQuantityValueReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesQuantityValueReport]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetInHosueRetunDetls]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetInHosueRetunDetls]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_GetInHosueRetunDetls]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_PopulateInHosueRetunDetls]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_PopulateInHosueRetunDetls]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_PopulateInHosueRetunDetls]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturDetail]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Update_InHouseCons_ReturDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_Update_InHouseCons_ReturDetail]
GO
/****** Object:  View [dbo].[vwInhousePurchasesNotBilled]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesNotBilled]'))
DROP VIEW [dbo].[vwInhousePurchasesNotBilled]
GO
/****** Object:  View [dbo].[vw_Report_Service_Bills]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_Service_Bills]'))
DROP VIEW [dbo].[vw_Report_Service_Bills]
GO
/****** Object:  View [dbo].[vwitempackingtypecheck]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitempackingtypecheck]'))
DROP VIEW [dbo].[vwitempackingtypecheck]
GO
/****** Object:  View [dbo].[vw_Report_Service_invoices]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_Service_invoices]'))
DROP VIEW [dbo].[vw_Report_Service_invoices]
GO
/****** Object:  View [dbo].[vwinvoiceswithAdvance]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceswithAdvance]'))
DROP VIEW [dbo].[vwinvoiceswithAdvance]
GO
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinSplInvoice]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinSplInvoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCorrectCostPriceinSplInvoice]
GO
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinCreditInvoice]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinCreditInvoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCorrectCostPriceinCreditInvoice]
GO
/****** Object:  View [dbo].[vwshopservicesalesWithOutGST]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopservicesalesWithOutGST]'))
DROP VIEW [dbo].[vwshopservicesalesWithOutGST]
GO
/****** Object:  View [dbo].[vwShopSplInvItemAmount]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplInvItemAmount]'))
DROP VIEW [dbo].[vwShopSplInvItemAmount]
GO
/****** Object:  View [dbo].[vwInhousePurchasesBilled]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesBilled]'))
DROP VIEW [dbo].[vwInhousePurchasesBilled]
GO
/****** Object:  View [dbo].[vwInvoiceServicePartsForPrinting]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoiceServicePartsForPrinting]'))
DROP VIEW [dbo].[vwInvoiceServicePartsForPrinting]
GO
/****** Object:  View [dbo].[vwinvoiceout]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceout]'))
DROP VIEW [dbo].[vwinvoiceout]
GO
/****** Object:  View [dbo].[VWItemRateDetails]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWItemRateDetails]'))
DROP VIEW [dbo].[VWItemRateDetails]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ServiceHistoryWeb]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_ServiceHistoryWeb]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb1]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ServiceHistoryWeb1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_ServiceHistoryWeb1]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]
GO
/****** Object:  StoredProcedure [dbo].[sptrial]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptrial]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sptrial]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckShopUserRights]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckShopUserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_CheckShopUserRights]
GO
/****** Object:  StoredProcedure [dbo].[spSalesConfirmation]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesConfirmation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesConfirmation]
GO
/****** Object:  StoredProcedure [dbo].[spSellingPriceFetch]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellingPriceFetch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSellingPriceFetch]
GO
/****** Object:  StoredProcedure [dbo].[spSellingPriceFetchWOPriceChange]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellingPriceFetchWOPriceChange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSellingPriceFetchWOPriceChange]
GO
/****** Object:  StoredProcedure [dbo].[spSerialNoFetch]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSerialNoFetch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSerialNoFetch]
GO
/****** Object:  StoredProcedure [dbo].[SpServiceAlerts]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpServiceAlerts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpServiceAlerts]
GO
/****** Object:  View [dbo].[vwtoolsreturn]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtoolsreturn]'))
DROP VIEW [dbo].[vwtoolsreturn]
GO
/****** Object:  View [dbo].[vwdatewisearrivalHQ]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisearrivalHQ]'))
DROP VIEW [dbo].[vwdatewisearrivalHQ]
GO
/****** Object:  View [dbo].[vwsuppreplacements]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsuppreplacements]'))
DROP VIEW [dbo].[vwsuppreplacements]
GO
/****** Object:  View [dbo].[vwitemdescpurchseorder]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemdescpurchseorder]'))
DROP VIEW [dbo].[vwitemdescpurchseorder]
GO
/****** Object:  View [dbo].[vwdcnwithcontrolaccdep]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdcnwithcontrolaccdep]'))
DROP VIEW [dbo].[vwdcnwithcontrolaccdep]
GO
/****** Object:  View [dbo].[vwDebitCreditCheckList]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitCreditCheckList]'))
DROP VIEW [dbo].[vwDebitCreditCheckList]
GO
/****** Object:  View [dbo].[vwDebitCreditNote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitCreditNote]'))
DROP VIEW [dbo].[vwDebitCreditNote]
GO
/****** Object:  View [dbo].[vwDebitNote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitNote]'))
DROP VIEW [dbo].[vwDebitNote]
GO
/****** Object:  View [dbo].[vwCancelEditUser]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCancelEditUser]'))
DROP VIEW [dbo].[vwCancelEditUser]
GO
/****** Object:  View [dbo].[vwPendingDeliveries]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPendingDeliveries]'))
DROP VIEW [dbo].[vwPendingDeliveries]
GO
/****** Object:  View [dbo].[vwPopulateGodownArrivals]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPopulateGodownArrivals]'))
DROP VIEW [dbo].[vwPopulateGodownArrivals]
GO
/****** Object:  View [dbo].[vwshipmentexpensespaidorprojected]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentexpensespaidorprojected]'))
DROP VIEW [dbo].[vwshipmentexpensespaidorprojected]
GO
/****** Object:  View [dbo].[vwShipmentRelatedExpenses]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentRelatedExpenses]'))
DROP VIEW [dbo].[vwShipmentRelatedExpenses]
GO
/****** Object:  View [dbo].[vwserialnoAudit]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoAudit]'))
DROP VIEW [dbo].[vwserialnoAudit]
GO
/****** Object:  View [dbo].[vwShipmentwiseitem]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentwiseitem]'))
DROP VIEW [dbo].[vwShipmentwiseitem]
GO
/****** Object:  View [dbo].[vwShipmentExpences]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentExpences]'))
DROP VIEW [dbo].[vwShipmentExpences]
GO
/****** Object:  View [dbo].[vwserbookingpartsblocked]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserbookingpartsblocked]'))
DROP VIEW [dbo].[vwserbookingpartsblocked]
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking2]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking2]'))
DROP VIEW [dbo].[vwPurchaseOrderTracking2]
GO
/****** Object:  View [dbo].[vwCreditPurchaseOrder]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditPurchaseOrder]'))
DROP VIEW [dbo].[vwCreditPurchaseOrder]
GO
/****** Object:  View [dbo].[vwCreditPurchaseQuotation]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditPurchaseQuotation]'))
DROP VIEW [dbo].[vwCreditPurchaseQuotation]
GO
/****** Object:  View [dbo].[vwcreditpurchaserequest]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditpurchaserequest]'))
DROP VIEW [dbo].[vwcreditpurchaserequest]
GO
/****** Object:  View [dbo].[vwcreditinvoice]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditinvoice]'))
DROP VIEW [dbo].[vwcreditinvoice]
GO
/****** Object:  View [dbo].[vwcreditnote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditnote]'))
DROP VIEW [dbo].[vwcreditnote]
GO
/****** Object:  View [dbo].[vwConfirmedDeliveryNote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwConfirmedDeliveryNote]'))
DROP VIEW [dbo].[vwConfirmedDeliveryNote]
GO
/****** Object:  View [dbo].[vwrebateapproval]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrebateapproval]'))
DROP VIEW [dbo].[vwrebateapproval]
GO
/****** Object:  View [dbo].[vwquotationtracking2]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking2]'))
DROP VIEW [dbo].[vwquotationtracking2]
GO
/****** Object:  View [dbo].[vwLocalUserRightsRptDtls]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalUserRightsRptDtls]'))
DROP VIEW [dbo].[vwLocalUserRightsRptDtls]
GO
/****** Object:  View [dbo].[vwloiarrivaldetail]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwloiarrivaldetail]'))
DROP VIEW [dbo].[vwloiarrivaldetail]
GO
/****** Object:  View [dbo].[vwimportitem_sa]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwimportitem_sa]'))
DROP VIEW [dbo].[vwimportitem_sa]
GO
/****** Object:  View [dbo].[vwLoyaltyPointsDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLoyaltyPointsDetails]'))
DROP VIEW [dbo].[vwLoyaltyPointsDetails]
GO
/****** Object:  View [dbo].[vwshoppurchaseBills]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchaseBills]'))
DROP VIEW [dbo].[vwshoppurchaseBills]
GO
/****** Object:  View [dbo].[vwShoprequestpending]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShoprequestpending]'))
DROP VIEW [dbo].[vwShoprequestpending]
GO
/****** Object:  View [dbo].[vwInHouseConsumption]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInHouseConsumption]'))
DROP VIEW [dbo].[vwInHouseConsumption]
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder]'))
DROP VIEW [dbo].[vwHqPurchaseOrder]
GO
/****** Object:  View [dbo].[vwHqPurchaseOrderpre]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrderpre]'))
DROP VIEW [dbo].[vwHqPurchaseOrderpre]
GO
/****** Object:  View [dbo].[vwnotcoastingpayments]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnotcoastingpayments]'))
DROP VIEW [dbo].[vwnotcoastingpayments]
GO
/****** Object:  StoredProcedure [dbo].[spInsertTillHeader]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertTillHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertTillHeader]
GO
/****** Object:  StoredProcedure [dbo].[spMag_DeleteDeliveryVerification]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_DeleteDeliveryVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_DeleteDeliveryVerification]
GO
/****** Object:  StoredProcedure [dbo].[spMag_FetchCashSaleDeliveryDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_FetchCashSaleDeliveryDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_FetchCashSaleDeliveryDetails]
GO
/****** Object:  StoredProcedure [dbo].[spMag_FetchCreditSaleDeliveryDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_FetchCreditSaleDeliveryDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_FetchCreditSaleDeliveryDetails]
GO
/****** Object:  StoredProcedure [dbo].[spbankdetailsdatewise]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spbankdetailsdatewise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spbankdetailsdatewise]
GO
/****** Object:  StoredProcedure [dbo].[spBankPosition]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankPosition]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankPosition]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliation]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation_FromSIMDI]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation_FromSIMDI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliation_FromSIMDI]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation_SIMDI]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation_SIMDI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliation_SIMDI]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationAsOn25052011]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationAsOn25052011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliationAsOn25052011]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationRep]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationRep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliationRep]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationReport]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankReconciliationReport]
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceNew]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTrialBalanceNew]
GO
/****** Object:  StoredProcedure [dbo].[sptrial1]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptrial1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sptrial1]
GO
/****** Object:  StoredProcedure [dbo].[spShopReqFlowWithPrj]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopReqFlowWithPrj]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopReqFlowWithPrj]
GO
/****** Object:  StoredProcedure [dbo].[spshoprequestflow]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spshoprequestflow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spshoprequestflow]
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]
GO
/****** Object:  StoredProcedure [dbo].[spReexportProjFlow]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReexportProjFlow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReexportProjFlow]
GO
/****** Object:  StoredProcedure [dbo].[spRebateRequest]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebateRequest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRebateRequest]
GO
/****** Object:  StoredProcedure [dbo].[spbsuserformat]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spbsuserformat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spbsuserformat]
GO
/****** Object:  StoredProcedure [dbo].[spBoatNote]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBoatNote]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBoatNote]
GO
/****** Object:  StoredProcedure [dbo].[spBankBalance]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankBalance]
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalance]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankCashBalance]
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalanceDept]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalanceDept]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankCashBalanceDept]
GO
/****** Object:  StoredProcedure [dbo].[spulShopConsumption]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopConsumption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulShopConsumption]
GO
/****** Object:  StoredProcedure [dbo].[spULMASCheckOut]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASCheckOut]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULMASCheckOut]
GO
/****** Object:  StoredProcedure [dbo].[spULMASRoomBilling]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASRoomBilling]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULMASRoomBilling]
GO
/****** Object:  StoredProcedure [dbo].[spULReexport]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULReexport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULReexport]
GO
/****** Object:  StoredProcedure [dbo].[spULSaleInv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSaleInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULSaleInv]
GO
/****** Object:  StoredProcedure [dbo].[spULshopPayments]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopPayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopPayments]
GO
/****** Object:  StoredProcedure [dbo].[spULBusinessPromotion]    Script Date: 10/06/2012 14:17:32 ******/
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
/****** Object:  StoredProcedure [dbo].[spULInvSplDesp]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvSplDesp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULInvSplDesp]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopDespToGodown]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopDespToGodown]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopDespToGodown]
GO
/****** Object:  StoredProcedure [dbo].[spULWarrentyClaim]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULWarrentyClaim]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULWarrentyClaim]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownarrival]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownarrival]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGodownarrival]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopSv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopSv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopSv]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopSWO]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopSWO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopSWO]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateBPWCStock]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateBPWCStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateBPWCStock]
GO
/****** Object:  View [dbo].[vwAssetTransfer]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetTransfer]'))
DROP VIEW [dbo].[vwAssetTransfer]
GO
/****** Object:  View [dbo].[vwAssetTransferHistory]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetTransferHistory]'))
DROP VIEW [dbo].[vwAssetTransferHistory]
GO
/****** Object:  View [dbo].[vwArrivalToGodownFromShop]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwArrivalToGodownFromShop]'))
DROP VIEW [dbo].[vwArrivalToGodownFromShop]
GO
/****** Object:  View [dbo].[vwapartmentcheckdtls]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwapartmentcheckdtls]'))
DROP VIEW [dbo].[vwapartmentcheckdtls]
GO
/****** Object:  View [dbo].[vwapartmentrommcheckout]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwapartmentrommcheckout]'))
DROP VIEW [dbo].[vwapartmentrommcheckout]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillName]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateTillName]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateLOUserRights]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateLOUserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateLOUserRights]
GO
/****** Object:  View [dbo].[vwInventoryAge]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInventoryAge]'))
DROP VIEW [dbo].[vwInventoryAge]
GO
/****** Object:  View [dbo].[vwadvancepaidCredits]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidCredits]'))
DROP VIEW [dbo].[vwadvancepaidCredits]
GO
/****** Object:  View [dbo].[vwadvancepaidDebits]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidDebits]'))
DROP VIEW [dbo].[vwadvancepaidDebits]
GO
/****** Object:  View [dbo].[vwwarrentyclaim]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwwarrentyclaim]'))
DROP VIEW [dbo].[vwwarrentyclaim]
GO
/****** Object:  View [dbo].[vwTransferIn]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferIn]'))
DROP VIEW [dbo].[vwTransferIn]
GO
/****** Object:  View [dbo].[vwTransferOutshoptoGdn]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOutshoptoGdn]'))
DROP VIEW [dbo].[vwTransferOutshoptoGdn]
GO
/****** Object:  View [dbo].[purchasetransflow]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchasetransflow]'))
DROP VIEW [dbo].[purchasetransflow]
GO
/****** Object:  View [dbo].[vwJobcardServicePartsForPrinting]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJobcardServicePartsForPrinting]'))
DROP VIEW [dbo].[vwJobcardServicePartsForPrinting]
GO
/****** Object:  View [dbo].[vwHQbatchno]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQbatchno]'))
DROP VIEW [dbo].[vwHQbatchno]
GO
/****** Object:  View [dbo].[vwPaymentsOnPO]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPaymentsOnPO]'))
DROP VIEW [dbo].[vwPaymentsOnPO]
GO
/****** Object:  View [dbo].[vwpandcPurchasebillamount]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpandcPurchasebillamount]'))
DROP VIEW [dbo].[vwpandcPurchasebillamount]
GO
/****** Object:  View [dbo].[VwPartsReplacerequestdtls]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwPartsReplacerequestdtls]'))
DROP VIEW [dbo].[VwPartsReplacerequestdtls]
GO
/****** Object:  View [dbo].[vwpaymentandreceipt]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentandreceipt]'))
DROP VIEW [dbo].[vwpaymentandreceipt]
GO
/****** Object:  View [dbo].[vwOnsiteJobCardforprinting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOnsiteJobCardforprinting]'))
DROP VIEW [dbo].[vwOnsiteJobCardforprinting]
GO
/****** Object:  View [dbo].[vwgroupmasterwithlevel]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgroupmasterwithlevel]'))
DROP VIEW [dbo].[vwgroupmasterwithlevel]
GO
/****** Object:  View [dbo].[vwreexportInvoice]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportInvoice]'))
DROP VIEW [dbo].[vwreexportInvoice]
GO
/****** Object:  View [dbo].[vwReplacementReceipt]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReplacementReceipt]'))
DROP VIEW [dbo].[vwReplacementReceipt]
GO
/****** Object:  View [dbo].[vwreexportPurchaseOrder]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportPurchaseOrder]'))
DROP VIEW [dbo].[vwreexportPurchaseOrder]
GO
/****** Object:  View [dbo].[vwreexportpurchaserequest]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportpurchaserequest]'))
DROP VIEW [dbo].[vwreexportpurchaserequest]
GO
/****** Object:  View [dbo].[vwreexportquotation]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportquotation]'))
DROP VIEW [dbo].[vwreexportquotation]
GO
/****** Object:  View [dbo].[vwPurchaseBillDetailwithunit]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetailwithunit]'))
DROP VIEW [dbo].[vwPurchaseBillDetailwithunit]
GO
/****** Object:  View [dbo].[vwPurchaseBillNotCosted]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillNotCosted]'))
DROP VIEW [dbo].[vwPurchaseBillNotCosted]
GO
/****** Object:  View [dbo].[vwPrePurchaseOrderTracking2]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPrePurchaseOrderTracking2]'))
DROP VIEW [dbo].[vwPrePurchaseOrderTracking2]
GO
/****** Object:  View [dbo].[vwpaymentvoucherdebitdetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentvoucherdebitdetails]'))
DROP VIEW [dbo].[vwpaymentvoucherdebitdetails]
GO
/****** Object:  View [dbo].[vwPayrollLinkwithPayment]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayrollLinkwithPayment]'))
DROP VIEW [dbo].[vwPayrollLinkwithPayment]
GO
/****** Object:  View [dbo].[vwservicetechniciandetails]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicetechniciandetails]'))
DROP VIEW [dbo].[vwservicetechniciandetails]
GO
/****** Object:  View [dbo].[vwShopDamageClearing]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopDamageClearing]'))
DROP VIEW [dbo].[vwShopDamageClearing]
GO
/****** Object:  View [dbo].[vwspecialdespatch]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialdespatch]'))
DROP VIEW [dbo].[vwspecialdespatch]
GO
/****** Object:  View [dbo].[vwSpecialDespatchOutQty]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialDespatchOutQty]'))
DROP VIEW [dbo].[vwSpecialDespatchOutQty]
GO
/****** Object:  View [dbo].[vwShopStockVerification]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopStockVerification]'))
DROP VIEW [dbo].[vwShopStockVerification]
GO
/****** Object:  View [dbo].[vwShopStockWriteoff]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopStockWriteoff]'))
DROP VIEW [dbo].[vwShopStockWriteoff]
GO
/****** Object:  View [dbo].[vwShopTotalStockVerification]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopTotalStockVerification]'))
DROP VIEW [dbo].[vwShopTotalStockVerification]
GO
/****** Object:  View [dbo].[vwRommapartmentOccupancydtls]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRommapartmentOccupancydtls]'))
DROP VIEW [dbo].[vwRommapartmentOccupancydtls]
GO
/****** Object:  StoredProcedure [dbo].[spBudUserFormat]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudUserFormat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudUserFormat]
GO
/****** Object:  StoredProcedure [dbo].[spGenPrefix]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGenPrefix]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGenPrefix]
GO
/****** Object:  StoredProcedure [dbo].[spAgreement]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAgreement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAgreement]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceconscheck]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceconscheck]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceconscheck]
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spaccountsarriveexdiff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spaccountsarriveexdiff]
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff_BACKUP24022012]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spaccountsarriveexdiff_BACKUP24022012]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spaccountsarriveexdiff_BACKUP24022012]
GO
/****** Object:  View [dbo].[VwCommisionInvDetails]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwCommisionInvDetails]'))
DROP VIEW [dbo].[VwCommisionInvDetails]
GO
/****** Object:  StoredProcedure [dbo].[spLCRegisterAllDetailsOld]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegisterAllDetailsOld]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLCRegisterAllDetailsOld]
GO
/****** Object:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_SaveDeliveryVerificationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_SaveDeliveryVerificationDetails]
GO
/****** Object:  View [dbo].[VwCashDrawer]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwCashDrawer]'))
DROP VIEW [dbo].[VwCashDrawer]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchVehicleList]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchVehicleList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_FetchVehicleList]
GO
/****** Object:  View [dbo].[vwDiscountFromSupplierPerShipment]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountFromSupplierPerShipment]'))
DROP VIEW [dbo].[vwDiscountFromSupplierPerShipment]
GO
/****** Object:  View [dbo].[vwendoritemdescription]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwendoritemdescription]'))
DROP VIEW [dbo].[vwendoritemdescription]
GO
/****** Object:  View [dbo].[vwDummyUniPriceVariancePerBill]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDummyUniPriceVariancePerBill]'))
DROP VIEW [dbo].[vwDummyUniPriceVariancePerBill]
GO
/****** Object:  View [dbo].[vwdeliverynote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdeliverynote]'))
DROP VIEW [dbo].[vwdeliverynote]
GO
/****** Object:  View [dbo].[vwdeliverynotenew]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdeliverynotenew]'))
DROP VIEW [dbo].[vwdeliverynotenew]
GO
GO
/****** Object:  StoredProcedure [dbo].[spPostings]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostings]
GO
/****** Object:  StoredProcedure [dbo].[spPostings_Detail]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostings_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostings_Detail]
GO
/****** Object:  StoredProcedure [dbo].[spPostingsAll]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsAll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostingsAll]
GO
/****** Object:  StoredProcedure [dbo].[spPostingsbank]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsbank]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostingsbank]
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankDateWise]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsBankDateWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostingsBankDateWise]
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankMonthWise]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsBankMonthWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostingsBankMonthWise]
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopLocationTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopLocationTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeShopTransactions]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeShopTransactions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSummarizeShopTransactions]
GO
/****** Object:  View [dbo].[vwInquiryShopStock_Pos]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStock_Pos]'))
DROP VIEW [dbo].[vwInquiryShopStock_Pos]
GO
/****** Object:  View [dbo].[vwShopBinCardAudit_Pos]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAudit_Pos]'))
DROP VIEW [dbo].[vwShopBinCardAudit_Pos]
GO
/****** Object:  View [dbo].[vwInquiryShopStockDatewise]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockDatewise]'))
DROP VIEW [dbo].[vwInquiryShopStockDatewise]
GO
/****** Object:  View [dbo].[vwInquiryShopStockDirect]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockDirect]'))
DROP VIEW [dbo].[vwInquiryShopStockDirect]
GO
/****** Object:  StoredProcedure [dbo].[spInventoryAgeAnalysis]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryAgeAnalysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInventoryAgeAnalysis]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockStg]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockStg]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockStg]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopVerification]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopVerification]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopWriteOff]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopWriteOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopWriteOff]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockExport]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateStockExport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateStockExport]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateshopDamageClearing]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateshopDamageClearing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateshopDamageClearing]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockInv]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateShopStockInv]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockKegReturn]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockKegReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockKegReturn]
GO
/****** Object:  View [dbo].[vwKegItemsHistory]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwKegItemsHistory]'))
DROP VIEW [dbo].[vwKegItemsHistory]
GO
/****** Object:  View [dbo].[vwLCMarginOutstanding]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCMarginOutstanding]'))
DROP VIEW [dbo].[vwLCMarginOutstanding]
GO
/****** Object:  View [dbo].[vwLCMarginPaid]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCMarginPaid]'))
DROP VIEW [dbo].[vwLCMarginPaid]
GO
/****** Object:  View [dbo].[vwLCOutstandingAge]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCOutstandingAge]'))
DROP VIEW [dbo].[vwLCOutstandingAge]
GO
/****** Object:  View [dbo].[vwLcOutstandingPaid]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLcOutstandingPaid]'))
DROP VIEW [dbo].[vwLcOutstandingPaid]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersDebitCredit]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersDebitCredit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersDebitCredit]
GO
/****** Object:  StoredProcedure [dbo].[spGodownExpiryTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownExpiryTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownExpiryTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownStockSpecial]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownStockSpecial]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGodownStockSpecial]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetRegister]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAssetRegister]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetTransfer]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetTransfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAssetTransfer]
GO
/****** Object:  StoredProcedure [dbo].[spReverseShopTotalStockVerification]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseShopTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReverseShopTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[spGITDifference]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGITDifference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGITDifference]
GO
/****** Object:  StoredProcedure [dbo].[spHandlingDebitNote]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHandlingDebitNote]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHandlingDebitNote]
GO
/****** Object:  StoredProcedure [dbo].[spGetServiceHistory]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetServiceHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetServiceHistory]
GO
/****** Object:  StoredProcedure [dbo].[spRptCustomBalanceSheet]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRptCustomBalanceSheet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRptCustomBalanceSheet]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersBills]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersBills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersBills]
GO
/****** Object:  StoredProcedure [dbo].[spReturnSellingPriceDetail]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnSellingPriceDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReturnSellingPriceDetail]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAdjustments]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BackUp]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments_BackUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAdjustments_BackUp]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BACKUP24022012]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments_BACKUP24022012]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersAdjustments_BACKUP24022012]
GO
/****** Object:  StoredProcedure [dbo].[spPandCInquiryShopStock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPandCInquiryShopStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPandCInquiryShopStock]
GO
/****** Object:  View [dbo].[vwInquiryShopStockSummary]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockSummary]'))
DROP VIEW [dbo].[vwInquiryShopStockSummary]
GO
/****** Object:  View [dbo].[vwShopBincardAuditSummary]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAuditSummary]'))
DROP VIEW [dbo].[vwShopBincardAuditSummary]
GO
/****** Object:  View [dbo].[vwShopBincardBadQtySummary]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardBadQtySummary]'))
DROP VIEW [dbo].[vwShopBincardBadQtySummary]
GO
/****** Object:  View [dbo].[vwPandCInquiryShopStock]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryShopStock]'))
DROP VIEW [dbo].[vwPandCInquiryShopStock]
GO
/****** Object:  View [dbo].[shopstock1]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[shopstock1]'))
DROP VIEW [dbo].[shopstock1]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockPos]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockPos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateShopStockPos]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockRecvr]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockRecvr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockRecvr]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopPurchaseReturn]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopPurchaseReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopPurchaseReturn]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockServiceInvoice]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateStockServiceInvoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateStockServiceInvoice]
GO
/****** Object:  View [dbo].[vwjournaldetailsmonthwise]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldetailsmonthwise]'))
DROP VIEW [dbo].[vwjournaldetailsmonthwise]
GO
/****** Object:  View [dbo].[vwJournalParticulars]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalParticulars]'))
DROP VIEW [dbo].[vwJournalParticulars]
GO
/****** Object:  StoredProcedure [dbo].[spPLAmtForBSdep]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLAmtForBSdep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPLAmtForBSdep]
GO
/****** Object:  StoredProcedure [dbo].[spPlannedBsheet]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedBsheet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPlannedBsheet]
GO
/****** Object:  StoredProcedure [dbo].[spPlannedPL]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedPL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPlannedPL]
GO
/****** Object:  StoredProcedure [dbo].[spPlannedTB]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedTB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPlannedTB]
GO
/****** Object:  StoredProcedure [dbo].[spPLBudget]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLBudget]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPLBudget]
GO
/****** Object:  View [dbo].[TestView_2]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TestView_2]'))
DROP VIEW [dbo].[TestView_2]
GO
/****** Object:  View [dbo].[vwGetWarntyDtlsForReplacedItem]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGetWarntyDtlsForReplacedItem]'))
DROP VIEW [dbo].[vwGetWarntyDtlsForReplacedItem]
GO
/****** Object:  View [dbo].[vwGodownExpiryAlertItems]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExpiryAlertItems]'))
DROP VIEW [dbo].[vwGodownExpiryAlertItems]
GO
/****** Object:  View [dbo].[vwGodownExpirywiseStock]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExpirywiseStock]'))
DROP VIEW [dbo].[vwGodownExpirywiseStock]
GO
/****** Object:  View [dbo].[machinerepairegister]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[machinerepairegister]'))
DROP VIEW [dbo].[machinerepairegister]
GO
/****** Object:  StoredProcedure [dbo].[spPopulateHpInterestDetails]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPopulateHpInterestDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPopulateHpInterestDetails]
GO
/****** Object:  StoredProcedure [dbo].[spPLdep]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLdep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPLdep]
GO
/****** Object:  StoredProcedure [dbo].[SpEOQProcessing]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEOQProcessing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEOQProcessing]
GO
/****** Object:  StoredProcedure [dbo].[spFixCostPriceAfterMerging]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixCostPriceAfterMerging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFixCostPriceAfterMerging]
GO
/****** Object:  View [dbo].[vwDailyDeliveryNote]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailyDeliveryNote]'))
DROP VIEW [dbo].[vwDailyDeliveryNote]
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOutCompanyWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockOutCompanyWise]
GO
/****** Object:  View [dbo].[vwDepWiseItems]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDepWiseItems]'))
DROP VIEW [dbo].[vwDepWiseItems]
GO
/****** Object:  View [dbo].[vwCustomerWiseService]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerWiseService]'))
DROP VIEW [dbo].[vwCustomerWiseService]
GO
/****** Object:  View [dbo].[vwcustomerwiseservicepending]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerwiseservicepending]'))
DROP VIEW [dbo].[vwcustomerwiseservicepending]
GO
/****** Object:  View [dbo].[vwcustomerlisting]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerlisting]'))
DROP VIEW [dbo].[vwcustomerlisting]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLoginShop]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckLoginShop]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_CheckLoginShop]
GO
/****** Object:  View [dbo].[vwExpiryItemDetails]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwExpiryItemDetails]'))
DROP VIEW [dbo].[vwExpiryItemDetails]
GO
/****** Object:  View [dbo].[vwGodownTranferFlow]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownTranferFlow]'))
DROP VIEW [dbo].[vwGodownTranferFlow]
GO
/****** Object:  StoredProcedure [dbo].[spMag_getInvoiceByNumber]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_getInvoiceByNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_getInvoiceByNumber]
GO
/****** Object:  View [dbo].[vwchequereportprint]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwchequereportprint]'))
DROP VIEW [dbo].[vwchequereportprint]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheet]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Asset_Comp]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Asset_Comp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheet_Asset_Comp]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Detail]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheet_Detail]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Liability_Comp]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Liability_Comp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheet_Liability_Comp]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheetDep]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep_old]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDep_old]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheetDep_old]
GO
/****** Object:  StoredProcedure [dbo].[SpCashFlowStatement1]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpCashFlowStatement1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpCashFlowStatement1]
GO
/****** Object:  StoredProcedure [dbo].[SpCashFlowSummary]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpCashFlowSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpCashFlowSummary]
GO
/****** Object:  StoredProcedure [dbo].[spCFUserFormat]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCFUserFormat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCFUserFormat]
GO
/****** Object:  StoredProcedure [dbo].[spCheckAlertOnMergeComplete]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCheckAlertOnMergeComplete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCheckAlertOnMergeComplete]
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetOutPut]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetOutPut]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBalanceSheetOutPut]
GO
/****** Object:  StoredProcedure [dbo].[spDeletePOSDetail]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeletePOSDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDeletePOSDetail]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlightOperator]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeleteFlightOperator]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDeleteFlightOperator]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlights]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeleteFlights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDeleteFlights]
GO
/****** Object:  View [dbo].[vwrqtohqforitem]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrqtohqforitem]'))
DROP VIEW [dbo].[vwrqtohqforitem]
GO
/****** Object:  View [dbo].[vwserviceinvoiceamt]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserviceinvoiceamt]'))
DROP VIEW [dbo].[vwserviceinvoiceamt]
GO
/****** Object:  View [dbo].[vwServiceInvoiceDetails]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoiceDetails]'))
DROP VIEW [dbo].[vwServiceInvoiceDetails]
GO
/****** Object:  View [dbo].[vwServiceInvoicePostAmount]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoicePostAmount]'))
DROP VIEW [dbo].[vwServiceInvoicePostAmount]
GO
/****** Object:  View [dbo].[vwServiceReplacements]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceReplacements]'))
DROP VIEW [dbo].[vwServiceReplacements]
GO
/****** Object:  View [dbo].[vwShopCustomerDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCustomerDetails]'))
DROP VIEW [dbo].[vwShopCustomerDetails]
GO
/****** Object:  View [dbo].[vwservicedoneforotherbranditems]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicedoneforotherbranditems]'))
DROP VIEW [dbo].[vwservicedoneforotherbranditems]
GO
/****** Object:  View [dbo].[vwServiceHistory]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceHistory]'))
DROP VIEW [dbo].[vwServiceHistory]
GO
/****** Object:  View [dbo].[vwserviceinvlisting]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserviceinvlisting]'))
DROP VIEW [dbo].[vwserviceinvlisting]
GO
/****** Object:  View [dbo].[vwServDeptRevenueSeperated]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServDeptRevenueSeperated]'))
DROP VIEW [dbo].[vwServDeptRevenueSeperated]
GO
/****** Object:  View [dbo].[vwservicebookinginvoices]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicebookinginvoices]'))
DROP VIEW [dbo].[vwservicebookinginvoices]
GO
/****** Object:  View [dbo].[vwservicedbookdetails]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicedbookdetails]'))
DROP VIEW [dbo].[vwservicedbookdetails]
GO
/****** Object:  View [dbo].[vwPosSales]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosSales]'))
DROP VIEW [dbo].[vwPosSales]
GO
/****** Object:  View [dbo].[vwPosSalesForReport]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosSalesForReport]'))
DROP VIEW [dbo].[vwPosSalesForReport]
GO
/****** Object:  View [dbo].[vwpostingsdifference]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostingsdifference]'))
DROP VIEW [dbo].[vwpostingsdifference]
GO
/****** Object:  View [dbo].[vwprePurchaseAmount]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwprePurchaseAmount]'))
DROP VIEW [dbo].[vwprePurchaseAmount]
GO
/****** Object:  View [dbo].[vwprePurchaseOrderTracking1]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwprePurchaseOrderTracking1]'))
DROP VIEW [dbo].[vwprePurchaseOrderTracking1]
GO
/****** Object:  View [dbo].[vwPurchaseAmount]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseAmount]'))
DROP VIEW [dbo].[vwPurchaseAmount]
GO
/****** Object:  View [dbo].[vwreexportinvoices]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportinvoices]'))
DROP VIEW [dbo].[vwreexportinvoices]
GO
/****** Object:  View [dbo].[vwGoodsRequestToHq]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodsRequestToHq]'))
DROP VIEW [dbo].[vwGoodsRequestToHq]
GO
/****** Object:  View [dbo].[vwHQAccBills]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccBills]'))
DROP VIEW [dbo].[vwHQAccBills]
GO
/****** Object:  View [dbo].[vwOpeningStock]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOpeningStock]'))
DROP VIEW [dbo].[vwOpeningStock]
GO
/****** Object:  View [dbo].[vwhpSPfinding]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpSPfinding]'))
DROP VIEW [dbo].[vwhpSPfinding]
GO
/****** Object:  View [dbo].[vwPaymentCheckList]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPaymentCheckList]'))
DROP VIEW [dbo].[vwPaymentCheckList]
GO
/****** Object:  View [dbo].[vwpaymentCLbankwise]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentCLbankwise]'))
DROP VIEW [dbo].[vwpaymentCLbankwise]
GO
/****** Object:  View [dbo].[vwpaymentlisting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentlisting]'))
DROP VIEW [dbo].[vwpaymentlisting]
GO
/****** Object:  View [dbo].[vwpartsfromcustomer]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpartsfromcustomer]'))
DROP VIEW [dbo].[vwpartsfromcustomer]
GO
/****** Object:  View [dbo].[vwHQAccinterdevBills]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccinterdevBills]'))
DROP VIEW [dbo].[vwHQAccinterdevBills]
GO
/****** Object:  View [dbo].[vwunpostedposbills]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwunpostedposbills]'))
DROP VIEW [dbo].[vwunpostedposbills]
GO
/****** Object:  StoredProcedure [dbo].[spAllotedStock]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAllotedStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAllotedStock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersServiceInv]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersServiceInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersServiceInv]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldExchangeRates2]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldExchangeRates2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateOldExchangeRates2]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgerspandcRet]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgerspandcRet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgerspandcRet]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersPAndCBill]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersPAndCBill]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersPAndCBill]
GO
/****** Object:  StoredProcedure [dbo].[spYearEnd]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearEnd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spYearEnd]
GO
/****** Object:  StoredProcedure [dbo].[spYearEndCheck]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearEndCheck]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spYearEndCheck]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSHeader]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdatePOSHeader]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSHeaderAsOn07062011]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSHeaderAsOn07062011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdatePOSHeaderAsOn07062011]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateRecepieDetails]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateRecepieDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateRecepieDetails]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateDailyGodownStock]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateDailyGodownStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateDailyGodownStock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateDailyShopStock]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateDailyShopStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateDailyShopStock]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlightOperator]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateFlightOperator]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateFlightOperator]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlights]    Script Date: 10/06/2012 14:17:33 ******/
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
/****** Object:  StoredProcedure [dbo].[spUpdateGodownRecovery]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownRecovery]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownRecovery]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionBills]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersInterDivisionBills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersInterDivisionBills]
GO
/****** Object:  StoredProcedure [dbo].[spULMASAgreement]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASAgreement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULMASAgreement]
GO
/****** Object:  StoredProcedure [dbo].[spULInvRecover]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvRecover]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULInvRecover]
GO
/****** Object:  StoredProcedure [dbo].[spULHQSWO]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHQSWO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHQSWO]
GO
/****** Object:  StoredProcedure [dbo].[spULBookInvoice]    Script Date: 10/06/2012 14:17:32 ******/
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
/****** Object:  StoredProcedure [dbo].[spULBookInvoice_BEFOREGST]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULBookInvoice_BEFOREGST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULBookInvoice_BEFOREGST]
GO
/****** Object:  StoredProcedure [dbo].[spULShopPos]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopPos]
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn04042011]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosBackUpAsOn04042011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopPosBackUpAsOn04042011]
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn05042011]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosBackUpAsOn05042011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopPosBackUpAsOn05042011]
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosForSoneeAsOn04042011]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosForSoneeAsOn04042011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopPosForSoneeAsOn04042011]
GO
/****** Object:  StoredProcedure [dbo].[spULSerBookingCancellation]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSerBookingCancellation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULSerBookingCancellation]
GO
/****** Object:  StoredProcedure [dbo].[spULShopDebitNote]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopDebitNote]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULShopDebitNote]
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalanceMIS]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalanceMIS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBankCashBalanceMIS]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSHeader]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertPOSHeader]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSHeaderBackUp03052011]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSHeaderBackUp03052011]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertPOSHeaderBackUp03052011]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetBalSheet]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetBalSheet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetBalSheet]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetingDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetingDetails]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetOpening]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetOpening]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetOpening]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPLdep]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetPLdep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetPLdep]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningBalance]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance_Adjustment]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance_Adjustment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningBalance_Adjustment]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance_Detail]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningBalance_Detail]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalanceAll]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalanceAll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningBalanceAll]
GO
/****** Object:  StoredProcedure [dbo].[spRatioAnalysis]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRatioAnalysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRatioAnalysis]
GO
/****** Object:  StoredProcedure [dbo].[spPL]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPL]
GO
/****** Object:  StoredProcedure [dbo].[spPL_Detail]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPL_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPL_Detail]
GO
/****** Object:  StoredProcedure [dbo].[spPLAmtForBS]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLAmtForBS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPLAmtForBS]
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalance]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTrialBalance]
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalance_Detail]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalance_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTrialBalance_Detail]
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceConsol]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceConsol]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTrialBalanceConsol]
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceDep]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceDep]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTrialBalanceDep]
GO
/****** Object:  View [dbo].[vwBillCurrency]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillCurrency]'))
DROP VIEW [dbo].[vwBillCurrency]
GO
/****** Object:  View [dbo].[vwInventoryAge_old]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInventoryAge_old]'))
DROP VIEW [dbo].[vwInventoryAge_old]
GO
/****** Object:  StoredProcedure [dbo].[sphpadvancePayments]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpadvancePayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sphpadvancePayments]
GO
/****** Object:  StoredProcedure [dbo].[spHPCustomerAdvanceAsOnDate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPCustomerAdvanceAsOnDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPCustomerAdvanceAsOnDate]
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlights]    Script Date: 10/06/2012 14:17:29 ******/
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
/****** Object:  StoredProcedure [dbo].[spHpCustomerLedger]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpCustomerLedger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHpCustomerLedger]
GO
/****** Object:  StoredProcedure [dbo].[sphpCustomerReconcilation]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpCustomerReconcilation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sphpCustomerReconcilation]
GO
/****** Object:  View [dbo].[gmlevelfour]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelfour]'))
DROP VIEW [dbo].[gmlevelfour]
GO
/****** Object:  View [dbo].[vwAllUsers]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllUsers]'))
DROP VIEW [dbo].[vwAllUsers]
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder1]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder1]'))
DROP VIEW [dbo].[vwHqPurchaseOrder1]
GO
/****** Object:  View [dbo].[vwHQSerinvoice]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQSerinvoice]'))
DROP VIEW [dbo].[vwHQSerinvoice]
GO
/****** Object:  View [dbo].[vwHqprePurchaseOrder]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqprePurchaseOrder]'))
DROP VIEW [dbo].[vwHqprePurchaseOrder]
GO
/****** Object:  View [dbo].[vwHqPurchaseBills]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseBills]'))
DROP VIEW [dbo].[vwHqPurchaseBills]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerCreditLimitExceeds]    Script Date: 10/06/2012 14:17:28 ******/
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
/****** Object:  StoredProcedure [dbo].[spcustomerwiseservices]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomerwiseservices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spcustomerwiseservices]
GO
/****** Object:  View [dbo].[vwShopPendingRequestsForPo]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPendingRequestsForPo]'))
DROP VIEW [dbo].[vwShopPendingRequestsForPo]
GO
/****** Object:  View [dbo].[vwshopitemshipmentdetailcompany]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemshipmentdetailcompany]'))
DROP VIEW [dbo].[vwshopitemshipmentdetailcompany]
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryunprocessedstock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquiryunprocessedstock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sppandcinquiryunprocessedstock]
GO
/****** Object:  View [dbo].[vwPandCInquiryUnprocessedStock]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryUnprocessedStock]'))
DROP VIEW [dbo].[vwPandCInquiryUnprocessedStock]
GO
/****** Object:  View [dbo].[vwShopInventoryValue]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInventoryValue]'))
DROP VIEW [dbo].[vwShopInventoryValue]
GO
/****** Object:  View [dbo].[vwshopwisevalue]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopwisevalue]'))
DROP VIEW [dbo].[vwshopwisevalue]
GO
/****** Object:  View [dbo].[vwshopitemshipmentdetailPU]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemshipmentdetailPU]'))
DROP VIEW [dbo].[vwshopitemshipmentdetailPU]
GO
/****** Object:  View [dbo].[vwShopItemShipmentDetailSegmentWise]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemShipmentDetailSegmentWise]'))
DROP VIEW [dbo].[vwShopItemShipmentDetailSegmentWise]
GO
/****** Object:  View [dbo].[vwmachinerepairegister]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmachinerepairegister]'))
DROP VIEW [dbo].[vwmachinerepairegister]
GO
/****** Object:  View [dbo].[vwmachinesinstalled]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmachinesinstalled]'))
DROP VIEW [dbo].[vwmachinesinstalled]
GO
/****** Object:  View [dbo].[vwMagnolia_ServiceHistoryWeb]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMagnolia_ServiceHistoryWeb]'))
DROP VIEW [dbo].[vwMagnolia_ServiceHistoryWeb]
GO
/****** Object:  View [dbo].[vwlosDebitCreditNote]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosDebitCreditNote]'))
DROP VIEW [dbo].[vwlosDebitCreditNote]
GO
/****** Object:  View [dbo].[vwlosShopItemShipment]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosShopItemShipment]'))
DROP VIEW [dbo].[vwlosShopItemShipment]
GO
/****** Object:  View [dbo].[vwlosshopitemshipmentdetail]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosshopitemshipmentdetail]'))
DROP VIEW [dbo].[vwlosshopitemshipmentdetail]
GO
/****** Object:  View [dbo].[vwHqPurchaseReturn]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseReturn]'))
DROP VIEW [dbo].[vwHqPurchaseReturn]
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingCompWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingCompWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockBalancingCompWise]
GO
/****** Object:  View [dbo].[vwCompanyOpeningStock]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyOpeningStock]'))
DROP VIEW [dbo].[vwCompanyOpeningStock]
GO
/****** Object:  View [dbo].[vwPurchaseStatus]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseStatus]'))
DROP VIEW [dbo].[vwPurchaseStatus]
GO
/****** Object:  View [dbo].[vwQuotationBaseUnit]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuotationBaseUnit]'))
DROP VIEW [dbo].[vwQuotationBaseUnit]
GO
/****** Object:  View [dbo].[vwquotationtracking1]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking1]'))
DROP VIEW [dbo].[vwquotationtracking1]
GO
/****** Object:  View [dbo].[vwCompanyExpiryAlertItems]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyExpiryAlertItems]'))
DROP VIEW [dbo].[vwCompanyExpiryAlertItems]
GO
/****** Object:  View [dbo].[vwMonthlyTenantutilityBills]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMonthlyTenantutilityBills]'))
DROP VIEW [dbo].[vwMonthlyTenantutilityBills]
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking1]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking1]'))
DROP VIEW [dbo].[vwPurchaseOrderTracking1]
GO
/****** Object:  View [dbo].[vwserbookconditions]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserbookconditions]'))
DROP VIEW [dbo].[vwserbookconditions]
GO
/****** Object:  View [dbo].[vwSellingFixAtHq]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingFixAtHq]'))
DROP VIEW [dbo].[vwSellingFixAtHq]
GO
/****** Object:  View [dbo].[vwpendingorderstilldate]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingorderstilldate]'))
DROP VIEW [dbo].[vwpendingorderstilldate]
GO
/****** Object:  View [dbo].[vwpendingpoitems]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingpoitems]'))
DROP VIEW [dbo].[vwpendingpoitems]
GO
/****** Object:  View [dbo].[vwpdcpayments]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpdcpayments]'))
DROP VIEW [dbo].[vwpdcpayments]
GO
/****** Object:  View [dbo].[vwpendingbilldetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingbilldetails]'))
DROP VIEW [dbo].[vwpendingbilldetails]
GO
/****** Object:  View [dbo].[vwfacilitytracking]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfacilitytracking]'))
DROP VIEW [dbo].[vwfacilitytracking]
GO
/****** Object:  View [dbo].[vwposout]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposout]'))
DROP VIEW [dbo].[vwposout]
GO
/****** Object:  View [dbo].[vwposposamount]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposposamount]'))
DROP VIEW [dbo].[vwposposamount]
GO
/****** Object:  UserDefinedFunction [dbo].[fnHQPurchaseorder]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnHQPurchaseorder]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnHQPurchaseorder]
GO
/****** Object:  View [dbo].[gdnstockout]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gdnstockout]'))
DROP VIEW [dbo].[gdnstockout]
GO
/****** Object:  View [dbo].[gdnstockout1]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gdnstockout1]'))
DROP VIEW [dbo].[gdnstockout1]
GO
/****** Object:  View [dbo].[vwHPProcessingWithAllDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPProcessingWithAllDetails]'))
DROP VIEW [dbo].[vwHPProcessingWithAllDetails]
GO
/****** Object:  View [dbo].[vwitemdesc]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemdesc]'))
DROP VIEW [dbo].[vwitemdesc]
GO
/****** Object:  View [dbo].[vwdatewisestock]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisestock]'))
DROP VIEW [dbo].[vwdatewisestock]
GO
/****** Object:  View [dbo].[vwdatewisestockshop]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisestockshop]'))
DROP VIEW [dbo].[vwdatewisestockshop]
GO
/****** Object:  View [dbo].[vwbookservicesdone]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesdone]'))
DROP VIEW [dbo].[vwbookservicesdone]
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysis]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetActualAnalysis]'))
DROP VIEW [dbo].[vwBudgetActualAnalysis]
GO
/****** Object:  View [dbo].[vwbookservicesneeded]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesneeded]'))
DROP VIEW [dbo].[vwbookservicesneeded]
GO
/****** Object:  View [dbo].[vwBillsWithControlAccounts]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsWithControlAccounts]'))
DROP VIEW [dbo].[vwBillsWithControlAccounts]
GO
/****** Object:  View [dbo].[vwbillswithcontrolaccs]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillswithcontrolaccs]'))
DROP VIEW [dbo].[vwbillswithcontrolaccs]
GO
/****** Object:  View [dbo].[vwBillsCheckList]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsCheckList]'))
DROP VIEW [dbo].[vwBillsCheckList]
GO
/****** Object:  View [dbo].[vwBillsCheckListInterDiv]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsCheckListInterDiv]'))
DROP VIEW [dbo].[vwBillsCheckListInterDiv]
GO
/****** Object:  View [dbo].[vwbookingdetails]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingdetails]'))
DROP VIEW [dbo].[vwbookingdetails]
GO
/****** Object:  View [dbo].[vwbookingpartsneeded]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingpartsneeded]'))
DROP VIEW [dbo].[vwbookingpartsneeded]
GO
/****** Object:  View [dbo].[vwbookingpartsreplaced]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingpartsreplaced]'))
DROP VIEW [dbo].[vwbookingpartsreplaced]
GO
/****** Object:  View [dbo].[vwbookingserviceinvoicedtls]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingserviceinvoicedtls]'))
DROP VIEW [dbo].[vwbookingserviceinvoicedtls]
GO
/****** Object:  View [dbo].[Vwbookingservicespartsforprint]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Vwbookingservicespartsforprint]'))
DROP VIEW [dbo].[Vwbookingservicespartsforprint]
GO
/****** Object:  StoredProcedure [dbo].[spsellpriceCurrwise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spsellpriceCurrwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spsellpriceCurrwise]
GO
/****** Object:  StoredProcedure [dbo].[spSellpriceCurrwiseWOPriceChange]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellpriceCurrwiseWOPriceChange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSellpriceCurrwiseWOPriceChange]
GO
/****** Object:  StoredProcedure [dbo].[spTenantRegister]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTenantRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTenantRegister]
GO
/****** Object:  View [dbo].[vwHpItemDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpItemDetails]'))
DROP VIEW [dbo].[vwHpItemDetails]
GO
/****** Object:  View [dbo].[vwItemRetailPackingPricelist]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemRetailPackingPricelist]'))
DROP VIEW [dbo].[vwItemRetailPackingPricelist]
GO
/****** Object:  View [dbo].[vwItemDiscountList]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDiscountList]'))
DROP VIEW [dbo].[vwItemDiscountList]
GO
/****** Object:  View [dbo].[vwItemOrderedInPO]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemOrderedInPO]'))
DROP VIEW [dbo].[vwItemOrderedInPO]
GO
/****** Object:  View [dbo].[vwInvoiceQuotation]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoiceQuotation]'))
DROP VIEW [dbo].[vwInvoiceQuotation]
GO
/****** Object:  View [dbo].[vwInvoicedPosRequests]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoicedPosRequests]'))
DROP VIEW [dbo].[vwInvoicedPosRequests]
GO
/****** Object:  View [dbo].[vwInvoicesWithControlAccounts]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoicesWithControlAccounts]'))
DROP VIEW [dbo].[vwInvoicesWithControlAccounts]
GO
/****** Object:  View [dbo].[vwinvoiceswithcontrolaccs]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceswithcontrolaccs]'))
DROP VIEW [dbo].[vwinvoiceswithcontrolaccs]
GO
/****** Object:  StoredProcedure [dbo].[spCreditForOverdueCustomers]    Script Date: 10/06/2012 14:17:28 ******/
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
/****** Object:  StoredProcedure [dbo].[spCreditController]    Script Date: 10/06/2012 14:17: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
/****** Object:  StoredProcedure [dbo].[spCrEDitDebitOpeningCur]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCrEDitDebitOpeningCur]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCrEDitDebitOpeningCur]
GO
/****** Object:  View [dbo].[vwjournaldetails]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldetails]'))
DROP VIEW [dbo].[vwjournaldetails]
GO
/****** Object:  StoredProcedure [dbo].[spGodownLocationStock]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownLocationStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownLocationStock]
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingShopWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingShopWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockBalancingShopWise]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrIN]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockTrIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockTrIN]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrout]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockTrout]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockTrout]
GO
/****** Object:  StoredProcedure [dbo].[sptempinsert]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptempinsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sptempinsert]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetPackagesettings]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetPackagesettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_GetPackagesettings]
GO
/****** Object:  View [dbo].[vwhpCustomerLedgerforReport]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpCustomerLedgerforReport]'))
DROP VIEW [dbo].[vwhpCustomerLedgerforReport]
GO
/****** Object:  View [dbo].[vwHPcustomersummaryasdate]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPcustomersummaryasdate]'))
DROP VIEW [dbo].[vwHPcustomersummaryasdate]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ExchangeRateHistory]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ExchangeRateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_ExchangeRateHistory]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_FetchShops]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_FetchShops]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_FetchShops]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GeneratePosBill]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GeneratePosBill]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_GeneratePosBill]
GO
/****** Object:  StoredProcedure [dbo].[spTargetAchievement]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTargetAchievement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTargetAchievement]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GetShopItemPrice]    Script Date: 10/06/2012 14:17:30 ******/
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
/****** Object:  StoredProcedure [dbo].[spSalesAndCostValue]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAndCostValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesAndCostValue]
GO
/****** Object:  View [dbo].[vwbillvendorcurrency]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillvendorcurrency]'))
DROP VIEW [dbo].[vwbillvendorcurrency]
GO
/****** Object:  View [dbo].[vwBudget]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudget]'))
DROP VIEW [dbo].[vwBudget]
GO
/****** Object:  View [dbo].[vwHPinvoices]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPinvoices]'))
DROP VIEW [dbo].[vwHPinvoices]
GO
/****** Object:  View [dbo].[vwhpfeePaymentdetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpfeePaymentdetails]'))
DROP VIEW [dbo].[vwhpfeePaymentdetails]
GO
/****** Object:  View [dbo].[vwpcpaymentsDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentsDetails]'))
DROP VIEW [dbo].[vwpcpaymentsDetails]
GO
/****** Object:  View [dbo].[vwBudgetAllocationDetails]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetAllocationDetails]'))
DROP VIEW [dbo].[vwBudgetAllocationDetails]
GO
/****** Object:  View [dbo].[vwMergeCompleteDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMergeCompleteDetails]'))
DROP VIEW [dbo].[vwMergeCompleteDetails]
GO
/****** Object:  View [dbo].[vwContraCheckList]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwContraCheckList]'))
DROP VIEW [dbo].[vwContraCheckList]
GO
/****** Object:  View [dbo].[vwReceiptDetailsCredit]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptDetailsCredit]'))
DROP VIEW [dbo].[vwReceiptDetailsCredit]
GO
/****** Object:  View [dbo].[vwNewJournalDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNewJournalDetails]'))
DROP VIEW [dbo].[vwNewJournalDetails]
GO
/****** Object:  View [dbo].[vwNewJournalDetails_GST]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNewJournalDetails_GST]'))
DROP VIEW [dbo].[vwNewJournalDetails_GST]
GO
/****** Object:  View [dbo].[vwNonControlAccounts]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNonControlAccounts]'))
DROP VIEW [dbo].[vwNonControlAccounts]
GO
/****** Object:  View [dbo].[vwNonControlsGroupAccounts]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNonControlsGroupAccounts]'))
DROP VIEW [dbo].[vwNonControlsGroupAccounts]
GO
/****** Object:  View [dbo].[vwPurchaseOrderReportHdr]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderReportHdr]'))
DROP VIEW [dbo].[vwPurchaseOrderReportHdr]
GO
/****** Object:  View [dbo].[vwPurchaseOrderStatus]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderStatus]'))
DROP VIEW [dbo].[vwPurchaseOrderStatus]
GO
/****** Object:  View [dbo].[vwshops]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshops]'))
DROP VIEW [dbo].[vwshops]
GO
/****** Object:  View [dbo].[vwSellingFixAtShops]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingFixAtShops]'))
DROP VIEW [dbo].[vwSellingFixAtShops]
GO
/****** Object:  View [dbo].[vwsellingtotalstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstock]'))
DROP VIEW [dbo].[vwsellingtotalstock]
GO
/****** Object:  View [dbo].[vwgodownstockitem]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownstockitem]'))
DROP VIEW [dbo].[vwgodownstockitem]
GO
/****** Object:  View [dbo].[vwshopstockout]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockout]'))
DROP VIEW [dbo].[vwshopstockout]
GO
/****** Object:  View [dbo].[gmlevelthree]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelthree]'))
DROP VIEW [dbo].[gmlevelthree]
GO
/****** Object:  StoredProcedure [dbo].[spInsertAccountsDefaultValues]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertAccountsDefaultValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertAccountsDefaultValues]
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlightOperator]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertFlightOperator]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertFlightOperator]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyHeader]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSdummyHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertPOSdummyHeader]
GO
/****** Object:  StoredProcedure [dbo].[sphpBouncedChequeDetails]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpBouncedChequeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sphpBouncedChequeDetails]
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesOfLastYear]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpShopItemSalesOfLastYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpShopItemSalesOfLastYear]
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationStock]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopLocationStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopLocationStock]
GO
/****** Object:  StoredProcedure [dbo].[spShipmentClearence]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShipmentClearence]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShipmentClearence]
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecasting]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReorderLevelForecasting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReorderLevelForecasting]
GO
/****** Object:  StoredProcedure [dbo].[spShopExpiryStock]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopExpiryStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopExpiryStock]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetUtilization]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetUtilization]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetUtilization]
GO
/****** Object:  StoredProcedure [dbo].[spPDChequeRegisterForPOS]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPDChequeRegisterForPOS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPDChequeRegisterForPOS]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetExceeds]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetExceeds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetExceeds]
GO
/****** Object:  StoredProcedure [dbo].[spBouncedChequeDetailsLC]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBouncedChequeDetailsLC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBouncedChequeDetailsLC]
GO
/****** Object:  StoredProcedure [dbo].[spULSerBooking]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSerBooking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULSerBooking]
GO
/****** Object:  StoredProcedure [dbo].[spULHPRepossession]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPRepossession]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPRepossession]
GO
/****** Object:  StoredProcedure [dbo].[spULHPResale]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPResale]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPResale]
GO
/****** Object:  StoredProcedure [dbo].[spULHPSaleInv]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPSaleInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPSaleInv]
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopDownPayment]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPShopDownPayment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPShopDownPayment]
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopReceipt]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPShopReceipt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPShopReceipt]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionJournal]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersInterDivisionJournal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersInterDivisionJournal]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersJournal]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersJournal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersJournal]
GO
/****** Object:  StoredProcedure [dbo].[spulShopPurchReturn]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopPurchReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulShopPurchReturn]
GO
/****** Object:  StoredProcedure [dbo].[spULUtilityBilling]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULUtilityBilling]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULUtilityBilling]
GO
/****** Object:  StoredProcedure [dbo].[spvendoroutstanding]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendoroutstanding]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spvendoroutstanding]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePostDateCheque]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePostDateCheque]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdatePostDateCheque]
GO
/****** Object:  StoredProcedure [dbo].[spValidPlFormats]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spValidPlFormats]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spValidPlFormats]
GO
/****** Object:  View [dbo].[vwAllshops]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllshops]'))
DROP VIEW [dbo].[vwAllshops]
GO
/****** Object:  View [dbo].[vwAssets]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssets]'))
DROP VIEW [dbo].[vwAssets]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReprocessing]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPReprocessing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersHPReprocessing]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersPayroll]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersPayroll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersPayroll]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPCP]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPCP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersPCP]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPO]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersPO]
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSdummyHeader]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSdummyHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdatePOSdummyHeader]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldCostPrice]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldCostPrice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateOldCostPrice]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldExchangeRates1]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldExchangeRates1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateOldExchangeRates1]
GO
/****** Object:  View [dbo].[purchsetracking]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchsetracking]'))
DROP VIEW [dbo].[purchsetracking]
GO
/****** Object:  View [dbo].[new1]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[new1]'))
DROP VIEW [dbo].[new1]
GO
/****** Object:  View [dbo].[vwadvancepaidReturn]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidReturn]'))
DROP VIEW [dbo].[vwadvancepaidReturn]
GO
/****** Object:  View [dbo].[vwJournalCheckList]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalCheckList]'))
DROP VIEW [dbo].[vwJournalCheckList]
GO
/****** Object:  View [dbo].[vwjournaldebitcreditamt]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldebitcreditamt]'))
DROP VIEW [dbo].[vwjournaldebitcreditamt]
GO
/****** Object:  View [dbo].[vwJournalDetailOneName]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalDetailOneName]'))
DROP VIEW [dbo].[vwJournalDetailOneName]
GO
/****** Object:  View [dbo].[vwhpSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpSettlementDetails]'))
DROP VIEW [dbo].[vwhpSettlementDetails]
GO
/****** Object:  View [dbo].[vwHPSettlements]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPSettlements]'))
DROP VIEW [dbo].[vwHPSettlements]
GO
/****** Object:  View [dbo].[vwHPAgreementDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAgreementDetails]'))
DROP VIEW [dbo].[vwHPAgreementDetails]
GO
/****** Object:  View [dbo].[vwhpCustomerLedger]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpCustomerLedger]'))
DROP VIEW [dbo].[vwhpCustomerLedger]
GO
/****** Object:  View [dbo].[vwreceiptvouchercreditdetails]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptvouchercreditdetails]'))
DROP VIEW [dbo].[vwreceiptvouchercreditdetails]
GO
/****** Object:  View [dbo].[vwRequestQuotationPurchase]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestQuotationPurchase]'))
DROP VIEW [dbo].[vwRequestQuotationPurchase]
GO
/****** Object:  View [dbo].[vwproductwiseservices]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwproductwiseservices]'))
DROP VIEW [dbo].[vwproductwiseservices]
GO
/****** Object:  View [dbo].[vwPayrollLinkwithjournal]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayrollLinkwithjournal]'))
DROP VIEW [dbo].[vwPayrollLinkwithjournal]
GO
/****** Object:  View [dbo].[vwpostdatedpayments]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostdatedpayments]'))
DROP VIEW [dbo].[vwpostdatedpayments]
GO
/****** Object:  View [dbo].[vwpostdatedreceipts]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostdatedreceipts]'))
DROP VIEW [dbo].[vwpostdatedreceipts]
GO
/****** Object:  View [dbo].[vwShopExchangerateDetails]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExchangerateDetails]'))
DROP VIEW [dbo].[vwShopExchangerateDetails]
GO
/****** Object:  View [dbo].[vwShopExpiryAlertItems]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExpiryAlertItems]'))
DROP VIEW [dbo].[vwShopExpiryAlertItems]
GO
/****** Object:  View [dbo].[vwShopExpirywiseStock]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExpirywiseStock]'))
DROP VIEW [dbo].[vwShopExpirywiseStock]
GO
/****** Object:  View [dbo].[vwShopGodownDepWise]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopGodownDepWise]'))
DROP VIEW [dbo].[vwShopGodownDepWise]
GO
/****** Object:  View [dbo].[vwserialnoitemsissuedgodownstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsissuedgodownstock]'))
DROP VIEW [dbo].[vwserialnoitemsissuedgodownstock]
GO
/****** Object:  View [dbo].[vwserialnoitemsissuedshopstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsissuedshopstock]'))
DROP VIEW [dbo].[vwserialnoitemsissuedshopstock]
GO
/****** Object:  View [dbo].[vwserialnoitemsshopstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsshopstock]'))
DROP VIEW [dbo].[vwserialnoitemsshopstock]
GO
/****** Object:  View [dbo].[vwSales]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSales]'))
DROP VIEW [dbo].[vwSales]
GO
/****** Object:  View [dbo].[vwserialnogodownitemstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnogodownitemstock]'))
DROP VIEW [dbo].[vwserialnogodownitemstock]
GO
/****** Object:  StoredProcedure [dbo].[spDateCheck]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDateCheck]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDateCheck]
GO
/****** Object:  StoredProcedure [dbo].[spULshopinterdeppurchase]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopinterdeppurchase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopinterdeppurchase]
GO
/****** Object:  StoredProcedure [dbo].[spULshopinterdepsale]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopinterdepsale]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopinterdepsale]
GO
/****** Object:  StoredProcedure [dbo].[spGetAccExrate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetAccExrate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetAccExrate]
GO
/****** Object:  StoredProcedure [dbo].[spInterdivisionalBalance]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInterdivisionalBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInterdivisionalBalance]
GO
/****** Object:  StoredProcedure [dbo].[spGetExpiryEmailCompanySettings]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailCompanySettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetExpiryEmailCompanySettings]
GO
/****** Object:  StoredProcedure [dbo].[spAssets]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssets]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAssets]
GO
/****** Object:  StoredProcedure [dbo].[sp_TargetAchievement]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_TargetAchievement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_TargetAchievement]
GO
/****** Object:  StoredProcedure [dbo].[spLCRegisterAllDetails]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegisterAllDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLCRegisterAllDetails]
GO
/****** Object:  View [dbo].[vwDiscountSales]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountSales]'))
DROP VIEW [dbo].[vwDiscountSales]
GO
/****** Object:  View [dbo].[vwcurrexrateagainstcompcurr]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrexrateagainstcompcurr]'))
DROP VIEW [dbo].[vwcurrexrateagainstcompcurr]
GO
/****** Object:  View [dbo].[vwcurrexrateagainstInventorycurr]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrexrateagainstInventorycurr]'))
DROP VIEW [dbo].[vwcurrexrateagainstInventorycurr]
GO
/****** Object:  View [dbo].[vwcustomerwiseservices]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerwiseservices]'))
DROP VIEW [dbo].[vwcustomerwiseservices]
GO
/****** Object:  StoredProcedure [dbo].[spPOPaymentStatus]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPOPaymentStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPOPaymentStatus]
GO
/****** Object:  StoredProcedure [dbo].[spPosMasterFetch]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPosMasterFetch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPosMasterFetch]
GO
/****** Object:  View [dbo].[vwGodownExchangerateDetails]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExchangerateDetails]'))
DROP VIEW [dbo].[vwGodownExchangerateDetails]
GO
/****** Object:  View [dbo].[vwGlobalAccounts]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGlobalAccounts]'))
DROP VIEW [dbo].[vwGlobalAccounts]
GO
/****** Object:  View [dbo].[vwTransferInShop]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferInShop]'))
DROP VIEW [dbo].[vwTransferInShop]
GO
/****** Object:  View [dbo].[vwTransferOutShopToShop]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOutShopToShop]'))
DROP VIEW [dbo].[vwTransferOutShopToShop]
GO
/****** Object:  StoredProcedure [dbo].[spPLCarryForwardAmt]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLCarryForwardAmt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPLCarryForwardAmt]
GO
/****** Object:  StoredProcedure [dbo].[spPostingTransactionwise]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingTransactionwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPostingTransactionwise]
GO
/****** Object:  StoredProcedure [dbo].[spproductwiseservices]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spproductwiseservices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spproductwiseservices]
GO
/****** Object:  StoredProcedure [dbo].[spgetshopstockasondate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgetshopstockasondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spgetshopstockasondate]
GO
/****** Object:  StoredProcedure [dbo].[sp_BudgetUtilization]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_BudgetUtilization]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_BudgetUtilization]
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_ASHOP]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_ASHOP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FETCH_ASHOP]
GO
/****** Object:  View [dbo].[vwJournalPostAmount]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalPostAmount]'))
DROP VIEW [dbo].[vwJournalPostAmount]
GO
/****** Object:  View [dbo].[Vwjournalswithcontrolaccs]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Vwjournalswithcontrolaccs]'))
DROP VIEW [dbo].[Vwjournalswithcontrolaccs]
GO
/****** Object:  View [dbo].[vwTransferInOutRequest]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferInOutRequest]'))
DROP VIEW [dbo].[vwTransferInOutRequest]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersDepreciation]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersDepreciation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersDepreciation]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersForex]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersForex]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersForex]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPFeePayment]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPFeePayment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersHPFeePayment]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPInterest]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPInterest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersHPInterest]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPPayments]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPPayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersHPPayments]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReceipts]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPReceipts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersHPReceipts]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersContra]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersContra]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLEDgersContra]
GO
/****** Object:  View [dbo].[vwshopbincardauditwithopening]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopbincardauditwithopening]'))
DROP VIEW [dbo].[vwshopbincardauditwithopening]
GO
/****** Object:  StoredProcedure [dbo].[spReverseOldCostPrice]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseOldCostPrice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReverseOldCostPrice]
GO
/****** Object:  StoredProcedure [dbo].[spGodownExpiryStock]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownExpiryStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownExpiryStock]
GO
/****** Object:  StoredProcedure [dbo].[SpGroupLevelOrdering]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpGroupLevelOrdering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpGroupLevelOrdering]
GO
/****** Object:  StoredProcedure [dbo].[spUlShopTrIn]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopTrIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUlShopTrIn]
GO
/****** Object:  StoredProcedure [dbo].[spULshopTrOut]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopTrOut]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULshopTrOut]
GO
/****** Object:  View [dbo].[vwLeadtime]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLeadtime]'))
DROP VIEW [dbo].[vwLeadtime]
GO
/****** Object:  View [dbo].[currencyexchangerate]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[currencyexchangerate]'))
DROP VIEW [dbo].[currencyexchangerate]
GO
/****** Object:  StoredProcedure [dbo].[sp_Crm_Report_Quotation]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_Crm_Report_Quotation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_Crm_Report_Quotation]
GO
/****** Object:  StoredProcedure [dbo].[spLocationMerging]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLocationMerging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLocationMerging]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockMerging]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockMerging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopStockMerging]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopItemMerge]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopItemMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopItemMerge]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopLocationItemMerge]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopLocationItemMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateShopLocationItemMerge]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownStockMerging]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownStockMerging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownStockMerging]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownItemMerge]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownItemMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownItemMerge]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownLocationItemMerge]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownLocationItemMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateGodownLocationItemMerge]
GO
/****** Object:  StoredProcedure [dbo].[spConvertequiamount]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertequiamount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spConvertequiamount]
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemorbrandsold]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomeritemorbrandsold]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spcustomeritemorbrandsold]
GO
/****** Object:  StoredProcedure [dbo].[spshopOpeningstockondate]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spshopOpeningstockondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spshopOpeningstockondate]
GO
/****** Object:  StoredProcedure [dbo].[spOpeningGodownstockondate]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningGodownstockondate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spOpeningGodownstockondate]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchTransferIn]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchTransferIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_FetchTransferIn]
GO
/****** Object:  StoredProcedure [dbo].[SendEmails]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SendEmails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SendEmails]
GO
/****** Object:  StoredProcedure [dbo].[SendSMS]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SendSMS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SendSMS]
GO
/****** Object:  View [dbo].[vwcustomercategory]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomercategory]'))
DROP VIEW [dbo].[vwcustomercategory]
GO
/****** Object:  View [dbo].[vwdummyPosSalesForReport]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyPosSalesForReport]'))
DROP VIEW [dbo].[vwdummyPosSalesForReport]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum_EmailClient]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSum_EmailClient]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSum_EmailClient]
GO
/****** Object:  StoredProcedure [dbo].[spGetAllSubDepartments]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetAllSubDepartments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetAllSubDepartments]
GO
/****** Object:  StoredProcedure [dbo].[spGetExchangeRate]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExchangeRate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetExchangeRate]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumForAgeing]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSumForAgeing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSumForAgeing]
GO
/****** Object:  View [dbo].[vwHPAccountPayment]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAccountPayment]'))
DROP VIEW [dbo].[vwHPAccountPayment]
GO
/****** Object:  View [dbo].[vwaHQadminuserRightsRptDtls]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaHQadminuserRightsRptDtls]'))
DROP VIEW [dbo].[vwaHQadminuserRightsRptDtls]
GO
/****** Object:  View [dbo].[vwaccountsdepwise]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccountsdepwise]'))
DROP VIEW [dbo].[vwaccountsdepwise]
GO
/****** Object:  View [dbo].[vwVendorCategory]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorCategory]'))
DROP VIEW [dbo].[vwVendorCategory]
GO
/****** Object:  StoredProcedure [dbo].[spPDChequeRegisterProcessingForPOS]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPDChequeRegisterProcessingForPOS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPDChequeRegisterProcessingForPOS]
GO
/****** Object:  StoredProcedure [dbo].[spReservation]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReservation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReservation]
GO
/****** Object:  StoredProcedure [dbo].[spNonBuyingCustomersItemwise]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spNonBuyingCustomersItemwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spNonBuyingCustomersItemwise]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchDepartments]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchDepartments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_FetchDepartments]
GO
/****** Object:  View [dbo].[gmleveltwo]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmleveltwo]'))
DROP VIEW [dbo].[gmleveltwo]
GO
/****** Object:  View [dbo].[vwinhousepurchase]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinhousepurchase]'))
DROP VIEW [dbo].[vwinhousepurchase]
GO
/****** Object:  View [dbo].[vwInhousePurchasesAgainstVendors]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesAgainstVendors]'))
DROP VIEW [dbo].[vwInhousePurchasesAgainstVendors]
GO
/****** Object:  StoredProcedure [dbo].[spCRM_GeneratePrefix]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCRM_GeneratePrefix]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCRM_GeneratePrefix]
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSum]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCreditorAgeSum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCreditorAgeSum]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsDetails]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetShowDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetShowDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetShowDetails]
GO
/****** Object:  View [dbo].[vwpcpaymentvoucherdetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentvoucherdetails]'))
DROP VIEW [dbo].[vwpcpaymentvoucherdetails]
GO
/****** Object:  View [dbo].[vwPCPaymentCheckList]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPCPaymentCheckList]'))
DROP VIEW [dbo].[vwPCPaymentCheckList]
GO
/****** Object:  View [dbo].[vwpcpaymentCLbankwise]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentCLbankwise]'))
DROP VIEW [dbo].[vwpcpaymentCLbankwise]
GO
/****** Object:  View [dbo].[vwpcpaymentlisting]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentlisting]'))
DROP VIEW [dbo].[vwpcpaymentlisting]
GO
/****** Object:  View [dbo].[vwHPProcessingDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPProcessingDetails]'))
DROP VIEW [dbo].[vwHPProcessingDetails]
GO
/****** Object:  View [dbo].[vwhpReceiptDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpReceiptDetails]'))
DROP VIEW [dbo].[vwhpReceiptDetails]
GO
/****** Object:  UserDefinedFunction [dbo].[fnGetExchangeRates]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnGetExchangeRates]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnGetExchangeRates]
GO
/****** Object:  StoredProcedure [dbo].[spSalesPromotionDetails]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesPromotionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesPromotionDetails]
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommission]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesCommission]
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionDetail]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesCommissionDetail]
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionEligiblity]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionEligiblity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesCommissionEligiblity]
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionPayment]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionPayment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesCommissionPayment]
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionTrans]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionTrans]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesCommissionTrans]
GO
/****** Object:  StoredProcedure [dbo].[spSelectAllSubDepartments]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSelectAllSubDepartments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSelectAllSubDepartments]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetExchangeRates]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetExchangeRates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_GetExchangeRates]
GO
/****** Object:  View [dbo].[vwHpItemRegistrationDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpItemRegistrationDetails]'))
DROP VIEW [dbo].[vwHpItemRegistrationDetails]
GO
/****** Object:  View [dbo].[vwHPFeePaymentCheckList]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentCheckList]'))
DROP VIEW [dbo].[vwHPFeePaymentCheckList]
GO
/****** Object:  View [dbo].[vwHPFeePaymentVoucherdetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentVoucherdetails]'))
DROP VIEW [dbo].[vwHPFeePaymentVoucherdetails]
GO
/****** Object:  StoredProcedure [dbo].[spConvertequiamounttemp]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertequiamounttemp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spConvertequiamounttemp]
GO
/****** Object:  View [dbo].[vwinterdeppurchase]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinterdeppurchase]'))
DROP VIEW [dbo].[vwinterdeppurchase]
GO
/****** Object:  View [dbo].[vwinterdepsales]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinterdepsales]'))
DROP VIEW [dbo].[vwinterdepsales]
GO
/****** Object:  UserDefinedFunction [dbo].[GenerateNextTransactionNo]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenerateNextTransactionNo]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GenerateNextTransactionNo]
GO
/****** Object:  View [dbo].[gmlevelone]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelone]'))
DROP VIEW [dbo].[gmlevelone]
GO
/****** Object:  StoredProcedure [dbo].[SPHPOVERDUE]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPHPOVERDUE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SPHPOVERDUE]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumCurrencyPrw]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSumCurrencyPrw]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSumCurrencyPrw]
GO
/****** Object:  StoredProcedure [dbo].[SpLmGetCurrency]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmGetCurrency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmGetCurrency]
GO
/****** Object:  StoredProcedure [dbo].[sp_help_column]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_help_column]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_help_column]
GO
/****** Object:  StoredProcedure [dbo].[CrmSpGetTask]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CrmSpGetTask]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CrmSpGetTask]
GO
/****** Object:  StoredProcedure [dbo].[Sp_KotItemDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_KotItemDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Sp_KotItemDetails]
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedKOTDetails]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SelectedKOTDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SelectedKOTDetails]
GO
/****** Object:  View [dbo].[vwfinyearperiod]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfinyearperiod]'))
DROP VIEW [dbo].[vwfinyearperiod]
GO
/****** Object:  StoredProcedure [dbo].[spfetchforsegment]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spfetchforsegment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spfetchforsegment]
GO
/****** Object:  StoredProcedure [dbo].[spFindInActiveItems]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFindInActiveItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFindInActiveItems]
GO
/****** Object:  StoredProcedure [dbo].[UpdateData]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateData]
GO
/****** Object:  View [dbo].[vAllIndexes]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vAllIndexes]'))
DROP VIEW [dbo].[vAllIndexes]
GO
/****** Object:  StoredProcedure [dbo].[spLeafNode]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeafNode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLeafNode]
GO
/****** Object:  StoredProcedure [dbo].[spLeafNodeValues]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeafNodeValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLeafNodeValues]
GO
/****** Object:  View [dbo].[vwdummyQuotationReport]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyQuotationReport]'))
DROP VIEW [dbo].[vwdummyQuotationReport]
GO
/****** Object:  View [dbo].[vwDishIngrdItems]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDishIngrdItems]'))
DROP VIEW [dbo].[vwDishIngrdItems]
GO
/****** Object:  View [dbo].[vwDenominationTotal]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDenominationTotal]'))
DROP VIEW [dbo].[vwDenominationTotal]
GO
/****** Object:  StoredProcedure [dbo].[spDeleteListItemDetails]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeleteListItemDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDeleteListItemDetails]
GO
/****** Object:  StoredProcedure [dbo].[SPLatestSegmentRates]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPLatestSegmentRates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SPLatestSegmentRates]
GO
/****** Object:  View [dbo].[vwHPAdvancePayment]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAdvancePayment]'))
DROP VIEW [dbo].[vwHPAdvancePayment]
GO
/****** Object:  View [dbo].[vwHpChequeReceived]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpChequeReceived]'))
DROP VIEW [dbo].[vwHpChequeReceived]
GO
/****** Object:  View [dbo].[vwHpCustomerDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpCustomerDetails]'))
DROP VIEW [dbo].[vwHpCustomerDetails]
GO
/****** Object:  View [dbo].[vwpackingtype]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpackingtype]'))
DROP VIEW [dbo].[vwpackingtype]
GO
/****** Object:  View [dbo].[vwPackQuantity]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPackQuantity]'))
DROP VIEW [dbo].[vwPackQuantity]
GO
/****** Object:  View [dbo].[vwHPAgreement]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAgreement]'))
DROP VIEW [dbo].[vwHPAgreement]
GO
/****** Object:  View [dbo].[vwAccountGroupOrderCounter]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccountGroupOrderCounter]'))
DROP VIEW [dbo].[vwAccountGroupOrderCounter]
GO
/****** Object:  StoredProcedure [dbo].[spQuoteDiscount]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuoteDiscount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spQuoteDiscount]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetCostSales]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetCostSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetCostSales]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPurchase]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetPurchase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spBudgetPurchase]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateUserRights]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateUserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateUserRights]
GO
/****** Object:  StoredProcedure [dbo].[spHpProcessingtracking]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpProcessingtracking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHpProcessingtracking]
GO
/****** Object:  StoredProcedure [dbo].[spHpReceiptTracking]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpReceiptTracking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHpReceiptTracking]
GO
/****** Object:  StoredProcedure [dbo].[spHPFinancialIncomeEarned]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPFinancialIncomeEarned]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPFinancialIncomeEarned]
GO
/****** Object:  StoredProcedure [dbo].[spInsertListItemDetails]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertListItemDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertListItemDetails]
GO
/****** Object:  StoredProcedure [dbo].[spHPCustomerClassification]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPCustomerClassification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPCustomerClassification]
GO
/****** Object:  StoredProcedure [dbo].[generatebc]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[generatebc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[generatebc]
GO
/****** Object:  View [dbo].[gmwithlevel]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmwithlevel]'))
DROP VIEW [dbo].[gmwithlevel]
GO
/****** Object:  View [dbo].[vwitempackingonebarcode]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitempackingonebarcode]'))
DROP VIEW [dbo].[vwitempackingonebarcode]
GO
/****** Object:  View [dbo].[vwHPFinancialIncomeEarned]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFinancialIncomeEarned]'))
DROP VIEW [dbo].[vwHPFinancialIncomeEarned]
GO
/****** Object:  View [dbo].[vwHPInvoiceDetails]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPInvoiceDetails]'))
DROP VIEW [dbo].[vwHPInvoiceDetails]
GO
/****** Object:  View [dbo].[vwhpItemTransfer]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpItemTransfer]'))
DROP VIEW [dbo].[vwhpItemTransfer]
GO
/****** Object:  View [dbo].[vwHPNonSettledCustomer]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPNonSettledCustomer]'))
DROP VIEW [dbo].[vwHPNonSettledCustomer]
GO
/****** Object:  View [dbo].[vwHPOverDueBalance]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOverDueBalance]'))
DROP VIEW [dbo].[vwHPOverDueBalance]
GO
/****** Object:  View [dbo].[vwHPOverDueBalanceTEST]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOverDueBalanceTEST]'))
DROP VIEW [dbo].[vwHPOverDueBalanceTEST]
GO
/****** Object:  View [dbo].[vwhpPDChequeRegistry]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpPDChequeRegistry]'))
DROP VIEW [dbo].[vwhpPDChequeRegistry]
GO
/****** Object:  View [dbo].[vwHPDummyQuotationReport]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPDummyQuotationReport]'))
DROP VIEW [dbo].[vwHPDummyQuotationReport]
GO
/****** Object:  StoredProcedure [dbo].[spTillEndStockVerificationRpt]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndStockVerificationRpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spTillEndStockVerificationRpt]
GO
/****** Object:  View [dbo].[vwHPQuotationReport]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPQuotationReport]'))
DROP VIEW [dbo].[vwHPQuotationReport]
GO
/****** Object:  View [dbo].[vwTargetActualAnalysis]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetActualAnalysis]'))
DROP VIEW [dbo].[vwTargetActualAnalysis]
GO
/****** Object:  View [dbo].[vwLoyaltyCardContactDetails]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLoyaltyCardContactDetails]'))
DROP VIEW [dbo].[vwLoyaltyCardContactDetails]
GO
/****** Object:  View [dbo].[vwMEDifferenceinStock]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMEDifferenceinStock]'))
DROP VIEW [dbo].[vwMEDifferenceinStock]
GO
/****** Object:  View [dbo].[vwShopPurchaseReturn]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPurchaseReturn]'))
DROP VIEW [dbo].[vwShopPurchaseReturn]
GO
/****** Object:  View [dbo].[vwItemsHavingStock]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsHavingStock]'))
DROP VIEW [dbo].[vwItemsHavingStock]
GO
/****** Object:  View [dbo].[vwShopItemStockitemsItemDtls]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemStockitemsItemDtls]'))
DROP VIEW [dbo].[vwShopItemStockitemsItemDtls]
GO
/****** Object:  View [dbo].[vwItemAttributes1]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemAttributes1]'))
DROP VIEW [dbo].[vwItemAttributes1]
GO
/****** Object:  View [dbo].[vwItemAttributes2]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemAttributes2]'))
DROP VIEW [dbo].[vwItemAttributes2]
GO
/****** Object:  StoredProcedure [dbo].[spCRM_SendMail]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCRM_SendMail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCRM_SendMail]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsInsertCardRegistation]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsInsertCardRegistation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsInsertCardRegistation]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsRewardsearch]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsRewardsearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsRewardsearch]
GO
/****** Object:  StoredProcedure [dbo].[SpLMsUpateRewardPoint]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLMsUpateRewardPoint]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLMsUpateRewardPoint]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsUpdateCardRegistation]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsUpdateCardRegistation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsUpdateCardRegistation]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetpoint]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetpoint]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetpoint]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetPoints]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetPoints]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetPoints]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistaion]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRegistaion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetRegistaion]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistatioDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRegistatioDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetRegistatioDetails]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetReward]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetReward]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetReward]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRewards]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRewards]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsGetRewards]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeletePoint]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeletePoint]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsDeletePoint]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteReward]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeleteReward]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsDeleteReward]
GO
/****** Object:  View [dbo].[vwcompsalesquantitywise]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcompsalesquantitywise]'))
DROP VIEW [dbo].[vwcompsalesquantitywise]
GO
/****** Object:  View [dbo].[vwSerialNoArrival]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSerialNoArrival]'))
DROP VIEW [dbo].[vwSerialNoArrival]
GO
/****** Object:  View [dbo].[vwSerialNofetch]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSerialNofetch]'))
DROP VIEW [dbo].[vwSerialNofetch]
GO
/****** Object:  View [dbo].[vwTargetActualAnalysismax]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetActualAnalysismax]'))
DROP VIEW [dbo].[vwTargetActualAnalysismax]
GO
/****** Object:  View [dbo].[vwTargetAllocationdetails]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetAllocationdetails]'))
DROP VIEW [dbo].[vwTargetAllocationdetails]
GO
/****** Object:  View [dbo].[VwTemplocation]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwTemplocation]'))
DROP VIEW [dbo].[VwTemplocation]
GO
/****** Object:  View [dbo].[vwhpReceipt]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpReceipt]'))
DROP VIEW [dbo].[vwhpReceipt]
GO
/****** Object:  View [dbo].[vwHPFeePaymentFrameWise]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentFrameWise]'))
DROP VIEW [dbo].[vwHPFeePaymentFrameWise]
GO
/****** Object:  View [dbo].[vwitemcustomcode]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemcustomcode]'))
DROP VIEW [dbo].[vwitemcustomcode]
GO
/****** Object:  UserDefinedFunction [dbo].[fnIssueSerialNos]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnIssueSerialNos]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnIssueSerialNos]
GO
/****** Object:  UserDefinedFunction [dbo].[fnIssueSerialNosForSpINV]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnIssueSerialNosForSpINV]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnIssueSerialNosForSpINV]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchItem]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_FetchItem]
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysismax]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetActualAnalysismax]'))
DROP VIEW [dbo].[vwBudgetActualAnalysismax]
GO
/****** Object:  View [dbo].[vwbrandcategory]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbrandcategory]'))
DROP VIEW [dbo].[vwbrandcategory]
GO
/****** Object:  View [dbo].[vwbookingservinvoices]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingservinvoices]'))
DROP VIEW [dbo].[vwbookingservinvoices]
GO
/****** Object:  StoredProcedure [dbo].[spSaveExpiryEmailSettings]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSaveExpiryEmailSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSaveExpiryEmailSettings]
GO
/****** Object:  View [dbo].[vwHPOutstandingAmount]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOutstandingAmount]'))
DROP VIEW [dbo].[vwHPOutstandingAmount]
GO
/****** Object:  UserDefinedFunction [dbo].[GetIndexColumns]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetIndexColumns]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetIndexColumns]
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyDetail]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSdummyDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInsertPOSdummyDetail]
GO
/****** Object:  View [dbo].[vwAllMergeHeader]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllMergeHeader]'))
DROP VIEW [dbo].[vwAllMergeHeader]
GO
/****** Object:  StoredProcedure [dbo].[spQuotereplaceSelPrice]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuotereplaceSelPrice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spQuotereplaceSelPrice]
GO
/****** Object:  StoredProcedure [dbo].[spreportInformation]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spreportInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spreportInformation]
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesForBudget]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpShopItemSalesForBudget]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpShopItemSalesForBudget]
GO
/****** Object:  View [dbo].[vwItemDescription_ASKholdings]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription_ASKholdings]'))
DROP VIEW [dbo].[vwItemDescription_ASKholdings]
GO
/****** Object:  View [dbo].[vwItemDescription1]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription1]'))
DROP VIEW [dbo].[vwItemDescription1]
GO
/****** Object:  View [dbo].[vwitemDescriptionprint]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemDescriptionprint]'))
DROP VIEW [dbo].[vwitemDescriptionprint]
GO
/****** Object:  View [dbo].[vwVendorGroupcategory]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorGroupcategory]'))
DROP VIEW [dbo].[vwVendorGroupcategory]
GO
/****** Object:  View [dbo].[vwvendorItemDescription]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwvendorItemDescription]'))
DROP VIEW [dbo].[vwvendorItemDescription]
GO
/****** Object:  View [dbo].[vwAllMergeDetails]    Script Date: 10/06/2012 14:17:05 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllMergeDetails]'))
DROP VIEW [dbo].[vwAllMergeDetails]
GO
/****** Object:  View [dbo].[vwpurchaseorderothcharge]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchaseorderothcharge]'))
DROP VIEW [dbo].[vwpurchaseorderothcharge]
GO
/****** Object:  View [dbo].[vwserialnogodownstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnogodownstock]'))
DROP VIEW [dbo].[vwserialnogodownstock]
GO
/****** Object:  View [dbo].[vwserialnoissuegodownstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoissuegodownstock]'))
DROP VIEW [dbo].[vwserialnoissuegodownstock]
GO
/****** Object:  View [dbo].[vwserialnoissueshopstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoissueshopstock]'))
DROP VIEW [dbo].[vwserialnoissueshopstock]
GO
/****** Object:  View [dbo].[vwserialnoshopstock]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoshopstock]'))
DROP VIEW [dbo].[vwserialnoshopstock]
GO
/****** Object:  View [dbo].[vwShopHPInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopHPInvoiceSettlementNo]'))
DROP VIEW [dbo].[vwShopHPInvoiceSettlementNo]
GO
/****** Object:  View [dbo].[vwshopexpirystock]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopexpirystock]'))
DROP VIEW [dbo].[vwshopexpirystock]
GO
/****** Object:  View [dbo].[vwhpunsettledProcessing]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpunsettledProcessing]'))
DROP VIEW [dbo].[vwhpunsettledProcessing]
GO
/****** Object:  View [dbo].[vwHPSettiementReceipts]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPSettiementReceipts]'))
DROP VIEW [dbo].[vwHPSettiementReceipts]
GO
/****** Object:  View [dbo].[vwHpShopReceipt]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpShopReceipt]'))
DROP VIEW [dbo].[vwHpShopReceipt]
GO
/****** Object:  View [dbo].[vwhpAdvanceReceived]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpAdvanceReceived]'))
DROP VIEW [dbo].[vwhpAdvanceReceived]
GO
/****** Object:  View [dbo].[vwHPAdvaneShopReceipt]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAdvaneShopReceipt]'))
DROP VIEW [dbo].[vwHPAdvaneShopReceipt]
GO
/****** Object:  StoredProcedure [dbo].[spGetExpiryEmailSettings]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetExpiryEmailSettings]
GO
/****** Object:  StoredProcedure [dbo].[spDeletePOSdummyDetail]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeletePOSdummyDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDeletePOSdummyDetail]
GO
/****** Object:  StoredProcedure [dbo].[spDateWiseSalesReport]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDateWiseSalesReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDateWiseSalesReport]
GO
/****** Object:  StoredProcedure [dbo].[spCompSalesQuantityWise]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompSalesQuantityWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCompSalesQuantityWise]
GO
/****** Object:  StoredProcedure [dbo].[spCompSalesValueWise]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompSalesValueWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCompSalesValueWise]
GO
/****** Object:  View [dbo].[vwcustomerGroupcategory]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerGroupcategory]'))
DROP VIEW [dbo].[vwcustomerGroupcategory]
GO
/****** Object:  View [dbo].[vwEligibleForDiscount]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwEligibleForDiscount]'))
DROP VIEW [dbo].[vwEligibleForDiscount]
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteCardRegistation]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeleteCardRegistation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpLmsDeleteCardRegistation]
GO
/****** Object:  StoredProcedure [dbo].[spLlmsGetCard]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLlmsGetCard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLlmsGetCard]
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLogin]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnolia_CheckLogin]
GO
/****** Object:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationHeader]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_SaveDeliveryVerificationHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_SaveDeliveryVerificationHeader]
GO
/****** Object:  View [dbo].[tempItems]    Script Date: 10/06/2012 14:17:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[tempItems]'))
DROP VIEW [dbo].[tempItems]
GO
/****** Object:  View [dbo].[vwGodownCloseDate]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownCloseDate]'))
DROP VIEW [dbo].[vwGodownCloseDate]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteRecepients]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_DeleteRecepients]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_DeleteRecepients]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteReportParameter]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_DeleteReportParameter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_DeleteReportParameter]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepost]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetByIdRepost]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetByIdRepost]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepostParameter]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetByIdRepostParameter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetByIdRepostParameter]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRecepients]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetRecepients]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetRecepients]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRepost]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetRepost]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetRepost]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetSettings]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetSettings]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetUsers]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_GetUsers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_GetUsers]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveRecepients]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_SaveRecepients]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_SaveRecepients]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReport]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_SaveReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_SaveReport]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReportParameter]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_SaveReportParameter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_SaveReportParameter]
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveSettings]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpEmail_SaveSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpEmail_SaveSettings]
GO
/****** Object:  StoredProcedure [dbo].[proc1]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc1]
GO
/****** Object:  StoredProcedure [dbo].[spFixedCost]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedCost]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spFixedCost]
GO
/****** Object:  StoredProcedure [dbo].[SP_MIS_GetCompanyImage]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MIS_GetCompanyImage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MIS_GetCompanyImage]
GO
/****** Object:  StoredProcedure [dbo].[Sp_param_SellingPrice]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_param_SellingPrice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Sp_param_SellingPrice]
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_SELLINGPRICE]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_SELLINGPRICE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FETCH_SELLINGPRICE]
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_AITEM]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_AITEM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FETCH_AITEM]
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_AITEMCATEGORY]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_AITEMCATEGORY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FETCH_AITEMCATEGORY]
GO
/****** Object:  View [dbo].[vwShopCloseDate]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCloseDate]'))
DROP VIEW [dbo].[vwShopCloseDate]
GO
/****** Object:  View [dbo].[vwFixedCost]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwFixedCost]'))
DROP VIEW [dbo].[vwFixedCost]
GO
/****** Object:  StoredProcedure [dbo].[spGetUser]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetUser]
GO
/****** Object:  View [dbo].[vwItemSearching]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSearching]'))
DROP VIEW [dbo].[vwItemSearching]
GO
/****** Object:  StoredProcedure [dbo].[spReturnValue]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReturnValue]
GO
/****** Object:  StoredProcedure [dbo].[spgodownitemnotinshop]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgodownitemnotinshop]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spgodownitemnotinshop]
GO
/****** Object:  StoredProcedure [dbo].[spGodownPriceList]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownPriceList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGodownPriceList]
GO
/****** Object:  StoredProcedure [dbo].[spReturnExrate]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnExrate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spReturnExrate]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStock]    Script Date: 10/06/2012 14:17:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateShopStock]
GO
/****** Object:  StoredProcedure [dbo].[CryptPwd]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CryptPwd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CryptPwd]
GO
/****** Object:  StoredProcedure [dbo].[Create_Login]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Create_Login]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Create_Login]
GO
--/****** Object:  StoredProcedure [dbo].[sp_sproc_columns]    Script Date: 10/06/2012 14:17:27 ******/
--IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_sproc_columns]') AND type in (N'P', N'PC'))
--DROP PROCEDURE [dbo].[sp_sproc_columns]
GO
/****** Object:  View [dbo].[vwshopstockitem]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockitem]'))
DROP VIEW [dbo].[vwshopstockitem]
GO
/****** Object:  StoredProcedure [dbo].[spForwardCosting]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spForwardCosting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spForwardCosting]
GO
/****** Object:  StoredProcedure [dbo].[spContainedRecords]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spContainedRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spContainedRecords]
GO
/****** Object:  StoredProcedure [dbo].[spPoItemListOrGDN]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPoItemListOrGDN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPoItemListOrGDN]
GO
/****** Object:  StoredProcedure [dbo].[spConvertCurrency]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertCurrency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spConvertCurrency]
GO
/****** Object:  StoredProcedure [dbo].[ErrorDemo]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ErrorDemo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ErrorDemo]
GO
/****** Object:  UserDefinedFunction [dbo].[FnConvertCustomerStatementToHtml]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FnConvertCustomerStatementToHtml]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[FnConvertCustomerStatementToHtml]
GO
/****** Object:  StoredProcedure [dbo].[usp_GetErrorInfo]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_GetErrorInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[usp_GetErrorInfo]
GO
/****** Object:  StoredProcedure [dbo].[spDishCategorySales]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDishCategorySales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDishCategorySales]
GO
/****** Object:  StoredProcedure [dbo].[spMag_RebuildAllIndexes]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_RebuildAllIndexes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_RebuildAllIndexes]
GO
/****** Object:  StoredProcedure [dbo].[spLedgerPreviewAfterPosting]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLedgerPreviewAfterPosting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLedgerPreviewAfterPosting]
GO
/****** Object:  UserDefinedFunction [dbo].[SplitStringByComma]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitStringByComma]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitStringByComma]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardSummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwGdnBinCardSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwGdnBinCardSummary]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryGodownStockSummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwInquiryGodownStockSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwInquiryGodownStockSummary]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryShopStockSummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwInquiryShopStockSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwInquiryShopStockSummary]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardAuditSummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwShopBincardAuditSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwShopBincardAuditSummary]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardBadQtySummary]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwShopBincardBadQtySummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwShopBincardBadQtySummary]
GO
/****** Object:  StoredProcedure [dbo].[spcompstockout]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcompstockout]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spcompstockout]
GO
/****** Object:  StoredProcedure [dbo].[spAccoutReceivableAudit]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAccoutReceivableAudit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAccoutReceivableAudit]
GO
/****** Object:  StoredProcedure [dbo].[spDaySales]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDaySales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDaySales]
GO
/****** Object:  StoredProcedure [dbo].[spGdnNonMovingItems]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGdnNonMovingItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGdnNonMovingItems]
GO
/****** Object:  StoredProcedure [dbo].[spDaySalesShopWise]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDaySalesShopWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDaySalesShopWise]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 10/06/2012 14:17:28 ******/
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
/****** Object:  StoredProcedure [dbo].[spLCRegister]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spLCRegister]
GO
/****** Object:  View [dbo].[vwOpeningStockValue]    Script Date: 10/06/2012 14:17:11 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOpeningStockValue]'))
DROP VIEW [dbo].[vwOpeningStockValue]
GO
/****** Object:  View [dbo].[vwPostingTransType]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPostingTransType]'))
DROP VIEW [dbo].[vwPostingTransType]
GO
/****** Object:  StoredProcedure [dbo].[spShopItemSales]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopItemSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopItemSales]
GO
/****** Object:  StoredProcedure [dbo].[spQuoteItReplace]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuoteItReplace]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spQuoteItReplace]
GO
/****** Object:  StoredProcedure [dbo].[spnonmovingitems]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spnonmovingitems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spnonmovingitems]
GO
/****** Object:  StoredProcedure [dbo].[spPaymentWithChequeDetails]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPaymentWithChequeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spPaymentWithChequeDetails]
GO
/****** Object:  StoredProcedure [dbo].[spServiceSalesDateWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spServiceSalesDateWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spServiceSalesDateWise]
GO
/****** Object:  StoredProcedure [dbo].[spSettledInvoice]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSettledInvoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSettledInvoice]
GO
/****** Object:  StoredProcedure [dbo].[spSetupLastYearData]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetupLastYearData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSetupLastYearData]
GO
/****** Object:  StoredProcedure [dbo].[spRatioDetails]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRatioDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRatioDetails]
GO
/****** Object:  StoredProcedure [dbo].[spRebuildAllIndex]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebuildAllIndex]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRebuildAllIndex]
GO
/****** Object:  StoredProcedure [dbo].[spRebatePayment]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebatePayment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spRebatePayment]
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSalesAllShops]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthWiseProductSalesAllShops]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMonthWiseProductSalesAllShops]
GO
/****** Object:  StoredProcedure [dbo].[spYearSales]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spYearSales]
GO
/****** Object:  StoredProcedure [dbo].[spYearSalesShopWise]    Script Date: 10/06/2012 14:17:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearSalesShopWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spYearSalesShopWise]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownGoodCheck]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownGoodCheck]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGodownGoodCheck]
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownCheck]    Script Date: 10/06/2012 14:17:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownCheck]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpUpdateGodownCheck]
GO
/****** Object:  StoredProcedure [dbo].[spHPDebtorAgeSum]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPDebtorAgeSum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPDebtorAgeSum]
GO
/****** Object:  UserDefinedFunction [dbo].[GetIndexColumnOrder]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetIndexColumnOrder]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetIndexColumnOrder]
GO
/****** Object:  StoredProcedure [dbo].[spMagnoliaReturnExrate]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnoliaReturnExrate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMagnoliaReturnExrate]
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSales]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthWiseProductSales]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMonthWiseProductSales]
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrdering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockOrdering]
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering1]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrdering1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockOrdering1]
GO
/****** Object:  StoredProcedure [dbo].[spStockOrderingOld]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrderingOld]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockOrderingOld]
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrdering]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockReOrdering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockReOrdering]
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrderingMonthlyWise]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockReOrderingMonthlyWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spStockReOrderingMonthlyWise]
GO
/****** Object:  StoredProcedure [dbo].[SpTotalBinCardAudit]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpTotalBinCardAudit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpTotalBinCardAudit]
GO
/****** Object:  StoredProcedure [dbo].[sptemp]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptemp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sptemp]
GO
/****** Object:  StoredProcedure [dbo].[spSalesAndStock]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAndStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesAndStock]
GO
/****** Object:  StoredProcedure [dbo].[spSalesAnalysisByItem]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAnalysisByItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesAnalysisByItem]
GO
/****** Object:  StoredProcedure [dbo].[spSalesAnalysisByItemGstSeparately]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAnalysisByItemGstSeparately]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spSalesAnalysisByItemGstSeparately]
GO
/****** Object:  StoredProcedure [dbo].[spsmsversion]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spsmsversion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spsmsversion]
GO
/****** Object:  UserDefinedFunction [dbo].[fnMultipleSplit]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnMultipleSplit]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnMultipleSplit]
GO
/****** Object:  StoredProcedure [dbo].[spMag_LocationwiseStock]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_LocationwiseStock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_LocationwiseStock]
GO
/****** Object:  View [dbo].[vwCompanyTotalStock]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyTotalStock]'))
DROP VIEW [dbo].[vwCompanyTotalStock]
GO
/****** Object:  UserDefinedFunction [dbo].[fnSplit]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnSplit]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnSplit]
GO
/****** Object:  UserDefinedFunction [dbo].[fnHourRange]    Script Date: 10/06/2012 14:17:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnHourRange]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnHourRange]
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumAllBills]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCreditorAgeSumAllBills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCreditorAgeSumAllBills]
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumBackup]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCreditorAgeSumBackup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCreditorAgeSumBackup]
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionUserWise]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailySalesCollectionUserWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailySalesCollectionUserWise]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSalesQtyWise]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerSalesQtyWise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerSalesQtyWise]
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollection]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailySalesCollection]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailySalesCollection]
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionBackUp]    Script Date: 10/06/2012 14:17:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailySalesCollectionBackUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDailySalesCollectionBackUp]
GO
/****** Object:  StoredProcedure [dbo].[spShopExpiryTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopExpiryTotalStockVerification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spShopExpiryTotalStockVerification]
GO
/****** Object:  StoredProcedure [dbo].[FindBlanktable]    Script Date: 10/06/2012 14:17:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FindBlanktable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[FindBlanktable]
GO
/****** Object:  StoredProcedure [dbo].[spCompanyOpeningStockAsOnDate]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompanyOpeningStockAsOnDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCompanyOpeningStockAsOnDate]
GO
/****** Object:  View [dbo].[vwCompanyItemFlow]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyItemFlow]'))
DROP VIEW [dbo].[vwCompanyItemFlow]
GO
/****** Object:  View [dbo].[vwCompanyBincard]    Script Date: 10/06/2012 14:17:06 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyBincard]'))
DROP VIEW [dbo].[vwCompanyBincard]
GO
/****** Object:  StoredProcedure [dbo].[spHPmonthwisesale]    Script Date: 10/06/2012 14:17:29 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPmonthwisesale]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spHPmonthwisesale]
GO
/****** Object:  View [dbo].[vwHpSaleMothwise]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpSaleMothwise]'))
DROP VIEW [dbo].[vwHpSaleMothwise]
GO
/****** Object:  View [dbo].[vwItemDescription]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription]'))
DROP VIEW [dbo].[vwItemDescription]
GO
/****** Object:  View [dbo].[vwCompBinCardWithOpening]    Script Date: 10/06/2012 14:17:07 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompBinCardWithOpening]'))
DROP VIEW [dbo].[vwCompBinCardWithOpening]
GO
/****** Object:  View [dbo].[vwtotalstockcolor]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalstockcolor]'))
DROP VIEW [dbo].[vwtotalstockcolor]
GO
/****** Object:  View [dbo].[vwstockcolor]    Script Date: 10/06/2012 14:17:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstockcolor]'))
DROP VIEW [dbo].[vwstockcolor]
GO
/****** Object:  View [dbo].[vwsellingtotalstockwithnegative_company]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstockwithnegative_company]'))
DROP VIEW [dbo].[vwsellingtotalstockwithnegative_company]
GO
/****** Object:  View [dbo].[vwsellingtotalstockwithnegative]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstockwithnegative]'))
DROP VIEW [dbo].[vwsellingtotalstockwithnegative]
GO
/****** Object:  View [dbo].[vwshopstockitemwithnegative]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockitemwithnegative]'))
DROP VIEW [dbo].[vwshopstockitemwithnegative]
GO
/****** Object:  View [dbo].[vwQuantityUnprocessed]    Script Date: 10/06/2012 14:17:12 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuantityUnprocessed]'))
DROP VIEW [dbo].[vwQuantityUnprocessed]
GO
/****** Object:  View [dbo].[vwDiffStockRecovery]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiffStockRecovery]'))
DROP VIEW [dbo].[vwDiffStockRecovery]
GO
/****** Object:  View [dbo].[vwHqDiffWriteOff]    Script Date: 10/06/2012 14:17:09 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqDiffWriteOff]'))
DROP VIEW [dbo].[vwHqDiffWriteOff]
GO
/****** Object:  View [dbo].[vwgodownstockitemwithnegative]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownstockitemwithnegative]'))
DROP VIEW [dbo].[vwgodownstockitemwithnegative]
GO
/****** Object:  StoredProcedure [dbo].[spCompanyMovingItems]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompanyMovingItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCompanyMovingItems]
GO
/****** Object:  StoredProcedure [dbo].[spAsonDateStockDepwise]    Script Date: 10/06/2012 14:17:27 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAsonDateStockDepwise]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spAsonDateStockDepwise]
GO
/****** Object:  View [dbo].[vwItemRetailPacking]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemRetailPacking]'))
DROP VIEW [dbo].[vwItemRetailPacking]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_SaveTransferOutDetails]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_SaveTransferOutDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_SaveTransferOutDetails]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_SaveTransferOutHeader]    Script Date: 10/06/2012 14:17:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_SaveTransferOutHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SpMag_SaveTransferOutHeader]
GO
/****** Object:  StoredProcedure [dbo].[spQuickItemInquiryWithFilterCondition]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuickItemInquiryWithFilterCondition]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spQuickItemInquiryWithFilterCondition]
GO
/****** Object:  StoredProcedure [dbo].[spQuickItemInquiry]    Script Date: 10/06/2012 14:17:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuickItemInquiry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spQuickItemInquiry]
GO
/****** Object:  View [dbo].[vwInquiryShopStock]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStock]'))
DROP VIEW [dbo].[vwInquiryShopStock]
GO
/****** Object:  View [dbo].[vwShopBincardAudit]    Script Date: 10/06/2012 14:17:13 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit]'))
DROP VIEW [dbo].[vwShopBincardAudit]
GO
/****** Object:  View [dbo].[vwshopbincardbadqty]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopbincardbadqty]'))
DROP VIEW [dbo].[vwshopbincardbadqty]
GO
/****** Object:  View [dbo].[vwShopItemShipmentDetail]    Script Date: 10/06/2012 14:17:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemShipmentDetail]'))
DROP VIEW [dbo].[vwShopItemShipmentDetail]
GO
/****** Object:  View [dbo].[vwInquirygodownStock]    Script Date: 10/06/2012 14:17:10 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquirygodownStock]'))
DROP VIEW [dbo].[vwInquirygodownStock]
GO
/****** Object:  View [dbo].[vwGdnBinCardBadQty]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardBadQty]'))
DROP VIEW [dbo].[vwGdnBinCardBadQty]
GO
/****** Object:  View [dbo].[vwGdnBinCard]    Script Date: 10/06/2012 14:17:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCard]'))
DROP VIEW [dbo].[vwGdnBinCard]
GO
/****** Object:  View [dbo].[vwGdnBinCard]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCard]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- Modified by          : Kishore
-- Modified on          : 17/12/2002
-- Comments             : Replaced the table loiGodownShopArrivalToLocation with
--                        loiArrivalShipmentDetail (17/12/2002)
--------------------------------------------------------------------------------
-- Modified by          : Kishore, Hariharan R
-- Modified on          : 22/11/2003, 14/01/2004
-- Comments             : Added CostPrice and stock value columns
--------------------------------------------------------------------------------
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--Modified By       : venkitesh
--comments         : 20/05/2004 Given depcost and compcost
--------------------------------------------------------------------------------
-- Upgraded By : Regin T.
-- Upgraded On : 23-07-2010
-- Upgrade     : Query Performance Tuning
--    Removed outer GROUP BY which is not necessary.
--    StockValue was commented which is not used in output.
--------------------------------------------------------------------------------
-- Modified by          : MANUNADH.U ON : 11/05/2011
-- Comments             : Added the column From/To for Bincard Audit report
--------------------------------------------------------------------------------
-- =============================================================================
CREATE VIEW [dbo].[vwGdnBinCard] AS
--select godownid, itemid, GDate, Transid, TransNo, TRansqty, Type, mode,updatetime,
--CostPrice,depcostprice,concostprice from (
--arrival from hq
select ad.adgodownid Godownid, ad.aditemid ItemId, ah.ahArrivaldate GDate,ah.aharrivalid TransId,
	ah.ahArrivalno TransNo,convert(numeric(18,3),sum(ad.adReceivedQty * pk.quantity * counts)) TransQty ,
	''Shipment Arrival'' as [Type], 1 Mode, UpdateTime, Min(adCostPrice) CostPrice,
	Min(adCostPrice)*ahdepexrate  DepCostPrice,Min(adCostPrice)*ahconexrate ConCostPrice
	--,sum(ad.adReceivedQty * pk.quantity * adCostPrice) StockValue
	--,case ahArrivalType
	--	when ''H'' then ''HQ''
	--	when ''G'' then ( Select godownname from aGodown where godownid=ah.ahGodownID)
	--	when ''S'' then ( select shopname from aShops where shopid=ah.ahShopID )
	-- end as ''From/To''
	,''HQ'' as ''From/To''
from  loiarrivalheader ah, loiarrivaldetail ad,aitem ai, aPackingTypeCapacityDetail pk, aunit u
where ah.ahcancelled=0 and ah.ahtransfinished=1 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 ai.unitsid = u.unitid
group by ad.adgodownid,ah.ahArrivaldate, ah.aharrivalid, ah.ahArrivalno, ad.aditemid,updatetime,
	ahdepexrate,ahconexrate
union all
--Transfer in from shop or godown
select  gal.asdGodownID, gal.asdItemId, ah.ahArrivaldate, ah.aharrivalid,
	ah.ahArrivalno TinNo, convert(numeric(18,3), isnull(sum(gal.asdReceivedGoodQty), 0))  as TinQty,
	''Transfer In'' as type, 1 mode, updatetime, Min(gal.asdcostprice) CostPrice,
	Min(gal.asdcostprice)*ahdepexrate depcostprice,Min(gal.asdcostprice)*ahconexrate concostprice
	--,sum(gal.asdReceivedGoodQty * asdCostPrice) StockValue
	,case ahArrivalType
		when ''H'' then ''HQ''
		when ''G'' then ( Select godownname from aGodown where godownid=ah.ahGodownID)
		when ''S'' then ( select shopname from aShops where shopid=ah.ahShopID )
	 end as ''From/To''
from loiarrivalheader ah
	--left outer join ashops s on s.ShopID=ah.TIHfromshopID,lostransferindetail d
	,loiArrivalShipmentDetail gal
where ah.aharrivalid = gal.asdArrivalID and
ah.ahlocalgodownid = gal.asdGodownId and ah.ahcancelled = 0 and ah.ahtransfinished = 1
group by gal.asdGodownId, ahArrivaldate, ah.aharrivalid,
ah.ahArrivalno, gal.asdItemId,updatetime,ahdepexrate,ahconexrate ,ah.ahArrivalType  ,ah.ahGodownID,ah.ahShopID
union all
--recovery add
select sr.srgodownid, sr.sritemid, sr.srdate, sr.srid  GrnNo,
	''Rec'' + convert(varchar(50), sr.srid) srno,
	convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd,
	''Recovery Plus'' as type , 1 mode, updatetime, Min(srCostPrice) CostPrice,
	Min(srCostPrice)* srDepExRate  depcostprice, Min(srCostPrice)*srConExRate concostprice
	--,sum(sr.srAddStock * srCostPrice)  StockValue
	,'''' as ''From/To''
from loistockrecovery sr
group by sr.srgodownid, sr.srid, sr.srdate,  sr.sritemid, updatetime,srConExRate,srDepExRate
having isnull(sum(sr.sraddstock),0) >0
union all
--itemsplitting adding
select isdgodownid, isditemid, ishdate, ishid, ishno, convert(numeric(18,3),isdqty),''Splitting Add'' as type,
	1 as mode, updatetime, IsNull(scf.scfdCostPrice, i.ItemRate) CostPrice,
	IsNull(scf.scfdCostPrice, i.ItemRate)*ishdepexrate  depCostPrice,
	IsNull(scf.scfdCostPrice, i.ItemRate)* ishconexrate conCostPrice
	--,isdQty * IsNull(scf.scfdCostPrice, i.ItemRate) StockValue
	,'''' as ''From/To''
from LoiItemSplitDetail sd Left Outer Join (Select scfhItemSplitId,
scfhGodownId, scfdItemId, scfdCostprice
From loaItemSplitCostingDetail scfd, loaItemSplitCostingHeader scfh
	Where scfhId = scfdId And scfhCancelled = 0) scf
On sd.isdItemId = scf.scfdItemID And sd.isdId = scf.scfhItemSplitId
	And sd.isdGodownId = scf.scfhGodownid, LoiItemSplitheader sh, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=sh.ishgodownid and sh.ishcancelled=0 and sd.isdIteMId = i.itemId
union all
--write off
select wd.wdGodownid RGId, wd.wditemid RItemID, wh.whDate RDate,
	wh.whid, wh.whNo WriteoffNo, convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty,
	''Write Off''  as Type, -1 mode,updatetime, Min(wd.wdCostPrice) CostPrice,
	Min(wd.wdCostPrice)*whdepexrate depCostPrice,
	Min(wd.wdCostPrice)*whconexrate conCostPrice
	--,Sum(-1 * wdWriteOffQty * wdCostPrice) StockValue
	,'''' as ''From/To''
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid=wd.wdid and wh.whgodownid=wd.wdgodownid and wh.whcancelled=0
group by wd.wdGodownid, wh.whDate, wh.whid, wh.whNo, wd.wditemid,updatetime,whdepexrate,whconexrate
union all
--Deapatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, dh.dhdespatchid, dh.dhDespatchNo DespatchNo,
	convert(numeric(18,3),sum(dd.dditemgoodqty)) as despatchqty,
	''Despatch To Shop'' as Type, -1 mode,updatetime, Min(ddcostedprice) CostPrice,
	Min(ddcostedprice)*dhdepexrate  depCostPrice,Min(ddcostedprice)*dhconexrate conCostPrice
	--,sum(-1 * ddItemGoodQty * ddCostedPrice) StockValue
	,s.ShopName as ''From/To''
from meidespatchtoshopheader dh,meidespatchtoshopdetail dd,ashops s
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0
	and dhtransfinished = 1 and s.ShopID=dh.dhShopID --added for new concept (hari 021019)
group by dd.ddgodownid, dh.dhDespatchDate, dh.dhDespatchNo, dh.dhdespatchid,
	dd.dditemid,updatetime,dhdepexrate ,dhconexrate,s.ShopName
union all
-- special despatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, dh.dhdespatchid,
	dh.dhDespatchNo DespatchNo, convert(numeric(18,3),sum(dd.dditemgoodqty)) as despatchqty,
	''Special Despatch'' as Type, -1 mode, updatetime, Min(ddCostedPrice) CostPrice,
	Min(ddCostedPrice)*dhdepexrate depCostPrice,Min(ddCostedPrice)*dhconexrate conCostPrice
	--,Sum(-1 * ddItemGoodQty * ddCostedPrice) StockValue
	,s.ShopName as ''From/To''
from meispecialdespatchtoshopheader dh, meispecialdespatchtoshopdetail dd,ashops s
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0 and s.ShopID=dh.dhShopID
group by dd.ddgodownid, dh.dhDespatchDate, dh.dhdespatchid, dh.dhDespatchNo,
	dd.dditemid,updatetime,dhdepexrate,dhconexrate,s.ShopName
union all
--Transferout
select gtdGodownid, gtditemid, gthDespatchDate, gthdespatchid,
	 gthDespatchNo ToutNo, convert(numeric(18,3),sum(isnull(gtdItemGoodQty,0))) as ToutQty,
	''Transfer Out'' as Type, -1 mode,updatetime, Min(gtdCostPrice) CostPrice,
	Min(gtdCostPrice)*gthdepexrate depCostPrice,Min(gtdCostPrice)*gthconexrate ConCostPrice
	--,Sum(-1 * gtdItemGoodQty * gtdCostPrice) StockValue
	,a.GodownName as ''From/To''
from meigodowntransferheader, meigodowntransferdetail,aGodown a
where gthdespatchid = gtddespatchid and gthFromGodownid = gtdgodownid and gthCancelled = 0
	and gthtransfinished = 1 --added for new concept (hari 021019)
	and gthToGodownID=a.GodownID
group by gtdGodownid, gthDespatchDate, gthdespatchid, gthDespatchNo, gtdItemid,
	updatetime,gthdepexrate,gthconexrate,a.GodownName
union all
--recovery minus
select sr.srgodownid, sr.sritemid, sr.srdate, sr.srid,''Rec'' + convert(varchar(50), sr.srid) GrnNo,
	convert(numeric(18,3),isnull(sum(sr.srdedstock),0))  as recded,
	''Recovery Minus'' as type, -1 mode, updatetime, Min(srCostPrice) CostPrice,
	Min(srCostPrice)*srDepExRate depCostPrice, Min(srCostPrice)*srconExRate conCostPrice
	--,Sum(-1 * srDedStock * srCostPrice) StockValue
	,'''' as ''From/To''
from loistockrecovery sr
group by sr.srgodownid, sr.srid, sr.srdate,  sr.sritemid,  updatetime,srDepExRate,srconExRate
having isnull(sum(sr.srdedstock),0) >0
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, svhid,
	svhno SvAddNo , convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,
	''Verification Plus'' as Type, 1 mode,updatetime, Min(svdCostPrice) CostPrice,
	Min(svdCostPrice)*svhdepexrate depCostPrice,Min(svdCostPrice)*svhconexrate conCostPrice
	--,sum((svdVerifiedStock - svdAvailStock) * svdCostPrice) StockValue
	,'''' as ''From/To''
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock > svdAvailStock
	and svhCancelled=0  and left(svhFutureVc, 1) <> ''t''
group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime,svhdepexrate,svhconexrate
union all
--stockverification minus
select svdGodownid, svdItemid, svhDate, svhid,
	svhno SvAddNo , convert(numeric(18,3),sum(svdAvailStock - svdVerifiedStock)) as svMinusQty,
	''Verification Minus'' as Type , -1 mode, updatetime, Min(svdCostPrice) CostPrice,
	Min(svdCostPrice)*svhdepexrate depCostPrice,Min(svdCostPrice)*svhconexrate conCostPrice
	--,Sum(-1 * (svdAvailStock - svdVerifiedStock) * svdCostPrice) StockValue
	,'''' as ''From/To''
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
	and svhCancelled = 0    and left(svhFutureVc, 1) <> ''t''
group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime,svhdepexrate,svhconexrate
UNION ALL
--TOTAL stock verification add
select svdGodownid, svdItemid, svhDate, svhid,
	svhno SvAddNo , convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,
	''Verification Plus'' as Type, 1 mode,updatetime, Min(svdCostPrice) CostPrice,
	Min(svdCostPrice)*svhdepexrate depCostPrice,Min(svdCostPrice)*svhconexrate conCostPrice
	--,sum((svdVerifiedStock - svdAvailStock) * svdCostPrice) StockValue
	,'''' as ''From/To''
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock > svdAvailStock
	and svhCancelled=0  and left(svhFutureVc, 2) = ''tc''
group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime,svhdepexrate,svhconexrate
union all
--ToTAL stockverification minus
select svdGodownid, svdItemid, svhDate, svhid,
	svhno SvAddNo , convert(numeric(18,3),sum(svdAvailStock - svdVerifiedStock)) as svMinusQty,
	''Verification Minus'' as Type , -1 mode, updatetime, Min(svdCostPrice) CostPrice,
	Min(svdCostPrice)*svhdepexrate depCostPrice,Min(svdCostPrice)*svhconexrate conCostPrice
	--,Sum(-1 * (svdAvailStock - svdVerifiedStock) * svdCostPrice) StockValue
	,'''' as ''From/To''
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
	and svhCancelled = 0    and left(svhFutureVc, 2) = ''tc''
group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime,svhdepexrate,svhconexrate
union all
--itemsplitting minus
select isdgodownid, ishSplititemid, ishdate, ishid, ishno,
	convert(numeric(18,3),sum(isdqty)) as splitminus,
	''Splitting Ded'' as type, -1 as mode,updatetime,
	Min(IsNull(scfhCostedPrice, i.ItemRate)) CostPrice,
	Min(IsNull(scfhCostedPrice, i.ItemRate))*ishdepexrate depCostPrice,
	Min(IsNull(scfhCostedPrice, i.ItemRate))*ishconexrate conCostPrice
	--,Sum(-1 * isdQty * IsNull(scfhCostedPrice, i.ItemRate)) StockValue
	,'''' as ''From/To''
from LoiItemSplitDetail sd, LoiItemSplitheader sh
	Left Outer Join loaItemSplitCostingHeader scfh On sh.ishId = scfh.scfhItemSplitId
	and sh.ishGodownId = scfh.scfhGodownId, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=sh.ishgodownid and sh.ishcancelled=0 and ishSplitItemId =i.ItemId
group by isdgodownid,isdid, ishSplititemid, ishdate,
	ishid, ishno,updatetime,ishdepexrate,ishconexrate
	
--)bincard
union all
--Merging minus
select lgdGodownID, lgdItemID, lghDate, lghid, lghno,convert(numeric(18,3), sum(lgsdqty)) as splitminus,
	''Merging Deduct'' as type, -1 as mode, lghUpdatetime,null,null,null ,'''' as ''From/To''
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid  and md.lgdgodownid = mh.lghgodownid and lghCancelled = 0
group by lgdGodownID, lgdItemID, lghDate, lghid, lghno, lghUpdatetime
Having sum(lgsdqty) <> 0
union all
--Merging Add
select lgdGodownID, lghItemID, lghDate, lghid, lghno,convert(numeric(18,3), sum(lgsdqty)) as splitminus,
	''Merging Add'' as type, 1 as mode, lghUpdatetime,null,null,null,'''' as ''From/To''
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid and md.lgdgodownid = mh.lghgodownid and lghCancelled = 0
group by lgdGodownID, lghItemID, lghDate, lghid, lghno, lghUpdatetime
Having sum(lgsdqty) <> 0'
GO
/****** Object:  View [dbo].[vwGdnBinCardBadQty]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardBadQty]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on 	: 05/06/2003
-- Modified by		: Kishore
-- Comments		: v3
--                        Avoided the Purchase return and asset convertion
--                        while taking write off records (05/06/2003)
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
CREATE VIEW [dbo].[vwGdnBinCardBadQty] AS
--write off
select wd.wdGodownid godownid, wd.wditemid ItemID, wh.whDate GDate,
wh.whid Transid, wh.whNo TransNo, convert(numeric(18,3),sum(wd.wdWriteoffQty)) as
badtransqty,
"Write Off"  as Type, 1 mode, updatetime
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid = wd.wdid
and wh.whgodownid = wd.wdgodownid
and wh.whcancelled = 0
and wh.whType = ''W''
group by wd.wdGodownid, wh.whDate, wh.whid, wh.whNo, wd.wditemid,updatetime
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, svhid,
svhno SvAddNo , convert(numeric(18,3),sum(svdVerifiedbadStock-svdAvailbadStock)) as
svAddQty,
"Bad Verification Plus" as Type, 1 mode,updatetime
from  loistockverificationheader, loistockverificationdetail where
svhid = svdid and svhgodownid = svdgodownid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime
union all
--stock verification deduct
select svdGodownid, svdItemid, svhDate, svhid,
svhno SvAddNo , convert(numeric(18,3),sum(svdAvailbadStock - svdVerifiedbadStock)) as
svAddQty,
"Bad Verification Minus" as Type, -1 mode,updatetime
from  loistockverificationheader, loistockverificationdetail where
svhid = svdid and svhgodownid = svdgodownid and svdAvailbadStock > svdVerifiedbadStock
and svhCancelled=0 group by svdGodownID, svhdate ,SvhNo, svhid, svdItemid,updatetime
union all
--damage qty clearance
select dcdgodownid, dcdItemID, dchClearingDate sdate, dchClearingID, dchClearingNo,
convert(numeric(18,3),sum(dcdWriteOffQty)) as svMinusQty,
"Damage Cleared" type, -1 mode,updatetime
from  LOiDamageClearingHeader, LOiDamageClearingdetails where
dchClearingID = dcdClearingID and dchgodownid = dcdgodownid
and dchcancelled = 0 group by  dcdgodownid, dchClearingDate, dchClearingID, dchClearingNo,
dcdItemid, updatetime'
GO
/****** Object:  View [dbo].[vwInquirygodownStock]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquirygodownStock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwInquirygodownStock    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on  : 11/12/02
--Modified by  : leo
--Comments  : v3 ]
--select * from vwinquirygodownstock where DepartmentId=15 and gsgodownid=16
CREATE view [dbo].[vwInquirygodownStock] as
select gsgodownid, gsitemid,convert(numeric(18,3), sum(isnull(gsstock,0))) gsstock,
sum(isnull(gsbadstock,0)) gsbadstock, sum(isnull(gsopeningstock,0)) gsopeningstock, sum(isnull(gsopeningbadstock,0))
gsopeningbadstock, 1 gsshipmentid, 1 gslocationid, max(isnull(gsitemcost,0)) gsitemcost,DepartmentId
from
(
select  gsgodownid, gsitemid, isnull(gsopeningstock,0) gsstock, isnull(gsopeningbadstock,0) gsbadstock,
isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost,DepartmentId
from moigodownstock sd
LEFT OUTER JOIN aGodown g on g.GodownID=sd.gsgodownid
group by g.DepartmentId,gsgodownid,gsitemid,gsopeningstock,gsopeningbadstock,gsopeningstock,gsopeningbadstock,
gsitemcost
union all
select sd.godownid, itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) gsstock, 0, 0, 0, 0,DepartmentId from
vwgdnbincard sd
LEFT OUTER JOIN aGodown g on g.GodownID=sd.godownid
group by  sd.godownid,itemid ,DepartmentId
union all --for taking bad qty
select sd.godownid,itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) gsbadstock,
0, 0, 0,DepartmentId
from vwgdnbincardbadqty sd
LEFT OUTER JOIN aGodown g on g.GodownID=sd.godownid
group by sd.godownid, itemid,DepartmentId
) inqstock
group by GSgodownid, GSitemid ,DepartmentId --,gsstock,gsbadstock,gsopeningstock,gsopeningbadstock,gsitemcost,'
GO
/****** Object:  View [dbo].[vwShopItemShipmentDetail]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemShipmentDetail]'))
EXEC dbo.sp_executesql @statement = N'
----
-- Last Modified on  : 09/12/2003
-- Modified by  : Kishore
-- Comments  : Added the group by to avoice duplicate rows
--                        when an item has selling price both shop wise and hq wise
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified By: Regin
-- Modified On: 07-09-2009
-- Purpose: Added  pricefixedathq=0 , pricefixedathq=1 conditions.
-- Selling Price fixation mode can be changed at any time.
-- Say, for an item selling price was fixed at HQ when it was added to company.
-- But after a long time, selling price was fixed at shops.
-- In this case losshopitemshipmentdetail table has both selling prices.
-- To get the selling price based on the current mode of selling price fixation,
-- those condition was added.
--------------------------------------------------------------------------------
--Altered by Aadyakumar.D.V on 16/06/2011 added departmentid
--Altered by Aadyakumar.D.V on 11/07/2011 added Pricechanged=0 to correct WMR-990060
/*
ALTERED BY : SHINE DAS
ON : 23-07-2011
COMMENT: Added Currency Symbol to the view
*/
CREATE view [dbo].[vwShopItemShipmentDetail]
AS
select a.currencyid, itemid, shopid,packingtypeid,
Min(sellingprice) SellingPrice, Min(wholesaleprice) WholeSalePrice,
Min(discountprice) DiscountPrice,DepartmentID,a.Symbol
from (
-- If Selling Price is fixed at Shops, select SP of each shop.
select  sd.currencyid, sd.itemid, sd.shopid,packingtypeid,
sellingprice,wholesaleprice,discountprice,DepartmentID,cm.Symbol
from  aItem i,aCurrencyMaster cm, losshopitemshipmentdetail sd
LEFT OUTER JOIN ashops s on sd.shopid=s.shopid
where  sd.ItemID=i.ItemID and sd.shopid is not null  and sd.currencyid = cm.currencyid
and i.pricefixedathq=0 -- For only those items whom selling price fixed at Shops
and Pricechanged=0
union all
-- If Selling Price is fixed at HQ, apply that SP to all shops.
select  sd.currencyid, sd.itemid, s.shopid, sd.packingtypeid,
sd.sellingprice, sd.wholesaleprice, sd.discountprice,s.DepartmentID,cm.Symbol
from losshopitemshipmentdetail sd, aItem i,aCurrencyMaster cm , ashops s
LEFT OUTER JOIN aDepartmentMaster d on s.DepartmentID=d.DepartmentID
where sd.ItemID=i.ItemID and sd.shopid is null and sd.currencyid = cm.currencyid
and i.pricefixedathq=1 -- For only those items whom selling price fixed at HQ
and Pricechanged=0
) a
--where itemid=302 and shopid in(select shopid from vwInquiryShopStock where itemid= 302)
group by itemid, shopid,packingtypeid, a.currencyid, DepartmentID,a.Symbol'
GO
/****** Object:  View [dbo].[vwshopbincardbadqty]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopbincardbadqty]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopbincardbadqty    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
---------------------------------------------------------------------------------------------
--Last Modified on  : 16/06/2008
--Modified by  : Benzigar
--Comments  : Add Purchase Return
CREATE view [dbo].[vwshopbincardbadqty] as
--stock verification add
select svdshopid shopid , svdItemid itemid, svhDate sdate, svhid transid, svhno transno,
convert(numeric(18,3),sum(svdVerifiedbadStock-svdAvailbadStock)) as badtransqty,
''Bad Verification Plus'' Type, 1 mode,updatetime
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 group by   svdShopID, svhdate, svhid, svhno, svdItemid,updatetime
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whid, wh.whno,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as badtransqty, ''Write off'' TYpe, 1 mode,updatetime
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and wh.whType=''W'' group by
wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whid, Ph.whno,
convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as badtransqty, ''Purchase Return'' TYpe, 1 mode,updatetime
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whType=''P'' group by
Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhid, svhno,
convert(numeric(18,3),sum(svdAvailbadStock-svdVerifiedbadStock)) as svMinusQty,
''Bad Verification Minus'' type, -1 mode,updatetime
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock < svdAvailbadStock
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime
union all
--damage cleared
select dcdShopid, dcdItemID, dchClearingDate sdate, dchClearingID, dchClearingNo,
convert(numeric(18,3),sum(dcdWriteOffQty)) as svMinusQty,
''Damage Cleared'' type, -1 mode,updatetime
from  LOsShopDamageClearingHeader, LOsShopDamageClearingdetails where
dchClearingID = dcdClearingID and dchShopid = dcdShopid
and dchcancelled = 0 group by  dcdShopid, dchClearingDate, dchClearingID, dchClearingNo,
dcdItemid, updatetime'
GO
/****** Object:  View [dbo].[vwShopBincardAudit]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified By   : Benzigar 23092008
-- Modified Date : 23092008
-- Comment       : Added Business Promotion/Warrenty claim
-- =====================================
-- Upgraded By : Regin T.
-- Upgraded On : 22-07-2010
-- Upgrade     : An outer Group By clause was used to change
--   the position of TransId and TransNo fields.
--   This Group By clause casued delay. So I removed it, and
--   changed the position of fields in all union all parts.
--   Old position: TransId, TransNo
--   New position: TransNo, TransId
-- =====================================
-- Upgraded By : Regin T.
-- Upgraded On : 18-09-2010
-- Upgrade     : Added FandB Bill
-- =====================================
-- Upgraded By : NIDHEESH P.V.
-- Upgraded On : 09-02-2011
-- Upgrade     : Added In-House Return
-- =====================================
--------------------------------------------------------------------------------
-- Modified by          : MANUNADH.U ON : 11/05/2011
-- Comments             : Added the column From/To for Bincard Audit report
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011
-- Comments             : Bug fixed in transfer out
--------------------------------------------------------------------------------
--Modified by          : Nidheesh P V
--Modified on		   : 6/07/2011
--Comments             : Added In-House Consumption part seperately.
--Modified Area        : All Interfaces where stock effects
--Referenc No          : Ref-No1
--------------------------------------------------------------------------------
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U
-- Modified on	: 26/03/2012
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
--------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopBincardAudit]  AS
--arrival from godown
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,
convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,''Arrival From Godown'' [Type],
1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,
gadCostPrice * gahconexrate ConCostPrice,
--(case when g.GodownName IS null then ''HQ'' else g.GodownName end  + ''/'' + s.ShopName)  as ''From/To''
(case when g.GodownName IS null then ''HQ'' else g.GodownName end  )  as ''From/To''
from losgoodsarrivaltoshopheader h
left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID
left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,
gahdepexrate, gahconexrate,g.GodownName,s.ShopName
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,
GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,''Goods Return'',1 as mode,
updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,
'''' as ''From/To''
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0
and GRNDDamaged=0
union all
--transfer in
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,
convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, ''Transfer In'' TYpe, 1 mode,updatetime, tidCostPrice,
tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as ''From/To''
from lostransferinheader h
left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,
tihdepexrate, tihconexrate,s.ShopName
union all
--recovery add
select sr.srshopid, sr.sritemid, sr.srdate sdate, ''Rec'' + convert(varchar(50), sr.srid) srno, sr.srid,
convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, ''Recovery Plus'' Type,1 Mode,updatetime,
srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'''' as ''From/To''
from losstockrecovery sr
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,''Verification Plus'' Type, 1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and
left(svhFutureVc, 1) <> ''t''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate
union all
--TOTAL stock verification add
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,''Verification Plus'' Type, 1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and
left(svhFutureVc, 2) = ''tc''
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate
union all
--exchange in
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,
convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, ''Exchanged In'' Type,1 mode,updatetime,
sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'''' as ''From/To''
from losposexchangeheader, losposexchangedetail
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPrice, sehDepExrate, sehExchangerate
union all
--local purchase
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,''Local Purchase'' Type, 1 mode,updatetime,
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'''' as ''From/To''
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1--Ref-No2
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,
	lphdepexrate,lphExchangerate
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, ''Write off'' TYpe, -1 mode,updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'''' as ''From/To''
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and  whtype<>''I'' --Ref-No1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--InHouse Cons   --Ref-No1
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, ''In-House Cons'' TYpe, -1 mode,updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'''' as ''From/To''
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and  whtype=''I'' and whVerified=1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Despatch
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghNo, dh.dghid,
convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,''Despatch To Godown'' TYpe, -1 mode,updatetime,
dgdCostPrice,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice
,g.GodownName  as ''From/To''
from mesdespatchtogodownheader dh
left outer join aGodown g on g.GodownID=dh.dghGodownID,mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,
dgdCostPrice, dghdepexrate, dghconexrate,g.GodownName
union all
----Transferout
--select todshopid, toditemid, tohDate sdate, tohno, tohid,
-- convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty , ''Transfer Out'' Type,-1 mode,updatetime, todCostPrice,
-- todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as ''From/To''
--from mestransferoutheader h
-- left outer join ashops s on s.ShopID=h.TOHtoShopid,lostransferindetail d ,mestransferoutdetail
--where tohid=todid and Tohshopid=todshopid and tohcancelled=0
-- and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
--group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,
-- tohdepexrate, tohConExrate,s.ShopName
--Transferout
select todshopid, toditemid, tohDate sdate, tohno, tohid,
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty ,
''Transfer Out'' Type,-1 mode,updatetime, todCostPrice,
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as ''From/To''
from mestransferoutdetail inner join mestransferoutheader h
on tohid=todid and Tohshopid=todshopid and tohcancelled=0 and tohtransfinished = 1 inner join
ashops s on s.ShopID=h.TOHtoShopid --inner join lostransferindetail on TODitemid=TIDitemID
--where TOHShopid=5 and TODitemid=8626
group by todissuedgoodqty,tohid,todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,
tohdepexrate, tohConExrate,s.ShopName
union all
--recovery minus
select sr.srshopid, sr.sritemid, sr.srdate sdate,''Rec'' + convert(varchar(50), sr.srid) srno, sr.srid,
convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, ''Recovery Minus'' type,-1 Mode, updatetime,
srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'''' as ''From/To''
from losstockrecovery sr
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,''Verification Minus'' type, -1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--Total stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,''Verification Minus'' type, -1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,
'''' as ''From/To''
from losstockverificationheader,losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--pos sales
select poshShopID, posditemid, poshBilldate sdate, poshBillNo, poshbillid,
convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,''Cash Sales'' as type, -1 mode,updatetime,
posdCostPrice,posdCostPrice * poshdepexrate depCostPrice,posdCostPrice * poshExchangeRate ConCostPrice
,'''' as ''From/To''
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
group by poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate
union all
--credit invoice
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,
convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, ''Credit Sales'' Type,
-1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,
idCostPrice * ihExchangeRate ConCostPrice,'''' as ''From/To''
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0 and ihType =''I''
group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,
updatetime, idCostPrice, ihdepexrate, ihExchangeRate
union all
--exchange out
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,
convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,
''Exchange Out'' Type, -1 mode,updatetime, sedCostPRice,
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'''' as ''From/To''
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPRice, sehdepexrate, sehExchangerate
union all
--special invoice return to shop
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,
convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, ''Special Invoice Return'' Type,
1 mode,updatetime, idCostPrice,
idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,'''' as ''From/To''
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
group by ihshopid, ihinvoicedate, ihInvoiceid,
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate
-- transfinished added as stock is updated only after confirming
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select serinvhShopid, repinvdpartsid, serinvhdate , serinvNo, serinvhid,
convert(numeric(18,3) , sum(repinvdqty)) , ''Parts Replaced'' type,-1 as mode, serinvhupdatetime, repinvdcostprice,
repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,'''' as ''From/To''
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,
serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate
union all
--Re-Exporting
select rehShopID, reditemid, rehExportDate sdate, rehExportNo, rehExportID,
convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, ''Re-Export'' Type,
-1 mode, rehUpdatetime, redCostPrice,
redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,'''' as ''From/To''
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0 and rehType=''I''
group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate
union all
--MerGing minus
select lsdShopID, lsdItemID, lshDate, lshno, lshid,convert(numeric(18,3), sum(lsdqty)) as mergeded,
''Merging Deduct'' as type, -1 as mode, lshUpdatetime,null,null,null,'''' as ''From/To''
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid and md.lsdShopid = mh.lshShopId and lshCancelled=0
group by lsdShopID, lsdItemID, lshDate, lshid, lshno, lshUpdatetime
Having Sum(lsdQty) <> 0
union all
--MerGing Add
select lsdShopID, lshItemID, lshDate, lshno, lshid,convert(numeric(18,3),sum(lsdqty)) as splitminus,
''Merging Add'' as type, 1 as mode, lshUpdatetime,null,null,null,'''' as ''From/To''
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid and md.lsdShopID = mh.lshShopid and lshCancelled = 0
group by lsdShopID, lshItemID, lshDate, lshid, lshno, lshUpdatetime
Having Sum(lsdQty) <> 0
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whno, Ph.whid,
convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, ''Purchase Return'' TYpe, -1 mode,
updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'''' as ''From/To''
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1
group by Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Warrenty Claim/Business promotion
select wchShopID, wcditemid, wchdate sdate, wchNo, wchid,convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,
''WC/BP'' as type, -1 mode,wchupdatedtime, wcdCostPrice,wcdCostPrice * wchdepexrate depCostPrice,
wcdCostPrice * wchcomexrate ConCostPrice,'''' as ''From/To''
from losWarrentyClaimDetail,losWarrentyClaimHeader
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0
group by wchShopid, wchid, wchNo, wchdate, wchid, wchNo,
wcditemid,wchupdatedtime, wcdCostPrice, wchdepexrate, wchcomexrate
union all
-----Hire Purchase Invoice
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationNo,hpqhQuotationID,1 as Qty, ''Hire Purchase'' Type,
-1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,'''' as ''From/To''
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I''
group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,hpqhUpdatetime,hpqdCostPrice
union all
-- Food and Beverages Bill - added by Regin on 18-09-2010
SELECT Fb_kh_outletid, a.fb_ItemID, DATEADD(D, 0, DATEDIFF(D, 0, Fb_kh_kotdatetime)) sdate,Fb_kh_kotno, Fb_kh_kotid,
a.KotOrder,''FandB Bill'' Type, -1 mode, Fb_kh_kotdatetime,fb_costprice, fb_costprice*h.fb_depexrate depCostPrice,
fb_costprice*h.fb_ExchangeRate conCostPrice,'''' as ''From/To''
from fb_kotheader h
inner join fb_alternate a on Fb_kh_kotid=fb_kotID
where Fb_kh_cancelled=0
union all
--InHouse Return
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,
convert(numeric(18,3),sum(IHRDReturnedqty)) as IHRDReturnedqty,''In-House Return'' Type,1 mode,updatetime,
IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice
,'''' as ''From/To''
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1
AND (IHRDRetrnOrExch=''R'' OR IHRDRetrnOrExch=''B'' OR IHRDRetrnOrExch IS NULL) AND IHRDReturnedqty<>0
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,
IHRDcostprice,IHRHdepexrate,IHRHconexrate
UNION ALL
--InHouse Exchanged In
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,
convert(numeric(18,3),sum(IHRDArrivedQty)) as IHRDExchgdqty,''In-House Exchnaged In'' Type,-1 mode,updatetime,
IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice,'''' as ''From/To''
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND
IHRHConfirmed=1 AND IHRDRetrnOrExch=''E'' AND IHRDArrivedQty<>0
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,IHRDcostprice,IHRHdepexrate,IHRHconexrate'
GO
/****** Object:  View [dbo].[vwInquiryShopStock]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStock]'))
EXEC dbo.sp_executesql @statement = N'
--Altered by Aadyakumar.D.V on 16/06/2011:added new column departmentid
CREATE VIEW [dbo].[vwInquiryShopStock] AS
SELECT
ShopId, ItemId, convert(numeric(18,3), sum(stock)) Stock
, sum(badstock) BadStock, sum(openingstock) OpeningStock
, sum(openingbadstock) OpeningBadStock
, 1 ShipmentId, max(itemcostprice) ItemCostPrice,DepartmentID
FROM (
-- 1. Opening Stock
SELECT
mo.ShopID, itemid, openingstock stock, isnull(openingbadstock,0) badstock
, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
, itemcostprice,s.DepartmentID
FROM mosshopstock mo
LEFT OUTER JOIN ashops s on s.ShopID=mo.shopid
UNION ALL
-- 2. Shop Bin Card For Good Stock
SELECT
mo.ShopId,itemid, transqty * mode stock
, 0, 0, 0, 0,s.DepartmentID
FROM vwshopbincardaudit  mo
LEFT OUTER JOIN ashops s on s.ShopID=mo.shopid
UNION ALL
-- 3. Shop Bin Card For Bad Stock
SELECT mo.shopid,itemid,  0,  badtransqty * mode stock
, 0, 0, 0,s.DepartmentID
FROM vwshopbincardbadqty mo
LEFT OUTER JOIN ashops s on s.ShopID=mo.shopid
) inqstock
GROUP BY shopid, itemid,DepartmentID'
GO
/****** Object:  StoredProcedure [dbo].[spQuickItemInquiry]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuickItemInquiry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Ref.No.1
--Modified On:02/07/2011
--Modified By:Aadyakumr.D.V
--As per Client requirement BBI-575322 is modified as,while trying to load Quick item department wise,sub-department
--data also need to show.
--spQuickItemInquiry 1,3,0,0
CREATE proc [dbo].[spQuickItemInquiry]
(@intcompanyid as int,
@intDepartmentId as int,
@intShopId as int,
@intGodownid as int)
as
declare @StrShopType as char(1)
begin
if @intShopId<>0
begin
select @StrShopType=substring(futurevarchar,1,1) from ashops where shopid=@intShopId
end
else
begin
set @StrShopType=''''
end
declare @StrSql as varchar(2000)
-----------------------------------------------
--if  @intDepartmentId=0
--begin
select * into #tempshopitemshipmentdetail from
(
select max(isnull(sellingprice,0)) sellingprice,max(isnull(wholesaleprice,0)) wholesaleprice,
max(isnull(discountprice,0)) discountprice,Shopid,ItemID,PackingTypeID
from  vwshopitemshipmentdetail
group by ShopId,ItemID,PackingTypeID
)a
--end
--else
--begin
--select * into #tempshopitemshipmentdetail from
--(
--select max(isnull(sellingprice,0)) sellingprice,max(isnull(wholesaleprice,0)) wholesaleprice,
--max(isnull(discountprice,0)) discountprice,Shopid,ItemID,PackingTypeID
--from  vwshopitemshipmentdetail
--group by ShopId,ItemID,PackingTypeID
--)a
--end
---------------------
select * into #tempInquiryShopStock from
(select * from vwInquiryShopStock where (shopid=@intShopId or @intShopId=0)
)b
----------------------
select * into #tempinquirygodownstock from
(select * from vwinquirygodownstock where (gsgodownid=@intGodownid or @intGodownid=0)
)c
----------------------
Select a.itemid,itemcode,itemdescription,CategoryNameDescription,
unitname,PackingTypeName,colorname,sizename,isnull(brand,'''') brand,isnull(Part_code,0) partcode,
ShopName AS Location,convert(numeric(18,2),(isnull(vs.stock,0)/isnull(Quantity,1)))Stock,
SellingPrice,WholeSalePrice,DiscountPrice,ItemRate,
vs.ShopID ShopID,s.DepartmentID DepartmentID,0 as GodownID--aadya
from aitem a
left outer join aunit on a.unitsid = unitid and a.Active = 1 and ((@StrShopType=''B'' and a.itemtype =@StrShopType)or (@StrShopType='''' and a.itemtype <>''B''))
left outer join aColor on a.colorid = acolor.colorid
left outer join aSize on a.sizeid = asize.sizeid
left outer join aItemCategory ic on a.ItemCategoryID=ic.ItemCategoryID
left outer join aitempackingdetail pd on a.itemid = pd.itemid and PackingSlNo=1
left outer join apackingtype pt on pd.PackingTypeID = pt.PackingTypeID
left outer join apackingtypecapacitydetail pc on pc.PackingTypeID=pt.PackingTypeID and pc.UnitsID=a.UnitsID
left outer join #tempInquiryShopStock vs on vs.itemid=a.itemid
left outer join ashops s on s.shopid=vs.ShopID and s.CompanyID=@intcompanyid
----Ref.No.1--start
and (s.DepartmentID in (select DepartmentID from aDepartmentMaster where DepartmentID=@intDepartmentId or ParentDepId=@intDepartmentId)  or @intDepartmentId=0)
and (s.shopid=@intShopId or @intShopId=0)
--Ref.No.1---end
--left outer join #tempinquirygodownstock vg on vg.gsitemid=a.itemid
--left outer join agodown g on g.GodownID=vg.gsgodownid and g.CompanyID=@intcompanyid
--and (g.DepartmentId=@intDepartmentId or @intDepartmentId=0) and (g.GodownID=@intGodownid or @intGodownid=0)
left outer join #tempshopitemshipmentdetail sd on sd.itemid=vs.itemid
and sd.shopid=vs.shopid and sd.packingtypeid=pt.PackingTypeID
Where
--(s.DepartmentID =(select DepartmentID from aDepartmentMaster where DepartmentID=@intDepartmentId or ParentDepId=@intDepartmentId)
--or @intDepartmentId=0) and
s.shopid is not null
UNION ALL
Select a.itemid,itemcode,itemdescription,CategoryNameDescription,
unitname,PackingTypeName,colorname,sizename,isnull(brand,'''') brand,isnull(Part_code,0) partcode,
GodownName AS Location,convert(numeric(18,2),(isnull(vg.gsstock,0)/isnull(Quantity,1)))Stock
,''0'' SellingPrice,''0'' WholeSalePrice,''0'' DiscountPrice,''0'' ItemRate,
0 as ShopID,g.DepartmentId DepartmentID,vg.gsgodownid as GodownID--aadya
from aitem a
left outer join aunit on a.unitsid = unitid and a.Active = 1 and ((@StrShopType=''B'' and a.itemtype =@StrShopType)or (@StrShopType='''' and a.itemtype <>''B''))
left outer join aColor on a.colorid = acolor.colorid
left outer join aSize on a.sizeid = asize.sizeid
left outer join aItemCategory ic on a.ItemCategoryID=ic.ItemCategoryID
left outer join aitempackingdetail pd on a.itemid = pd.itemid and PackingSlNo=1
left outer join apackingtype pt on pd.PackingTypeID = pt.PackingTypeID
left outer join apackingtypecapacitydetail pc on pc.PackingTypeID=pt.PackingTypeID and pc.UnitsID=a.UnitsID
--left outer join #tempInquiryShopStock vs on vs.itemid=a.itemid
--left outer join ashops s on s.shopid=vs.ShopID and s.CompanyID=@intcompanyid
--and (s.DepartmentID=@intDepartmentId or @intDepartmentId=0) and (s.shopid=@intShopId or @intShopId=0)
left outer join #tempinquirygodownstock vg on vg.gsitemid=a.itemid
left outer join agodown g on g.GodownID=vg.gsgodownid and g.CompanyID=@intcompanyid
--Ref.No.1 ---start
and (g.DepartmentId in(select DepartmentID from aDepartmentMaster where DepartmentID=@intDepartmentId
or ParentDepId=@intDepartmentId) or @intDepartmentId=0)
and (g.GodownID=@intGodownid or @intGodownid=0)
--Ref.No.1---end
--left outer join #tempshopitemshipmentdetail sd on sd.itemid=vs.itemid
--and sd.shopid=vs.shopid and sd.packingtypeid=pt.PackingTypeID
where
--g.GodownID=(select DepartmentID from aDepartmentMaster where DepartmentID=@intDepartmentId
--or ParentDepId=@intDepartmentId) and
g.GodownID is not null
order by a.itemid
drop table #tempInquiryShopStock
drop table #tempinquirygodownstock
drop table #tempshopitemshipmentdetail
end
/*
-- Previous backup
CREATE proc spQuickItemInquiryBACKUP (@intcompanyid as int,@intDepartmentId as int,@intShopId as int,@intGodownid as int)
as
declare @StrShopType as char(1)
begin
if @intShopId<>0
begin
select @StrShopType=substring(futurevarchar,1,1) from ashops where shopid=@intShopId
end
else
begin
set @StrShopType=''''
end
select * into #tempshopitemshipmentdetail from
(select max(sellingprice) sellingprice,max(wholesaleprice) wholesaleprice,
max(discountprice) discountprice,Shopid,ItemID,PackingTypeID
from  vwshopitemshipmentdetail
group by ShopId,ItemID,PackingTypeID
)a
---------------------
select * into #tempInquiryShopStock from
(select * from vwInquiryShopStock where (shopid=@intShopId or @intShopId=0)
)b
----------------------
select * into #tempinquirygodownstock from
(select * from vwinquirygodownstock where (gsgodownid=@intGodownid or @intGodownid=0)
)c
----------------------
Select a.itemid,itemcode,itemdescription,CategoryNameDescription,
unitname,PackingTypeName,colorname,sizename,isnull(brand,'''') brand,isnull(Part_code,0) partcode,
--Quantity,isnull(dname,'''') disname,
ShopName,convert(numeric(18,2),(isnull(vs.stock,0)/Quantity))ShopStock,
GodownName,convert(numeric(18,2),(isnull(vg.gsstock,0)/Quantity))GodownStock,
--sum(convert(numeric(18,2),(isnull(vs.stock,0)/Quantity)))over (partition by a.itemid)TotalShopStock,
SellingPrice,WholeSalePrice,DiscountPrice,ItemRate
from aitem a left outer join aunit on a.unitsid = unitid and a.Active = 1 and ((@StrShopType=''B'' and a.itemtype =@StrShopType)or (@StrShopType='''' and a.itemtype <>''B''))
left outer join aColor on a.colorid = acolor.colorid
left outer join aSize on a.sizeid = asize.sizeid
left outer join aItemCategory ic on a.ItemCategoryID=ic.ItemCategoryID
--left outer join adistributormaster on a.did=adistributormaster.did
left outer join aitempackingdetail pd on a.itemid = pd.itemid and PackingSlNo=1
left outer join apackingtype pt on pd.PackingTypeID = pt.PackingTypeID
left outer join apackingtypecapacitydetail pc on pc.PackingTypeID=pt.PackingTypeID and pc.UnitsID=a.UnitsID
left outer join #tempInquiryShopStock vs on vs.itemid=a.itemid
--and (vs.shopid=@intShopId or @intShopId=0)
left outer join ashops s on s.shopid=vs.ShopID and s.CompanyID=@intcompanyid
and (s.DepartmentID=@intDepartmentId or @intDepartmentId=0) and (s.shopid=@intShopId or @intShopId=0)
left outer join #tempinquirygodownstock vg on vg.gsitemid=a.itemid
--and (vg.gsgodownid=@intGodownid or @intGodownid=0)
left outer join agodown g on g.GodownID=vg.gsgodownid and g.CompanyID=@intcompanyid
and (g.DepartmentId=@intDepartmentId or @intDepartmentId=0) and (g.GodownID=@intGodownid or @intGodownid=0)
left outer join #tempshopitemshipmentdetail sd on sd.itemid=vs.itemid and sd.shopid=vs.shopid and sd.packingtypeid=pt.PackingTypeID
where --a.itemid=1 and
(s.shopid is not null or g.GodownID is not null)
order by a.itemid
drop table #tempInquiryShopStock
drop table #tempinquirygodownstock
drop table #tempshopitemshipmentdetail
end
*/' 
END
GO
/****** Object:  StoredProcedure [dbo].[spQuickItemInquiryWithFilterCondition]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuickItemInquiryWithFilterCondition]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created On:26/04/2011
--Created By:Aadyakumar.D.V
--Purpose   :To Perform Quick Item Inquiry for a given filter condition.
--sp_helptext spQuickItemInquiryWithFilterCondition
--spQuickItemInquiry 1,15,5,0
--spQuickItemInquiryWithFilterCondition 1,3,0,0,'''' ,''%%'',''D''
--spQuickItemInquiryWithFilterCondition 1,3,0,0,'''',''%%'',''A''
--select count(*) from tempResult where itemdescription like ''%can%''
--select * from tempResult where itemdescription like ''%c%''
--IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[tempResult]'') AND type in (N''U''))
--DROP TABLE [dbo].[tempResult]
--go
--Ref.No.1
--Modified On:02/07/2011
--Modified By:Aadyakumr.D.V
--As per Client requirement BBI-575322 is modified as,while trying to load Quick item department wise,sub-department
--data also need to show.
CREATE proc [dbo].[spQuickItemInquiryWithFilterCondition] (
@intcompanyid as int,
@intDepartmentId as int,
@intShopId as int,
@intGodownid as int,
@filtercolumn as varchar(150),
@filtercodition as varchar(150),
@filtertype as char--A-All ,S-shop ,G-Godown,D-Department
)
as
begin
DECLARE @idtype AS varchar(30)
create table #tempResult(
itemid int,
itemcode varchar(50),
itemdescription varchar(200),
CategoryNameDescription varchar(200),
unitname varchar(200),
PackingTypeName varchar(200),
colorname varchar(200),
sizename varchar(200),
brand varchar(200),
partcode varchar(200),
Location varchar(200),
Stock numeric,
SellingPrice numeric,
WholeSalePrice numeric,
DiscountPrice numeric,
ItemRate numeric,
shopid int,
DepartmentId int,
GodownID int
)
DECLARE @SQL VARCHAR(1000)
--insert #tempResult exec spQuickItemInquiry @intcompanyid,@intDepartmentId,@intShopId,@intGodownid
if  @intDepartmentId=0
begin
if @intShopId=0
begin
insert #tempResult exec spQuickItemInquiry @intcompanyid,0,0,@intGodownid
end
else
begin
insert #tempResult exec spQuickItemInquiry @intcompanyid,0,@intShopId,0
end
end
else
begin
insert #tempResult exec spQuickItemInquiry @intcompanyid,@intDepartmentId,0,0
end
select @sql=''select * from #tempResult where '' --+ @filtercolumn + '' like ''''''+ @filtercodition +''''''''
if @filtercolumn=''''
begin
set @sql=@sql
end
else
begin
set @sql=@sql + @filtercolumn + N'' like ''''''+ @filtercodition +'''''' and ''
end
if @filtertype=''A''
begin
--select * from tempResult where @filtercolumn like ''%can%''
--select * from tempResult where itemdescription like ''%can%''
--select * from tempResult where ++ like ''%''+ @filtercodition+''%''
set @sql = @sql + N'' 1 = 1''
end
else if @filtertype=''G''
begin
set @sql=@sql + N'' GodownID='' + convert(varchar(5),@intGodownid)
end
else if @filtertype=''S''
begin
set @sql=@sql + N'' shopid='' + convert(varchar(5),@intShopId)
end
else if @filtertype=''D''
begin --Ref.No.1 start
set @sql=@sql + N'' DepartmentId in(select DepartmentID from aDepartmentMaster where DepartmentID=''+ convert(varchar(5),@intDepartmentId) +'' or ParentDepId='' + convert(varchar(5),@intDepartmentId) + '')''
end  --Ref.No.1  end
EXEC (@sql)
--print @sql
--print @filtercolumn
--print  @filtercodition
drop table #tempResult
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpMag_SaveTransferOutHeader]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_SaveTransferOutHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===========================================================
-- Author:  Yogesh Joe
-- Create date: 30-04-2010
-- Description: To Save a Transfer Out into TransferOut Header
-- ===========================================================
CREATE PROCEDURE [dbo].[SpMag_SaveTransferOutHeader](
@intCompanyId AS INT,
@intTOHShopid AS INT,
@intTOHtoShopid AS INT,
@strTOHno AS VARCHAR(50),
@dtTOHdate AS DATETIME,
@strTOHremarks AS VARCHAR(250),
@intTOHrequestid AS INT,
@TOHTransfinished AS BIT,
@intTOHNoofDetails AS INT,
@intTohdepartmentid AS INT,
@tohposted AS BIT,
@numTohconexrate AS NUMERIC(18,8),
@numtohdepexrate AS NUMERIC(18,8),
@strTohexchangerates AS VARCHAR(250),
@tohType AS CHAR(2),
@dtTOHtime AS DATETIME
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @intTOHid AS INT
SELECT @intTOHid=ISNULL(MAX(TOHid),0)+1 FROM mesTransferOutHeader WHERE TOHShopid=@intTOHShopid
INSERT INTO mesTransferOutHeader( TOHid,
TOHShopid,
TOHtoShopid,
TOHno,
TOHdate,
TOHremarks,
TOHrequestid,
TOHTransfinished,
TOHNoofDetails,
tohdepartmentid,
tohposted,
tohconexrate,
tohdepexrate,
tohexchangerates,
tohType,
TOHtime
)
VALUES( @intTOHid,
@intTOHShopid,
@intTOHtoShopid,
@strTOHno,
@dtTOHdate,
@strTOHremarks,
@intTOHrequestid,
@TOHTransfinished,
@intTOHNoofDetails,
@intTohdepartmentid,
@tohposted,
@numTohconexrate,
@numtohdepexrate,
@strTohexchangerates,
@tohType,
@dtTOHtime
)
SET NOCOUNT OFF;
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpMag_SaveTransferOutDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_SaveTransferOutDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Yogesh Joe
-- Create date: 30-04-2010
-- Description:	To save TransferOut Details
-- =============================================
CREATE PROCEDURE [dbo].[SpMag_SaveTransferOutDetails](
	@intTODid	AS INT,
	@intTODshopid AS INT,
	@intTODitemid AS INT,
	@intTODshipmentid AS INT,
	@intTODtoShopid AS INT,
	@numTODrequestedGoodqty AS NUMERIC(18,3),
	@numTODissuedGoodQty AS NUMERIC(18,3),
	@numTODrequestedBadQty AS NUMERIC(18,3),
	@numTODissuedBadQty AS NUMERIC(18,3),
	@numTODcostprice AS NUMERIC(18,2),
	@numtodSellingPrice AS NUMERIC(18,2),
	@numpackid AS NUMERIC(18,3),
	@numpackqty AS NUMERIC(18,3)
)
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO mesTransferoutDetail(	TODid,
										TODshopid,
										TODitemid,
										TODshipmentid,
										TODtoShopid,
										TODrequestedGoodqty,
										TODissuedGoodQty,
										TODrequestedBadQty,
										TODissuedBadQty,
										TODcostprice,
										todSellingPrice,
										packid,
										packqty
									)
								VALUES(	@intTODid,
										@intTODshopid,
										@intTODitemid,
										@intTODshipmentid,
										@intTODtoShopid,
										@numTODrequestedGoodqty,
										@numTODissuedGoodQty,
										@numTODrequestedBadQty,
										@numTODissuedBadQty,
										@numTODcostprice,
										@numtodSellingPrice,
										@numpackid,
										@numpackqty
									)
	SET NOCOUNT OFF;
END' 
END
GO
/****** Object:  View [dbo].[vwItemRetailPacking]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemRetailPacking]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 11/12/02
-- Modified by  : leo
-- Comments  : v3
----------------------------------------------
-- Modified on  : 10/06/2003
-- Modified by          : Kishore
-- Comments             : Added the condition Active = 1
--                        (On comparison with v2)
----------------------------------------------
--Ref.No:1
-- Modified on          : 01/06/2011
-- Modified by          : Aadya
-- Comments             : ip.PackingSlNo = 1  and remove  pcd.quantity = 1
----------------------------------------------
create VIEW [dbo].[vwItemRetailPacking] AS
select i.itemid, pcd.UnitsID, min(Quantity) quantity, min(pcd.packingtypeid) Packingtypeid
from aitempackingdetail ip, aPackingTypeCapacityDetail pcd, aitem i
where i.unitsid = pcd.unitsid
and ip.packingtypeid = pcd.packingtypeid
and ip.itemid = i.itemid
--and pcd.quantity = 1 --Ref.No:1
and ip.PackingSlNo = 1 --Ref.No:1
and ip.Active = 1
group by  i.itemid, pcd.UnitsID'
GO
/****** Object:  StoredProcedure [dbo].[spAsonDateStockDepwise]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAsonDateStockDepwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spAsonDateStockDepwise 1,''20040530''
-- Purpose : The procedure was written to get godown wise stock in item fast/slow
-- Created on  : 01/10/2004
-- Created by  : Aneesh
-- moving reports
------------------------------------------------------------------------------------------
-- Modified by  :
-- Modified on  :
-- Comments     :
------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spAsonDateStockDepwise] (@intDepid int, @strDate  varchar(10)) AS
BEGIN -- creating a dummy table to insert the values
CREATE TABLE #AsonDateStockDepwise( dItemID varchar(50),  dTransQty numeric(18,2))
INSERT INTO #AsonDateStockDepwise
SELECT C.itemId, SUM(C.itemQty) FROM
(
SELECT gsItemID itemId,  SUM(gsOpeningStock) itemQty FROM MoiGodownStock gs, aGodown g
WHERE gs.gsGodownID=g.GodownId AND g.departmentID=@intDepid GROUP BY gs.gsItemID
UNION ALL
SELECT ItemId itemId, SUM(OpeningStock) itemQty FROM mosshopstock ms,aShops s
WHERE  ms.ShopID=s.ShopID AND s.DepartmentID=@intDepid GROUP BY ms.itemId
UNION ALL
SELECT ItemId itemID, SUM(TransQty * Mode) itemQty FROM vwGdnBinCard bc,aGodown g
WHERE bc.godownid=g.GodownId AND g.departmentID=@intDepid  AND gDate<=@strDate GROUP BY bc.itemID
UNION ALL
SELECT ItemId itemID,  SUM(TransQty * Mode) itemQty FROM vwshopbincardaudit ba,aShops s
WHERE ba.shopid=s.ShopID AND s.DepartmentID=@intDepid  AND sDate<=@strDate GROUP BY ba.itemID
) C GROUP BY C.itemID
SELECT tmpTbl.dItemId, 0.0 dQty1, dTransQty, 0.0 dQty2, p.sellingprice
FROM #AsonDateStockDepwise tmpTbl,(SELECT sp.itemid, MAX(sellingprice) sellingprice
FROM losshopitemshipmentdetail sp,vwItemRetailPacking vw WHERE sp.itemid = vw.itemid
GROUP BY sp.itemid) p where tmpTbl.ditemid = p.itemid
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCompanyMovingItems]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompanyMovingItems]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spCompanyMovingItems ''20070101'',''20080105'',50,1000,''D'',0,0,'''',0,'''',30
/****** Object:  Stored Procedure dbo.spCompanyMovingItems    Script Date: 18/01/2003 9:45:42 PM ******/
-- created by  : Hariharan R
-- created date : 13/01/2003
--modified By : Shinu (07/07/2007)
--Comments : Added Brand Also
--modified by : Sreekanth.M.V (20/07/2007)
--comments    : Added "@NoOfBackDays" to filter Dead items according to Bill date.Only dead items having billdate less than  (@strToDate-@NoOfBackDays) are shown.
------------------------------------------------------
CREATE  PROC [dbo].[spCompanyMovingItems] @strStartDate AS VarChar(10), @strToDate AS VarChar(10),
@NoOfRecords AS int, @QuantityLimit AS Numeric(18, 3),
@MoveType AS Char(1), @numpricerangemin AS numeric(18,2),
@numpricerangemax as numeric(18,2), @strcategoryid as varchar(2000), @intDepartmentId int ,
@strBrand as varchar(250) ='''',@NoOfBackDays int=0  AS
BEGIN
set nocount on
CREATE TABLE #ItemStockEnd
(
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2),
selPrice numeric(18,2)
)
CREATE TABLE #ItemSales
(
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2),
selPrice numeric(18,2)
)
CREATE TABLE #ItemStock
(
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2),
selPrice numeric(18,2)
)
declare @strWhere as varchar(250)
declare @strSql as nvarchar(4000)
declare @strTop as varchar(250)
declare @strPricewhere as varchar(250)
declare @strBrandCondition as varchar(250)
declare @dtMaxBillDateforDead as varchar(8)
--Selecting maximum and minimum price range
if  @numpricerangemax <>0
begin
set @strPricewhere = '' and i.sellingprice >= '' + CONVERT(varchar(20),@numpricerangemin) +
'' and i.sellingprice <= '' + convert(varchar(20), @numpricerangemax )
end
else
begin
set @strPricewhere = '' ''
end
if @strcategoryid <>''''
set @strcategoryid = '' and i.ItemCategoryID in ('' + @strcategoryid + '')   ''
else
set @strcategoryid = ''''
if @strBrand<>''''
set @strBrandCondition = '' and I.Brand ='''''' + @strBrand +'''''' ''
else
set @strBrandCondition=''''
if  @intDepartmentId = 0
begin
-- Get the ending stock (stock at the end date)
set @strSql = N''select   vw.gsItemId, 0.0, sum(transqty * mode),
0.0,i.sellingprice from vwCompBinCardWithOpening vw, (select sp.itemid, max(sellingprice)
sellingprice from losshopitemshipmentdetail sp,vwItemRetailPacking vw
where sp.itemid = vw.itemid group by sp.itemid,sellingprice ) i
WHERE i.itemid=vw.gsitemid and (sdate <= '''''' +  @strtodate + '''''' or sdate is null)
'' + @strPricewhere + '' group by vw.gsItemId,i.sellingprice''
-- insert ending stock to gdnItemStockEnd
insert into #ItemStockEnd exec sp_Executesql @strSql
-- get transaction qty
set @strSql = N''select   vw.ItemId, 0.0,  0.0, sum(TransQty),i.sellingprice
from vwshopbincardaudit vw, (select sp.itemid, max(sellingprice)
sellingprice from losshopitemshipmentdetail sp,vwItemRetailPacking vw
where sp.itemid = vw.itemid group by sp.itemid,sellingprice) i WHERE (sdate >= '''''' +
@strStartDate + ''''''and sdate <= '''''' +  @strtodate + '''''' )
and (type = ''''Exchange Out'''' or type = ''''Credit Sales''''
or type = ''''Cash Sales'''') and  vw.ItemId=i.itemid  ''
+  @strPricewhere + '' group by vw.ItemId,i.sellingprice''
-- insert transation qty to gdnItemStockTrans
insert into #ItemSales  exec sp_Executesql @strSql
end
else
begin
insert into #ItemStockEnd exec spAsonDateStockDepwise @intDepartmentId,@strtodate
-- get transaction qty
set @strSql = N''select   vw.ItemId, 0.0,  0.0, sum(TransQty),i.sellingprice
from vwshopbincardaudit vw, ashops s, (select sp.itemid, max(sellingprice)
sellingprice from losshopitemshipmentdetail sp,vwItemRetailPacking vw
where sp.itemid = vw.itemid group by sp.itemid,sellingprice) i
WHERE vw.shopid = s.shopid and s.departmentid = '' +
convert(varchar(2), @intDepartmentId) + '' and (sdate >= '''''' +
@strStartDate + ''''''and sdate <= '''''' +  @strtodate + '''''' )
and (type = ''''Exchange Out'''' or type = ''''Credit Sales''''
or type = ''''Cash Sales'''') and  vw.ItemId=i.itemid  ''
+  @strPricewhere + '' group by vw.ItemId,i.sellingprice''
insert into #ItemSales  exec sp_Executesql @strSql
end
print ''Passed''
-- Then bring starting stock, ending stock and transaction qty to gdnItemStock
insert into #ItemStock select  itemid, sum(sdstock), sum(edstock),
sum(transstock),selPrice from (
select itemid, sdstock, edstock, transstock,selPrice
from #ItemStockEnd
union all
select itemid, sdstock, edstock, transstock,selPrice
from #ItemSales) a
group by itemid,selPrice
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
set @strSql = N''select vw1.* from(select '' + @strTop + '' s.*, u.unitname, ic.itemcategoryid, ic.CategoryNameDescription,
vw.ItemDescription, i.brand, i.itemcode,i.ItemRate
from aItem i, aItemCategory ic, aunit u, vwItemDescription vw,
#ItemStock s
where vw.itemid = s.itemid and s.itemid = i.itemid
and i.ItemCategoryID = ic.ItemCategoryID and
u.unitid = i.unitsid '' + @strcategoryid +@strBrandCondition + @strWhere + '')vw1 ''
---Added by: Sreekanth.M.V
---Purpose : Dead Items whose purchase 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 #ItemStockEnd
drop table #ItemSales
drop table #ItemStock
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwgodownstockitemwithnegative]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownstockitemwithnegative]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwgodownstockitemwithnegative    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
CREATE  view [dbo].[vwgodownstockitemwithnegative] as
select gs.gsgodownid, i.itemcategoryid, gsitemid as itemid,
convert(numeric(18,3), sum(gsstock)) as stock,
convert(numeric(18,3), sum(gsbadstock)) badstock,
convert(numeric(18,3), isnull(sum(isnull(gsopeningstock,0)),0)) openingstock ,
convert(numeric(18,3), isnull(sum(isnull(gsopeningbadstock,0)),0)) openingbadstock from
vwinquirygodownstock gs, aitem i, aitemcategory ic where gs.gsitemid = i.itemid and
i.itemcategoryid = ic.itemcategoryid group by gs.gsgodownid,i.itemcategoryid, gsitemid'
GO
/****** Object:  View [dbo].[vwHqDiffWriteOff]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqDiffWriteOff]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on : 03/01/2003
-- Modified by : Kishore
-- Comments    : added dsTransId, dsTransCode columns
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
------------------------------------
CREATE view [dbo].[vwHqDiffWriteOff] as
select dsTransId, dsTransCode, dsitemid, dstoadd, dstodeduct, shopname Location, dstoshopid,
dstogodownid, dsfromshopid, dsfromgodownid,dstransdate, dscostprice
from medifferenceinstock d, ashops s
where d.dstoshopid = s.shopid
and dsfromgodownid = 0
and dsfromshopid = 0
and dstogodownid = 0
and (dstoadd<>0 or dstodeduct<>0)
union all
select dsTransId, dsTransCode, dsitemid, dstoadd, dstodeduct, godownname Location, dstoshopid,
dstogodownid, dsfromshopid, dsfromgodownid,dstransdate, dscostprice
from medifferenceinstock d, agodown g
where d.dstogodownid = g.godownid
and dsfromgodownid = 0
and dsfromshopid = 0
and dstoshopid = 0
and (dstoadd<>0 or dstodeduct<>0)'
GO
/****** Object:  View [dbo].[vwDiffStockRecovery]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiffStockRecovery]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
-- Modified on      : 03/01/2003
-- Modified by      : Kishore
-- Comments         : Added dsTransId, dsTransCode columns
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--Modified by       : Benzigar S D 26/01/2009
--Comment           : Added costprice
-------------------------------------------------
CREATE view [dbo].[vwDiffStockRecovery] as
select dsTransId, dsTransCode, dsitemid,dstoadd,
dstodeduct, shopname Location, dstoshopid,
dstogodownid, dsfromshopid, dsfromgodownid,dstransdate,dscostprice
from medifferenceinstock d, ashops s
where d.dstoshopid = s.shopid and (dstoadd <> 0 or dstodeduct <> 0)
--
union all
--
select dsTransId, dsTransCode, dsitemid, dstoadd, dstodeduct,
godownname Location, dstoshopid,
dstogodownid, dsfromshopid, dsfromgodownid,dstransdate,dscostprice
from medifferenceinstock d, agodown g
where d.dstogodownid = g.godownid
and (dstoadd <> 0 or dstodeduct <> 0)'
GO
/****** Object:  View [dbo].[vwQuantityUnprocessed]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuantityUnprocessed]'))
EXEC dbo.sp_executesql @statement = N'
-- View
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on          : 21/06/2004
-- Modified by          : HARIHARAN
-- Comments             : Added the LocationType, modified to take locationid correctly
--   : added direct despatch to shop from hq options in queries related
--   : to despatch and arrival
--   : (verified From Dev Server(Fies))
--   : DepartmentId added
/*
RefNo: 01 		
Modified on          : 16/04/2011
Modified by          : SHINE DAS
Comments             : Earlier it was using getdate() as trans date. Then stock in
inventory valuation summary will not tally with item in stock. so changed it. See refernce no 01 for
details.
*/
-----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwQuantityUnprocessed] AS
--for hqarrivals which are not confirmed
select ad.adgodownid locationid, ad.aditemid itemid, ah.ahArrivaldate GDate,
ah.aharrivalid Transid, ah.ahArrivalno TransNo,
ad.adDespatchedQty * pk.quantity TransQty ,
''Shipment Arrival'' as type, ''T'' mode, updatetime, ''From HQ'' Fromlocation,
gd.godownname ToLocation, ''Not Confirmed'' ProcessType, ''g'' LocationType, ahDepartmentId DepartmentId
from loiarrivalheader ah, loiarrivaldetail ad,
aitem ai, aPackingTypeCapacityDetail pk, Agodown gd
where ah.ahcancelled=0
and ah.ahtransfinished= 0
and ah.aharrivalid=ad.adarrivalid
and ah.ahlocalgodownid=ad.adgodownid
and ad.aditemid=ai.itemid
and ahlocalgodownid = gd.godownid
and ai.unitsid=pk.unitsid
and ad.adpackingtypeid=pk.packingtypeid
union all
--Despatches not received in godowns
select  case isnull(dhgodownid,0) when 0 then dhShopId else dd.ddgodownid end  locationid,
dd.dditemid itemid, dnm.dnmdespatchnotedate GDate,
dh.dhdespatchnoteid Transid, dh.dhdespatchnoteno TransNo,
dd.ddQty * pk.quantity, ''Shipment Arrival'' as type, ''T'' mode, dh.updatetime,
''From HQ'' Fromlocation, gd.godownname ToLocation,
''Not Received'' ProcessType, case isnull(dhgodownid,0) when 0 then ''s''
else ''g'' end LocationType, dnm.DepartmentId DepartmentId
from ahqdespatchnotemain dnm,
ahqdespatchnoteheader dh left outer join Agodown gd on dhgodownid = gd.godownid
left outer join ashops sd on dhShopid = sd.shopid , 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
union all
--Transfer in from shop or godown which are not confirmed
select  ahlocalgodownid, asditemid, ah.ahArrivaldate, ah.aharrivalid,
ah.ahArrivalno TinNo, asd.asdDespatchedGoodQty  as TinQty,
''Transfer In'' as type, ''T'' mode,updatetime,
isnull(shopname,'''') + isnull(g.godownname,'''') FromLocation,
t.godownname ToLocation, ''Not Confirmed'' ProcessType, ''g'' LocationType,
ahDepartmentid
from  loiarrivalshipmentdetail asd, loiarrivalheader ah
left outer join ashops on ah.ahshopid = shopid
left outer join agodown g on ah.ahgodownid = g.godownid, agodown t
where ahlocalgodownid = t.godownid
and ah.ahcancelled=0
and ah.ahtransfinished = 0
and ahlocalgodownid = asd.asdgodownid
and aharrivalid = asd.asdarrivalid
union all
--Deapatch to shop which are not processed yet in shops
select dh.dhShopid, dd.dditemid, dh.dhDespatchDate,
dh.dhdespatchid, dh.dhDespatchNo DespatchNo,
dd.dditemgoodqty as despatchqty,
''Despatch To Shop'' as Type, ''T'' mode,updatetime, g.godownname fromlocation,
s.shopname, ''Not Received'', ''s'' LocationType, dhDepartmentid
from meidespatchtoshopheader dh, meidespatchtoshopdetail dd, ashops s, agodown g
where dh.dhdespatchid=dd.dddespatchid
and dh.dhgodownid=dd.ddgodownid
and dh.dhcancelled=0
and dhselected=0
and dhshopid = s.shopid
and dhgodownid = g.godownid
and dhtransfinished=1
union all
--Transferouts which are not processed yet in the receving godown
select gthToGodownid, gtditemid, gthDespatchDate, gthdespatchid,
gthDespatchNo ToutNo, gtdItemGoodQty as ToutQty ,
''Transfer Out'' as Type, ''T'' mode,updatetime, fg.godownname,
tg.godownname, ''Not Received'', ''g'' LocationType, gthDepartmentID
from meigodowntransferheader, meigodowntransferdetail, agodown fg, agodown tg
where gthdespatchid=gtddespatchid
and gthFromGodownid=gtdgodownid
and gthCancelled=0
and gthselected =0
and gthfromgodownid = fg.godownid
and gthtogodownid = tg.godownid
and gthtransfinished=1
union all
--arrival in shops from godown which are not confirmed yet
select h.gahshopid shopid, d.gaditemid itemid, h.gaharrivaldate sdate,
h.gaharrivalid Transid, h.gaharrivalno Transno, d.gadItemGoodQuantity TransQty,
''Arrival From Godown'' Type, ''T'' mode,updatetime,
isnull(g.godownname, ''HQ Despatch''), s.shopname, ''Not Confirmed'', ''s'' LocationType,
gahDepartmentId
from losgoodsarrivaltoshopheader h left outer join  agodown g on
gahDespatchedGodownID = g.godownid, losgoodsarrivaltoshopdetail d,
ashops s where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid
and h.gahcancelled=0 and h.gahtransfinished=0 and gahshopid = s.shopid
union all
--transfer in from other shops which are not confirmed yet
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihid, h.tihno,
d.TIDtransfergoodqty TinQty, ''Transfer In'' TYpe, ''T'' mode,
updatetime, fs.shopname, ts.shopname, ''Not Confirmed'', ''s'' LocationType,
tihDepartmentId
from lostransferinheader h, lostransferindetail d, ashops fs, ashops ts
where h.tihid=d.tidid
and h.tihshopid=d.tidshopid
and h.tihcancel=0
and h.tihtransfinished=0
and tihfromshopid = fs.shopid
and tihshopid = ts.shopid
union all
--Transferouts from shops to another shops which are not selected
select tohToshopid, toditemid, tohDate sdate, tohid, tohno,
todissuedgoodqty as ToutQty , ''Transfer Out'' Type, ''T'' mode,
updatetime, fs.shopname, ts.shopname, ''Not Received'', ''s'' LocationType,
tohDepartmentId
from mestransferoutheader , mestransferoutdetail, ashops fs, ashops ts
where tohid=todid
and Tohshopid=todshopid
and tohcancelled=0
and tohshopid = fs.shopid
and tohtoshopid = ts.shopid
and tohused = 0
and tohtransfinished=1
union all
--Deapatch to godowns from shops which are not received in godowns
select dh.dghGodownid, dd.dgditemid, dh.dghDate sdate, dh.dghid, dh.dghNo,
dd.dgddespatchedgoodqty as despatchqty,
''Despatch To Godown'' TYpe, ''T'' mode,updatetime, s.shopname,
g.godownname, ''Not Received'', ''g'' LocationType, dghDepartmentid
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd , ashops s, agodown g
where dh.dghid=dd.dgdid
and dh.dghshopid=dd.dgdshopid
and dh.dghcancelled=0
and dghshopid = s.shopid
and dghgodownid = g.godownid
and dghused = 0
and dghtransfinished=1
union all
-- Items which have difference in transactions while sending and receiving  dstransdate
--select dstogodownid, dsitemid, getdate() sdate, 1, ''DIST'', RefNo: 01 	
select dstogodownid, dsitemid, dstransdate sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Distribute'' TYpe, ''d''  mode,getdate(),
'''', godownname, ''Not Distributed'', ''g'' LocationType, agodown.departmentid
from vwHQDiffwriteoff, agodown
where dstogodownid = godownid and dstogodownid <> 0
union all
-- Items which have difference in transactions while sending and receiving
--select dstoshopid, dsitemid, getdate() sdate, 1, ''DIST'', RefNo: 01 	
select dstoshopid, dsitemid, dstransdate sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Distribute'' TYpe, ''d''  mode, getdate(),
'''', shopname, ''Not Distributed'', ''s'' LocationType , ashops.departmentid
from vwHQDiffwriteoff, ashops
where dstoshopid = shopid and dstoshopid <> 0
union all
-- Items which have difference in transactions while sending and receiving
--select dsfromshopid, dsitemid, getdate() sdate, 1, ''DIST'', RefNo: 01 	
select dsfromshopid, dsitemid, dstransdate sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Recovery'' TYpe, ''r''  mode, getdate(),
shopname, location, ''Not Recovered'', ''s'' LocationType , s.departmentid
from vwDiffStockRecovery, ashops s
where dsfromshopid = shopid and dsfromshopid <> 0
union all
-- Items which have difference in transactions while sending and receiving
--select dsfromgodownid, dsitemid, getdate() sdate, 1, ''DIST'', RefNo: 01 	
select dsfromgodownid, dsitemid, dstransdate sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Recovery'' TYpe, ''r''  mode, getdate(),
godownname, location, ''Not Recovered'', ''g'' LocationType , agodown.departmentid
from vwDiffStockRecovery, agodown
where dsfromgodownid = godownid and dsfromgodownid <> 0'
GO
/****** Object:  View [dbo].[vwshopstockitemwithnegative]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockitemwithnegative]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopstockitemwithnegative    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on 	: 11/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwshopstockitemwithnegative] as
select ss.shopid, i.itemcategoryid, ss.itemid,
sum(ss.stock) as stock, sum(ss.badstock) badstock,
isnull(sum(isnull(openingstock,0)),0) openingstock ,
isnull(sum(isnull(openingbadstock,0)),0) openingbadstock from
vwinquiryshopstock ss, aitem i, aitemcategory ic where
ss.itemid = i.itemid and i.itemcategoryid = ic.itemcategoryid
group by ss.shopid, i.itemcategoryid, ss.itemid'
GO
/****** Object:  View [dbo].[vwsellingtotalstockwithnegative]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstockwithnegative]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 21/06/04
--Modified by 		: Hariharan
--Comments		: add opening stock
--			: added departmentid
CREATE view [dbo].[vwsellingtotalstockwithnegative] as
select v.itemcategoryid, v.itemid, sum(v.stock) stock, sum(v.badstock) badstock
,sum(v.openstock) openstock, departmentid  from
(select itemcategoryid,itemid, convert(numeric(18,3), sum(stock)) stock, convert(numeric(18,3),
sum(badstock)) badstock,convert(numeric(18,3),sum(openingstock))openstock, S.departmentid from
vwshopstockitemwithnegative v, ashops s where v.shopid = s.shopid
group by itemcategoryid,itemid, s.DepartmentId
union all
select itemcategoryid,itemid,  convert(numeric(18,3), sum(stock)) stock,
convert(numeric(18,3), sum(badstock)) badstock,convert(numeric(18,3),
sum(openingstock)) openingstock,
s.DepartmentId from vwgodownstockitemwithnegative v, agodown s where v.gsgodownid = s.godownid
group by itemcategoryid,itemid, s.DepartmentId
union all
select a.itemcategoryid, a.itemid, convert(numeric(18,3), sum(transqty)) stock,
0 badstock, 0.000, QUP.Departmentid from vwquantityunprocessed qup, aitem a where
qup.itemid = a.itemid group by a.itemcategoryid, a.itemid, QUP.Departmentid)
v group by v.itemcategoryid, v.itemid, v.departmentid'
GO
/****** Object:  View [dbo].[vwsellingtotalstockwithnegative_company]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstockwithnegative_company]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By  :- Benzigar S D
-- Created On  :- 23/01/2010
-- Comment     :-For item in stock companywise report.
--               In previous view vwsellingtotalstockwithnegative departmentwise group is taken.
--               So companywise stock will not be correct
CREATE view [dbo].[vwsellingtotalstockwithnegative_company] as
select itemcategoryid,itemid,sum(stock) stock,badstock,openstock,0 departmentid
from vwsellingtotalstockwithnegative
group by itemcategoryid,itemid,badstock,openstock'
GO
/****** Object:  View [dbo].[vwstockcolor]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstockcolor]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwstockcolor] as
(select itemid,sum(stock) as stocks from vwInquiryShopStock
group by itemid)
union
(select gsitemid,gsstock from vwInquirygodownStock)'
GO
/****** Object:  View [dbo].[vwtotalstockcolor]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalstockcolor]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwtotalstockcolor] as
select itemid,sum(stocks) as totalstocks from vwstockcolor
group by itemid'
GO
/****** Object:  View [dbo].[vwCompBinCardWithOpening]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompBinCardWithOpening]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- Created On  : 13/01/2002
-- Created by  : Lawrence.J
-- Purpose  :Used in Godown Item Moving report
--------------------------------------------------------------------------------
-- Modified by : Regin
-- Modified on : 23-12-2009
-- Purpuse     :
--  1. [null sdate] was changed to [gsStockDate sdate] to get the date
--  2. ShopID and GodownID fields were added
--------------------------------------------------------------------------------
CREATE view [dbo].[vwCompBinCardWithOpening] as
select gsItemID,
--null sdate ,
gsStockDate sdate, ''Opening'' TransNo, 0 TransId,  IsNull(gsOpeningStock, 0) TransQty,
''Opening'' Type, 1 Mode, gsStockDate UpdateTime, NULL ShopID, gsGodownID GodownID
from MoiGodownStock
Union All
select ItemID,
--null sdate,
StockDate sdate, ''Opening'' TransNo, 0 TransId, IsNull(OpeningStock, 0) TransQty,
''Opening'' Type, 1 Mode, StockDate UpdateTime, ShopID, NULL GodownID
from mosshopstock
Union All
select ItemId, gDate, TransNo, TransID, TransQty, Type, Mode, UpdateTime,
NULL ShopID, godownid
from vwGdnBinCard
union all
select ItemId, sDate, TransNo, TransID, TransQty, Type, Mode, UpdateTime,
ShopID, NULL GodownID
from vwshopbincardaudit'
GO
/****** Object:  View [dbo].[vwItemDescription]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/*
Modified on  : 14/11/2003, 11/03/2004
Modified by  : Hariharan R
Comments     : Renamed the field Active to vwActive in order to avoice conflicting with aItem.Active
whereever this view and aitem are joined
: Unitcode, brand, Itemcategoryid added
: modified to take first 250 characters of itemdescription
: Modified By      : Benzigar S D
: Modified On      : 17/09/2009
: Comment          : For ask added Brand and Modelno
Modified By : Shine Das
For     : ASK HOLDINGS
ON     : 03-09-2010
COMMENT    : (Above updation was lost somehow between updations)
So Model No Added to the view. Item description IS now appended with Model No also. Order IS Color ID, Size ID, Did, ModelNo.
Commmented lines Like 1000,0100.. etc represents TRUE OR FALSE conditions of data in different criteria.
SELECT * FROM MYTEST
*/
--CREATE VIEW mytest AS
CREATE VIEW [dbo].[vwItemDescription] AS
SELECT ItemID,
--1000
CASE WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NULL AND aitem.did IS NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname)
--0100
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + sizename)
--0010
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + dname)
--0001
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NULL AND aitem.did IS NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + aitem.modelno)
--0000
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NULL AND aitem.did IS NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription)
--1111
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname + '' - '' + aitem.modelno)
--1100
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename)
--1101
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + aitem.modelno)
--1110
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
--0111
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + sizename + '' - '' + dname + '' - '' + aitem.modelno)
--0011
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + dname + '' - '' + aitem.modelno)
--0110
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + sizename + '' - '' + dname)
--1001
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NULL AND aitem.did IS NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + aitem.modelno)
--1010
WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NULL AND aitem.did IS NOT NULL
AND (aitem.modelno IS NULL OR aitem.modelno = ''0'' OR aitem.modelno = '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + dname)
--0101
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NULL
AND (aitem.modelno IS NOT NULL OR aitem.modelno <> ''0'' OR aitem.modelno <> '''')THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + sizename + '' - '' + aitem.modelno)
END AS itemdescription, itemcode code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid
FROM aitem
LEFT OUTER JOIN acolor ON aitem.colorid = acolor.colorid
LEFT OUTER JOIN asize ON aitem.sizeid = asize.sizeid
LEFT OUTER JOIN adistributormaster dist ON aitem.did = dist.did, aunit au
WHERE aitem.unitsid = au.unitid
/*
OLD COPY COMMENTED BY SHINE
-------------------------------
CASE WHEN aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
WHEN (aitem.colorid IS NOT NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NULL) THEN
CONVERT(VARCHAR(250),ItemDescription + '' - '' + colorname + '' - '' + sizename )
WHEN (aitem.colorid IS NULL AND aitem.sizeid IS NOT NULL AND aitem.did IS NOT NULL) THEN
CONVERT(VARCHAR(250), ItemDescription + '' - '' + sizename + '' - '' + dname)
WHEN (aitem.colorid IS NOT NULL AND aitem.sizeid IS NULL AND aitem.did IS NOT NULL) THEN
CONVERT(VARCHAR(250), ItemDescription + '' - '' + colorname + '' - '' + dname)
WHEN aitem.did IS NOT NULL THEN CONVERT(VARCHAR(250), ItemDescription + '' - '' + dname)
WHEN aitem.colorid IS NOT NULL THEN CONVERT(VARCHAR(250), ItemDescription + '' - '' + colorname )
WHEN aitem.sizeid IS NOT NULL THEN CONVERT(VARCHAR(250), ItemDescription + '' - '' + sizename )
WHEN aitem.colorid IS NULL AND aitem.sizeid IS NULL AND aitem.did IS NULL  THEN
CONVERT(VARCHAR(250), ItemDescription ) END AS itemdescription, itemcode code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid
from aitem LEFT OUTER JOIN acolor ON aitem.colorid = acolor.colorid
LEFT OUTER JOIN asize ON aitem.sizeid = asize.sizeid
LEFT OUTER JOIN adistributormaster dist ON aitem.did = dist.did, aunit au
WHERE aitem.unitsid = au.unitid
*/'
GO
/****** Object:  View [dbo].[vwHpSaleMothwise]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpSaleMothwise]'))
EXEC dbo.sp_executesql @statement = N'
----Created by         : Prasanth Joseph
----Created On         : 22-12-2007
----Created For        : To get Month Wise Item Sale
----Modifies By        :
CREATE view [dbo].[vwHpSaleMothwise] as
select gsitemid,sdate,month(sdate)smonth,year(sdate)syear,transqty,vw.itemdescription  item
from vwCompBinCardWithOpening inner join  vwitemDescription vw
on  gsitemid=vw.itemid where mode=-1 and vw.vItemCategoryID=5'
GO
/****** Object:  StoredProcedure [dbo].[spHPmonthwisesale]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPmonthwisesale]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----Created by         : Prasanth Joseph
----Created On         : 22-12-2007
----Created For        : To get Month Wise Item Sale
----Modifies By        :
CREATE proc [dbo].[spHPmonthwisesale]
@fromdate as varchar(12),
@todate as varchar(12)
-- @fromdate as datetime,
-- @todate as datetime
as
set nocount on
create table #tempData(
itemId int,
smonth nvarchar(30),
syear  nvarchar(30),
Isaledqty numeric(20),
item  nvarchar(100),
openingQty  numeric(20),
closingBalance numeric(20),
dtdate datetime)
declare @strSql as nvarchar(4000),
@itemID as int,
@openingBalance as numeric(20),
@intComapnyId as int,
@intYears as nvarchar(20),
@intMonth as nvarchar(20),
@saledQty as numeric(20),
@strItem as nvarchar(30),
@closingBalance as numeric(20),
@yearMonth as nvarchar(30),
@MonthName as nvarchar(30)
begin
declare opcurt cursor for
---select itemid from aitem where itemcategoryId=5 -- and itemid in (11119)
select distinct(gsItemID) from vwHpSaleMothwise ---where gsitemid in(11119)
open opcurt
fetch next from opcurt into @itemID
while @@fetch_status =0
begin
select @openingBalance=(sum(transQty*mode)) from vwCompBinCardWithOpening  where gsitemid=@itemID and updatetime<@fromdate
--select sum(saleqty) from vwhpsalessummery where hpqditemID=10540 and hpqhQuotationDate>=''20071001'' and hpqhQuotationDate<=''20061010''
--select @intComapnyId=hpqhCompanyID,@intYears=invyears,@intMonth=invmonth,@strItem=itemdescription--,@saledQty=sum(saleqty)
--from vwhpsalessummery where hpqditemID=@itemID and hpqhQuotationDate>=@fromdate and hpqhQuotationDate<=@todate
--group by hpqhCompanyID,invyears,invmonth,itemdescription
select @closingBalance=sum(transQty*mode) from vwCompBinCardWithOpening where gsitemId=@itemID and updatetime<@todate
-- select @itemID=gsitemid,@intMonth=smonth,@intYears=syear,@saledQty=sum(transqty) sqty,@strItem=item from vwHpSaleMothwise
--- where gsitemid=@itemID  and sdate>=@fromdate and sdate<=@todate
---group by gsitemid,smonth,syear,item
insert into #tempData select gsitemid,cast(smonth as nvarchar(20)) smonth,cast(syear as nvarchar(20))syear,sum(transqty) sqty,item,@openingBalance,@closingBalance,sdate  from vwHpSaleMothwise
where gsitemid=@itemID  and sdate>=@fromdate and sdate<=@todate
group by gsitemid,smonth,syear,item ,sdate
--- select @saledQty=sum(transQty) from vwCompBinCardWithOpening where mode=-1 and gsitemId=@itemID and updatetime>=@fromdate and updatetime<=@todate
-- insert into #tempData values(@openingBalance,@intComapnyId,@intYears,@intMonth,@yearMonth,@strItem,@itemID,@saledQty,@closingBalance)
fetch next from opcurt into @itemID
end
close opcurt
deallocate opcurt
End
set @strsql=N''Select itemId,smonth,syear,item,Isaledqty,openingQty,closingBalance,dtdate from #tempData order by dtdate''
---print @strsql
exec sp_executesql @strsql
set nocount off' 
END
GO
/****** Object:  View [dbo].[vwCompanyBincard]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyBincard]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Shinu
-- Created on  : 02/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Flow in Company
--------------------------------------------------------------------------------
-- Modified by : Regin
-- Modified on : 23-12-2009
-- Purpuse     : [and pbhUsed=1] condition was commented,
--               since items is added to stock before costing.
--------------------------------------------------------------------------------
-- Modified by : Regin
-- Modified on : 23-12-2009
-- Purpuse     :
--  1. HQ Write Off part was added
--  2. ShopID, GodownID, DeptID fields were added
-- Note: DeptID should not be NULL, since DeptID is used to filter records
-- in ItemFlowAnalysisCompanywise report.
--------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCompanyBincard] AS
-- SHOP TRANSACTIONS
SELECT gsItemID ItemID,sDate,TransID,TransNo,TransQty,Type,Mode,UpdateTime,
v.ShopID, NULL GodownID, s.DepartmentID DeptID
FROM vwCompBinCardWithOpening v
inner join aShops s on v.ShopID=s.ShopID
-- GODOWN TRANSACTIONS
UNION ALL
SELECT gsItemID ItemID,sDate,TransID,TransNo,TransQty,Type,Mode,UpdateTime,
NULL ShopID, v.GodownID, g.DepartmentId DeptID
FROM vwCompBinCardWithOpening v
inner join aGodown g on v.GodownID=g.GodownID
UNION ALL
SELECT pbdItemID,pbhBillDate,pbhBillID,pbhBillNo,pbditemquantity,''Imports'',1,
UpdateTime, NULL ShopID, NULL GodownID, pbhDepartmentID DeptID
FROM LOspPurchaseBillHeader INNER JOIN (select pbdBillID ,pbdItemID ,pbditemquantity*Quantity pbditemquantity FROM
LOspPurchaseBillDetail INNER JOIN (select ItemID,apc.PackingTypeID,apc.UnitsID,Quantity from
(select ai.ItemID,UnitsID,ap.PackingTypeID from  aItem ai
INNER JOIN aItemPackingDetail ap ON ai.ItemID=ap.ItemID )Det
INNER JOIN aPackingTypeCapacityDetail apc ON apc.UnitsID=det.UnitsID AND
apc.PackingTypeID=det.PackingTypeID) Item ON Item.ItemID=pbdItemID and Item.PackingTypeID=pbdPackingTypeID )Detail
ON pbhBillID = pbdBillID
WHERE pbhCancelled=0
--and pbhUsed=1   -- Commented By Regin On 23-12-2009, since items is added to stock before costing.
and pbhDespatched=1
UNION ALL
----minus all the Arrival done basis of Despatch From HQ Because Purchase Bill Quantity is Adding here
SELECT d.gaditemid itemid, h.gaharrivaldate sdate,
h.gaharrivalid Transid, h.gaharrivalno Transno,
convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,
''Arrival From Godown'' Type, -1 mode,updatetime,
gahShopid ShopID, NULL GodownID, s.DepartmentID
FROM
losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d, aShops s WHERE
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1 and isnull(gahHqDespatchID,0)<>0 and h.gahShopid=s.ShopId
GROUP BY  h.gaharrivaldate, h.gaharrivalid,
gaharrivalno, d.gaditemid,updatetime,gahShopid,s.DepartmentID
UNION ALL
----minus all the Arrival done basis of Despatch From HQ
SELECT ad.aditemid itemid, ah.ahArrivaldate GDate,
ah.aharrivalid Transid, ah.ahArrivalno TransNo,
convert(numeric(18,3),sum(ad.adReceivedQty * pk.quantity * counts)) TransQty , ''Shipment Arrival'' as type,
-1 mode,updatetime, NULL ShopID, ahLocalGodownID GodownID, DepartmentId DeptID
FROM  loiarrivalheader ah, loiarrivaldetail ad,
aitem ai, aPackingTypeCapacityDetail pk, aunit u, aGodown g
WHERE ah.ahcancelled=0 and ah.ahtransfinished=1 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 ai.unitsid = u.unitid and ahArrivalType=''H'' and ahLocalGodownID=g.GodownID
GROUP BY ah.ahArrivaldate, ah.aharrivalid,
ah.ahArrivalno, ad.aditemid,updatetime, ahLocalGodownID, DepartmentId
union all
----minus all the hq write off
-- HQ WRITE OFF AGAINST SHOPS
select swItemID ItemID, swDate, swID TransID, ''HQ Write Off'' TransNo, swAddStock TransQty,
''HQ Write Off'' Type, -1 Mode, updatetime, swShopID ShopID, NULL GodownID, s.DepartmentID DeptID
from moStockwriteoffhq
inner join aShops s on swShopID=s.ShopId
union all
-- HQ WRITE OFF AGAINST GODOWNS
select swItemID ItemID, swDate, swID TransID, ''HQ Write Off'' TransNo, swAddStock TransQty,
''HQ Write Off'' Type, -1 Mode, updatetime, NULL ShopID, swGodownID GodownID, g.DepartmentID DeptID
from moStockwriteoffhq
inner join aGodown g on swGodownID=g.GodownId'
GO
/****** Object:  View [dbo].[vwCompanyItemFlow]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyItemFlow]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view gives all those transactions that affect the company stock,
-- not shop or godown stock. This view eliminates internal transfer of items like
-- Despatch to Shop, Despatch to Godown, etc. This view shows items moving in
-- and out of the company, not shop or godown transfers.
-- This view is created with the intention of preparing a report
-- named "Item Flow Analysis Companywise"
--------------------------------------------------------------------------------
-- Coded by: Regin T.
-- Coded on: 23-12-2009
--------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCompanyItemFlow] AS
-- TRANS OF SHOPS THAT AFFECT COMPANY STOCK
select ItemId, sDate, TransNo, TransID, TransQty, Type, Mode, UpdateTime,
ShopID, GodownID, DeptID
from vwCompanyBinCard
where
-- Shop Transactions derived from vwShopBinCardAudit
(  Type=''Goods Return''
or Type=''Verification Plus''
or Type=''Exchanged In''
or Type=''Local Purchase''
or Type=''Write off''
or Type=''Verification Minus''
or Type=''Cash Sales''
or Type=''Credit Sales''
or Type=''Exchange Out''
or Type=''Special Invoice Return''
or Type=''Parts Replaced''
or Type=''Re-Export''
or Type=''Merging Deduct''
or Type=''Merging Add''
or Type=''Purchase Return''
or Type=''WC/BP''
or Type=''Hire Purchase''
-- Godown Transactions derived from vwGdnBinCard
or Type=''Splitting Add''
or Type=''Write Off''
or Type=''Special Despatch''
or Type=''Verification Plus''
or Type=''Verification Minus''
or Type=''Splitting Ded''
-- Other Transactions derived from vwCompanyBinCard
or Type=''Opening''
or Type=''Imports''
or Type=''HQ Write Off'')
-- To filter out trans having 0 qty
and TransQty <> 0'
GO
/****** Object:  StoredProcedure [dbo].[spCompanyOpeningStockAsOnDate]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompanyOpeningStockAsOnDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This Stored Procedure returns the opening stock of given item.
-- If DeptId is 0, this SP retruns the opening stock in the entire company.
-- If DeptId is provided, this SP returns the opening stock in select department.
-- This SP is used in Item Flow Analysis Companywise report (rptCompanyItemFlow.rpt)
--------------------------------------------------------------------------------
-- Coded by: Regin T.
-- Coded on: 05-01-2010
--------------------------------------------------------------------------------
-- spCompanyOpeningStockAsOnDate 10, ''20100101''
CREATE procedure [dbo].[spCompanyOpeningStockAsOnDate]
@intItemId as int,
@strDate as varchar(10),
@intDeptId as int=0
as
begin
set nocount on
Set ansi_warnings off
if @intDeptId>0
begin
-- DEPARTMENT OPENING STOCK
select isnull(sum(TransQty*Mode),0) OpenStock from vwCompanyItemFlow
where ItemId=@intItemId and sDate<cast(@strDate as datetime) and DeptID=@intDeptId
end
else
begin
-- COMPANY OPENING STOCK
select isnull(sum(TransQty*Mode),0) OpenStock from vwCompanyItemFlow
where ItemId=@intItemId and sDate<cast(@strDate as datetime)
end  -- end of else
set nocount off
set ansi_warnings off
End  -- end of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[FindBlanktable]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FindBlanktable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create procedure [dbo].[FindBlanktable]
as
Begin
create table #temp
(
	tablename varchar(100),
	msg varchar(200)
)
create table #temp2
(
countvalue int
)
declare @sql as varchar(200)
declare @i as int
declare @name as varchar(100)
Declare mycursor cursor  for select name from sysobjects where type=''U''
open mycursor
fetch next from mycursor into @name
while @@fetch_status=0
begin
set @sql=''select count(*) from ''+@name
insert into #temp2
exec (@sql)
set @i= (select * from #temp2)
if @i=0
begin
insert into #temp
select @name,''Blank''
end
else
begin
insert into #temp
select @name,''Not Blank''
end
delete from #temp2
fetch next from mycursor into @name
end
close mycursor
deallocate mycursor
select * from #temp
drop table #temp
drop table #temp2
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopExpiryTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopExpiryTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by	: Kishore
-- Created on	: 26/08/2003
-- Comments     : This sp updates the Expiry wise stock in total stock verification
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spShopExpiryTotalStockVerification](@intItemId as int,
							@intShopId as int,
							@intSvdId as int,
							@dtUpdate as DateTime,
							@intArrivalDetailId as int OUTPUT,
							@intIssueDetailId as int OUTPUT) AS
Begin
	Declare @numSalesQty as Numeric(18, 8)
	Declare @numVerifiedQty as Numeric(18, 3)
	Declare @dtExpiryDate as DateTime
	Declare @numCurExpiryStock as Numeric(18, 3)
	Declare @numSumOut as Numeric(18, 3)
	Declare @numSumIn as Numeric(18, 3)
	-- open the cursor to loop through the Expirys
	Declare curExpiry Cursor for
		SELECT eadExpiryDate, eadItemQty FROM losExpiryArrivalDetails
		WHERE eadShopId = @intShopId
		AND eadTransactionId = @intSvdId
		AND eadInterfaceId = 8010
		AND eadCancel = 1
	Open curExpiry
	Fetch Next From curExpiry Into @dtExpiryDate, @numVerifiedQty
	While @@fetch_status = 0
	Begin
		/* Interface ids of transaction
		* 1502        Point of Sales
		* 1504        Invoice for credit sales
		* 1518        Goods Exchange
		* 1516        Service Invoice
		* 1518        Goods Exchange
		* 5008        Special Invoice
		* 1512        Goods Return Note	
		*/
		
		-- get the sum qty involved in transactions
		-- in this case only special despatch to shop is transacted
		SELECT @numSumOut = SUM(eidItemQty)
			FROM losExpiryIssueDetails
			WHERE eidTransactionId IN
				(SELECT TransID
				FROM vwShopBinCardAudit
				WHERE ItemId = @intItemId
				AND UpdateTime >= @dtUpdate
				AND Type IN (''Cash Sales'', ''Credit Sales'',
				''Exchange Out'', ''Parts Replaced'')
				AND ShopId = @intShopId)
				AND eidShopId = @intShopId
				AND eidInterfaceId IN (1502, 1504, 1518, 1516)
				AND eidItemId = @intItemId
				AND eidExpiryDate = @dtExpiryDate
		-- get sum qty transacted in
		-- after starting the ''total stock verification''
		SELECT @numSumOut = SUM(eadItemQty)
			FROM losExpiryArrivalDetails
			WHERE eadTransactionId IN
				(SELECT TransId
				FROM vwShopBinCardAudit
				WHERE ItemId = @intItemId
				AND UpdateTime >= @dtUpdate
				AND Type IN (''Exchanged In'', ''Special Invoice Return'',
				''Goods Return'')
				AND ShopId = @intShopId)
			AND eadShopId = @intShopId
			AND eadInterfaceId IN (1518, 5008, 1512)
			AND eadItemId = @intItemId
			AND eadExpiryDate = @dtExpiryDate		
		Set @numSalesQty = @numSumIn - @numSumOut
		-- make the Expiry stock of specified item at
		-- specified Expiry to zero
		-- first get the currect Expiry stock
	SELECT @numCurExpiryStock = qty
	FROM
	(SELECT ExpiryDate, ShopId,
		ItemId, SUM(qty) qty
	        FROM
		(SELECT eadExpiryDate ExpiryDate,
		eadShopId ShopId, eadItemId ItemId , SUM(eadItemQty) qty
	FROM losExpiryArrivalDetails
		WHERE eadShopId = @intShopId
	AND eadItemId =  @intItemId
		AND eadCancel = 0
		AND eadExpiryDate = @dtExpiryDate
		GROUP BY eadExpiryDate, eadShopId, eadItemId
	UNION ALL
		SELECT eidExpiryDate, eidShopId, eidItemId, - SUM(eidItemQty)
	        FROM losExpiryIssueDetails
	WHERE eidShopId = @intShopId
	        AND eidItemId = @intItemId
		AND eidCancel = 0
		AND eidExpiryDate = @dtExpiryDate
	        GROUP BY eidExpiryDate, eidShopId, eidItemId) a
	        GROUP BY ExpiryDate, ShopId, ItemId
	        HAVING SUM(qty) <> 0 ) b
	WHERE b.ItemId = @intItemId  -- for extra safety
		
		-- if stock > 0, insert to issue details
		-- otherwise insert to arrival details
		-- to make the net stock zero
		If @numCurExpiryStock > 0
		Begin
			INSERT INTO losExpiryIssueDetails
			(eidinterfaceid, eidShopid, eidTransactionId, eiddetailId,
			eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
			eidpackingqty, eidcancel, eidadjustment)
			VALUES
			(8010, @intShopId, @intSvdId, @intIssueDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numCurExpiryStock), 1, ABS(@numCurExpiryStock), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		Else
		Begin
			INSERT INTO losExpiryArrivalDetails
			(eadinterfaceid, eadShopid, eadtransactionid, eaddetailId,
			eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
			eadpackingqty, eadcancel, eadadjustment)
			VALUES
			(8010, @intShopId, @intSvdId, @intArrivalDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numCurExpiryStock), 1, ABS(@numCurExpiryStock), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		
		-- now insert to arrival/issue details
		If (@numVerifiedQty - @numSalesQty) > 0
		Begin
			INSERT INTO losExpiryArrivalDetails
			(eadinterfaceid, eadShopid, eadTransactionId, eaddetailId,
			eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
			eadpackingqty, eadcancel, eadadjustment)
			VALUES
			(8010, @intShopId, @intSvdId, @intArrivalDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1,
			ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		Else
		Begin
			INSERT INTO losExpiryIssueDetails
			(eidinterfaceid, eidShopid, eidTransactionId, eiddetailId,
			eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
			eidpackingqty, eidcancel, eidadjustment)
			VALUES
			(8010, @intShopId, @intSvdId, @intArrivalDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1,
			ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		end
		Fetch Next From curExpiry Into @dtExpiryDate, @numVerifiedQty		
	End
	Close curExpiry
	Deallocate curExpiry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionBackUp]    Script Date: 10/06/2012 14:17: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].[spDailySalesCollectionBackUp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--IF EXISTS(SELECT *  FROM sys.views WHERE name =''spDailySalesCollection'')
--   DROP view dbo.spDailySalesCollection
--GO
--Created on : 16/05/2003, 08/10/2003, 06/04/2004, 13/05/2004
--Created by : R Harikrishnan, Hariharan R, Hariharan R
--Comments : For Reports, Modified removing receiptvoucherdetails table usage for taking receipt and shopid selected as 0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 18/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
-- exec spDailySalesCollection 1,''R'',''20080707'',''20080707'',1,0,0
----------------------------------------------------------------------------------------------
CREATE  procedure [dbo].[spDailySalesCollectionBackUp]
(
@intCompanyID  as int,
@strDateRangeType  as nvarchar(4),
@strFromDate   as nvarchar(10),
@strToDate   as nvarchar(10),
@intShopID   as int,
@intDeptID  as int,
@intChkDeptID  as int
)
as
set nocount on
create table #tempSales
(
companyid int,
departmentid int,
shopid int,
billdate datetime,
cashsales numeric(18,2),
dcashsales numeric(18,2),
ccashsales numeric(18,2),
creditcard numeric(18,2),
dcreditcard numeric(18,2),
ccreditcard numeric(18,2),
debitcard numeric(18,2),
ddebitcard numeric(18,2),
cdebitcard numeric(18,2),
receipts numeric(18,2),
dreceipts numeric(18,2),
creceipts numeric(18,2),
payments numeric(18,2),
dpayments numeric(18,2),
cpayments numeric(18,2),
creditsales numeric(18,2),
dcreditsales numeric(18,2),
ccreditsales numeric(18,2),
localpurchase numeric(18,2),
dlocalpurchase numeric(18,2),
clocalpurchase numeric(18,2)
)
declare @strSQL as nvarchar(2000)
-- cashsales
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, sum(actamount) cashsales,
sum(damount) dcashsales, sum(camount) 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, 0.0 as localpurchase,
0.0 as dlocalpurchase , 0.0 as clocalpurchase  from vwcashsalestruncated cs, aaccountmaster am where
am.misc=''''CA'''' and cs.accountid = am.accountid and cs.companyid = am.companyid
and cash = 1''
--set @strDateRangeType =''R''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intdeptid>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--Credit Card
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2),sum(actamount)) as creditcard, convert(numeric(18,2),sum(damount)) as dcreditcard,
convert(numeric(18,2),sum(camount)) 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, 0.0 as localpurchase, 0.0 as dlocalpurchase,
0.0 as clocalpurchase from vwcashsalestruncated cs, aaccountmaster am where am.misc = ''''CC'''' and
cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--debit card sales
set @strSQl = N''
insert into #tempSales
select cs.companyid,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, convert(numeric(18,2),sum(actamount))
as debitcard, convert(numeric(18,2),sum(damount)) as ddebitcard, convert(numeric(18,2),sum(camount))
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   from vwcashsalestruncated cs, aaccountmaster am where
am.misc =''''DC'''' and cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1 ''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--Receipts
set @strSQl = N''
insert into #tempSales
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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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
from losDummyReceiptHeader rh, acustomermaster cm where drcancelled=0 and rh.drcustomerid=
cm.customerid and rh.drcompanyid=cm.companyid ''
set @strSQL=@strSQL + N'' and drcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and drshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and drdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and drdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by drcompanyid, drdepartmentid, drshopid, drdate''
exec sp_Executesql @strSQl
--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
set @strSQl = N''
insert into #tempSales
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,2),sum(customeramount)) receipts,
convert(numeric(18,2),sum(amount * depexrate)) dreceipts,
convert(numeric(18,2),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
from receiptvoucherheader rh
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is not null ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
exec sp_Executesql @strSQl
--FOR TAKING MULTICUSTOMER RECEIPTS - hari 040406
--for receipts of customers
set @strSQl = N''
insert into #tempSales
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,2),sum(rcd.customeramount)) receipts,
convert(numeric(18,2),sum(rcd.amount * depexrate)) dreceipts,
convert(numeric(18,2),sum(rcd.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
from receiptvoucherheader rh, receiptvouchercustomerdetails rcd
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is null and
rh.ReceiptId = rcd.ReceiptId and rh.CompanyId = rcd.CompanyId ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
exec sp_Executesql @strSQl
set @strSQl = N''
insert into #tempSales
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,2),sum(phAmount)) as payments, convert(numeric(18,2),sum(phAmount*
phdepexrate)) as dpayments, convert(numeric(18,2),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   from LOsPaymentVoucherHeader ph where phcancelled=0  ''
set @strSQL=@strSQL + N'' and phcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and phshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and phdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and phPaymentDate between '''''' + @strFromDate + N'''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by phcompanyid,phdepartmentid, phshopid, phPaymentDate''
exec sp_Executesql @strSQl
--credit sales
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 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, convert(numeric(18,2),sum(actamount)) as creditsales,
convert(numeric(18,2),sum(damount)) as dcreditsales, convert(numeric(18,2),sum(camount))
as ccreditsales, 0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase
from vwcashsalestruncated cs where cash=0 ''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--local purchase - madhu 23/08/01
set @strSQl = N''
insert into #tempSales
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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),sum(lphbillamount*lphexchangerate)) as clocalpurchase
from loslocalpurchaseheader lh,adepartmentmaster d where
lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0 ''
set @strSQL=@strSQL + N'' and lphcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and lphshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and lphdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and lphbilldate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + N''group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate''
exec sp_Executesql @strSQl
if @intDeptID <> 0
Begin
select
companyid,departmentid, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase
from
#tempsales where departmentid = @intDeptID
group by
companyID,departmentID,Billdate
end
else
Begin
if @intShopId <> 0
Begin
select
companyid,0, ShopID shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase
from
#tempsales where shopid = @intShopID
group by
companyID, ShopID, Billdate
end
if @intShopId = 0
Begin
select
companyid,0, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase
from
#tempsales group by companyID, Billdate
end
End
drop table #tempsales
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollection]    Script Date: 10/06/2012 14:17: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].[spDailySalesCollection]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on : 16/05/2003, 08/10/2003, 06/04/2004, 13/05/2004
--Created by : R Harikrishnan, Hariharan R, Hariharan R
--Comments : For Reports, Modified removing receiptvoucherdetails table usage for taking receipt and shopid selected as 0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 18/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
-- exec spDailySalesCollection 1,''R'',''20080708'',''20080708'',1,0,0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 03/07/2011
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540
--               (defect id 33(b))
----------------------------------------------------------------------------------------------
--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 58)
-- spDailySalesCollection 1,''r'',''20110618'',''20110618'',0,0,0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-5
--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-6
--Modified by  : Bijesh.B
--Date         : 31/08/2011
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540
--               (defect id 60) - Other Receipt amount not showing
----------------------------------------------------------------------------------------------
CREATE  procedure [dbo].[spDailySalesCollection]
(
@intCompanyID  as int,
@strDateRangeType  as char(1),
@strFromDate   as varchar(10),
@strToDate   as varchar(10),
@intShopID   as int,
@intDeptID  as int,
@intChkDeptID  as int,
@intChkAllShops as int=0,  --RefNo-4
@intOptDepWise as int=0  --RefNo-5
)
as
set nocount on
create table #tempSales
(
companyid int,
departmentid int,
shopid int,
billdate datetime,
cashsales numeric(18,2),
dcashsales numeric(18,2),
ccashsales numeric(18,2),
creditcard numeric(18,2),
dcreditcard numeric(18,2),
ccreditcard numeric(18,2),
debitcard numeric(18,2),
ddebitcard numeric(18,2),
cdebitcard numeric(18,2),
receipts numeric(18,2),
dreceipts numeric(18,2),
creceipts numeric(18,2),
payments numeric(18,2),
dpayments numeric(18,2),
cpayments numeric(18,2),
creditsales numeric(18,2),
dcreditsales numeric(18,2),
ccreditsales numeric(18,2),
localpurchase numeric(18,2),
dlocalpurchase numeric(18,2),
clocalpurchase numeric(18,2),
--RefNo-2 start -----------
PdChequeSales numeric(18,2),
dPdChequeSales numeric(18,2),
cPdChequeSales numeric(18,2)
--RefNo-2 ends -----------
)
declare @strSQL as nvarchar(3000)
-- cashsales
set @strSQl = N'' insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, sum(actamount) cashsales,
sum(damount) dcashsales, sum(camount) 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, 0.0 as localpurchase,
0.0 as dlocalpurchase , 0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from vwcashsalestruncated cs, aaccountmaster am  where
am.misc=''''CA'''' and cs.accountid = am.accountid and cs.companyid = am.companyid and cash = 1''
--set @strDateRangeType =''R''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intdeptid>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--Credit Card
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2),sum(actamount)) as creditcard, convert(numeric(18,2),sum(damount)) as dcreditcard,
convert(numeric(18,2),sum(camount)) 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, 0.0 as localpurchase, 0.0 as dlocalpurchase,
0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from vwcashsalestruncated cs, aaccountmaster am where
am.misc = ''''CC'''' and
cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--debit card sales
set @strSQl = N''
insert into #tempSales
select cs.companyid,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, convert(numeric(18,2),sum(actamount))
as debitcard, convert(numeric(18,2),sum(damount)) as ddebitcard, convert(numeric(18,2),sum(camount))
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
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from vwcashsalestruncated cs, aaccountmaster am where
am.misc =''''DC'''' and cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--Receipts
set @strSQl = N''
insert into #tempSales
select drcompanyid,drdepartmentid departmentid, 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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from losDummyReceiptHeader rh, acustomermaster cm where drcancelled=0 and rh.drcustomerid=
cm.customerid and rh.drcompanyid=cm.companyid ''
set @strSQL=@strSQL + N'' and drcompanyid='' + convert(varchar(10),@intCompanyID)
--RefNo-5 start
if @intOptDepWise = 1
set @strSQL=@strSQL + N'' and drcancelledremarks=''''Accounted''''''
--RefNo-5 ends
if @intShopID>0
set @strSQL=@strSQL + N'' and drshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and drdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and drdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by drcompanyid, drdepartmentid, drshopid, drdate''
exec sp_Executesql @strSQl
--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
if @intChkAllShops <> 1  --RefNo-4
Begin
set @strSQl = N''
insert into #tempSales
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,2),sum(customeramount)) receipts,
convert(numeric(18,2),sum(amount * depexrate)) dreceipts,
convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from receiptvoucherheader rh
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is not null ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
exec sp_Executesql @strSQl
end
--FOR TAKING MULTICUSTOMER RECEIPTS - hari 040406
--for receipts of customers
-- RefNo-3 starts
/*
set @strSQl = N''
insert into #tempSales
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,2),sum(rcd.customeramount)) receipts,
convert(numeric(18,2),sum(rcd.amount * depexrate)) dreceipts,
convert(numeric(18,2),sum(rcd.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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from receiptvoucherheader rh, receiptvouchercustomerdetails rcd
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is null and
rh.ReceiptId = rcd.ReceiptId and rh.CompanyId = rcd.CompanyId ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
*/
-- RefNo-6 starts  commented below
/*
set @strSQl = N''
insert into #tempSales
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,2),sum(rh.customeramount)) receipts,
convert(numeric(18,2),sum(rh.Amount*rh.depexrate )) dreceipts,
convert(numeric(18,2),sum(rh.Amount*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
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from receiptvoucherheader rh, receiptvouchercustomerdetails rcd
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is null and
rh.ReceiptId = rcd.ReceiptId and rh.CompanyId = rcd.CompanyId ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
-- RefNo-3 ends
*/
-- bewlow copied from vwDailySalesCollection
-- For Populating Other Receipts
-- Other Receipts is done in Departments So ShopId will be 0
set @strSQl = N''
insert into #tempSales
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,2),sum(Amount)) receipts,
convert(numeric(18,2),sum(Amount * depexrate)) dreceipts,
convert(numeric(18,2),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 end -------------------
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)) ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
-- RefNo-6 ends
exec sp_Executesql @strSQl
set @strSQl = N''
insert into #tempSales
select phcompanyid,phdepartmentid departmentid, 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,2),sum(phAmount)) as payments, convert(numeric(18,2),sum(phAmount*
phdepexrate)) as dpayments, convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from LOsPaymentVoucherHeader ph where phcancelled=0  ''
set @strSQL=@strSQL + N'' and phcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and phshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and phdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and phPaymentDate between '''''' + @strFromDate + N'''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by phcompanyid,phdepartmentid, phshopid, phPaymentDate''
exec sp_Executesql @strSQl
--credit sales
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 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, convert(numeric(18,2),sum(actamount)) as creditsales,
convert(numeric(18,2),sum(damount)) as dcreditsales, convert(numeric(18,2),sum(camount))
as ccreditsales, 0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from vwcashsalestruncated cs where cash=0
and transtype <> ''''PD CHEQUE''''''   --RefNo-2
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--RefNo-2 start --------------------------------------------------------
-- PD Cheque Amount only
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 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,
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
convert(numeric(18,2),sum(actamount)) as PdChequeSales,
convert(numeric(18,2),sum(damount)) as dPdChequeSales,
convert(numeric(18,2),sum(camount)) as cPdChequeSales
from vwcashsalestruncated cs where cash=0 and transtype = ''''PD CHEQUE''''''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,departmentid, shopid, billdate''
exec sp_Executesql @strSQl
--RefNo-2 ends --------------------------------------------------------
--local purchase - madhu 23/08/01
set @strSQl = N''
insert into #tempSales
select lh.lphcompanyid,lh.lphdepartmentid departmentid,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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),sum(lphbillamount*lphexchangerate)) as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from loslocalpurchaseheader lh,adepartmentmaster d where
lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0 ''
set @strSQL=@strSQL + N'' and lphcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and lphshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and lphdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and lphbilldate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + N''group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate''
exec sp_Executesql @strSQl
if @intDeptID <> 0
Begin
select
companyid,departmentid, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
from
#tempsales where departmentid = @intDeptID
group by
companyID,departmentID,Billdate
end
else
Begin
if @intShopId <> 0
Begin
select
companyid,0 departmentid, ShopID shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
from
#tempsales where shopid = @intShopID
group by
companyID, ShopID, Billdate
end
if @intShopId = 0
Begin
select
companyid,0 departmentid, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales))dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales))cPdChequeSales
--RefNo-2 ends -------------------------
from
#tempsales group by companyID, Billdate
end
End
drop table #tempsales
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSalesQtyWise]    Script Date: 10/06/2012 14:17: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].[spCustomerSalesQtyWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spCustomerSalesQtyWise 2009,'''','''',1,'''',''''
--------------------------------------------------------------------------------
-- Created By : Hariharan
-- Created Date : 13/11/2003
-- modifiesdate :25/02/04 added department,cumpanyvalue
-- modified 15/04/03 used convert
--------------------------------------------------------------------------------
-- Modified By: Regin
-- Modified On: 22-09-2009
-- Modification:
-- Added the parameter @intEnableSalesDrilldown
-- Added the second Union All portion to get the details of only Cash Sales
-- Purpose:
-- To show Cash Sale Value separately in Customer Sales Itemwise report.
--------------------------------------------------------------------------------
-- Parameter Details
-- If @intEnableSalesDrilldown=0, the sp gives only the details of all sales as a whole.
-- If @intEnableSalesDrilldown=1, then sp gives All Sales, and drilldown of Cash Sales.
--------------------------------------------------------------------------------
-- Modified By: jyothish
-- Modified On: 22-09-2009
-- Modification:
-- Added the parameter sales person name and id  is added to the output
---------------------------------------------------------------------------------
-- exec spCustomerSalesQtyWise 2009,0,0,1,'''',''''
-- Modified By: VinothMurugan V
-- Modified On: 02-10-2010
-- Modification:
-- Added the column ihCustomerId,IdItemId
-- Purpose:
-- It used for another Stored Procedures name as "spNonBuyingCustomersItemwise"
--------------------------------------------------------------------------------
CREATE   Proc [dbo].[spCustomerSalesQtyWise] (@intYear as int, @intShopid as int,
@intDepId as int, @intCompanyId as int, @strBrand as varchar(2000),
@strItemCategoryid as varchar(2000),@strCustomerIDs as varchar(5000)='''',
@intEnableSalesDrilldown as int = 0)
as
Declare @strsql as nvarchar(4000)
Begin
-- To get the details of ALL sales
set @strsql = ''select ihshopid,IdItemId, substring(ItemDescription,1,  250) itemdescription,ihCustomerId,CustomerName,
sum(Quantity) Quantity ,month(ihinvoicedate) MonthNo, vunitcode, vUnitName, code,
vBrand, vitemCategoryid,  case '' + convert(varchar(5),@intDepId) + '' when 0 then  convert(numeric(18,2),
sum(csalesvalue)) else convert(numeric(18,2),sum(dsalesvalue)) end  salesvalue,
''''All Sales'''' SalesType,salespersonid,AsalesPersonmaster.Spername from
vwCustomerSalesQtyWise left outer  join AsalesPersonmaster on  AsalesPersonmaster.Sperid= vwCustomerSalesQtyWise.salespersonid  where year(ihInvoiceDate ) = '' +  convert(varchar(4), @intYear)
if @intDepId >0 and @intShopid = 0
set @strsql = @strsql + '' and ihDepartmentid = '' + convert(varchar(3), @intdepid)
if @intshopid >0
set @strsql = @strsql + '' and ihShopid = '' + convert(varchar(3), @intShopId)
if ltrim(rtrim(@strBrand)) <> ''''
set @strsql = @strsql + '' and vBrand in ( '' + @strBrand + '' ) ''
if ltrim(rtrim(@strItemCategoryid)) <> ''''
set @strsql = @strsql + '' and vItemCategoryid in ( '' + @strItemCategoryid + '' ) ''
if ltrim(rtrim(@strCustomerIDs)) <> ''''
set @strsql = @strsql + '' and ihCustomerid '' + @strCustomerIDs
set @strsql  = @strsql + '' group by ihshopid,IdItemId,itemdescription,ihCustomerId,CustomerName,
month(ihinvoicedate) , vunitcode, vUnitName, code, vBrand, vitemCategoryid,salespersonid,AsalesPersonmaster.Spername ''
-- If the SalesType is not considered in the program, below portion should not
-- be included in the result set, since it is a split up on sales type.
-- @intEnableSalesDrilldown is 0 by default ensuring that duplicate values are not generated.
if @intEnableSalesDrilldown=1
begin
set @strsql = @strsql + '' union all ''
-- To get the details of ONLY Cash Sales
-- This portion is just similar to the above query, but
-- 1. additionally [(Type=''''Cash Sales'''' or Type = ''''Exchanged Out'''' or Type = ''''Exchanged In'''')]
--   condition added for filtering sales.
-- 2. SalesType is ''Cash Sales''
set @strsql = @strsql  + ''select ihshopid,IdItemId,substring(ItemDescription,1,  250) itemdescription,ihCustomerId,CustomerName,
sum(Quantity) Quantity ,month(ihinvoicedate) MonthNo, vunitcode, vUnitName, code,
vBrand, vitemCategoryid,  case '' + convert(varchar(5),@intDepId) + '' when 0 then  convert(numeric(18,2),
sum(csalesvalue)) else convert(numeric(18,2),sum(dsalesvalue)) end  salesvalue,
''''Cash Sales'''' SalesType,salespersonid,AsalesPersonmaster.Spername from
vwCustomerSalesQtyWise left outer  join AsalesPersonmaster on  AsalesPersonmaster.Sperid= vwCustomerSalesQtyWise.salespersonid   where (Type=''''Cash Sales'''' or Type = ''''Exchanged Out'''' or Type = ''''Exchanged In'''')
and year(ihInvoiceDate ) = '' +  convert(varchar(4), @intYear)
if @intDepId >0 and @intShopid = 0
set @strsql = @strsql + '' and ihDepartmentid = '' + convert(varchar(3), @intdepid)
if @intshopid >0
set @strsql = @strsql + '' and ihShopid = '' + convert(varchar(3), @intShopId)
if ltrim(rtrim(@strBrand)) <> ''''
set @strsql = @strsql + '' and vBrand in ( '' + @strBrand + '' ) ''
if ltrim(rtrim(@strItemCategoryid)) <> ''''
set @strsql = @strsql + '' and vItemCategoryid in ( '' + @strItemCategoryid + '' ) ''
if ltrim(rtrim(@strCustomerIDs)) <> ''''
set @strsql = @strsql + '' and ihCustomerid '' + @strCustomerIDs
set @strsql  = @strsql + '' group by ihshopid,IdItemId, itemdescription,ihCustomerId, CustomerName,
month(ihinvoicedate) , vunitcode, vUnitName, code, vBrand, vitemCategoryid,salespersonid,AsalesPersonmaster.Spername ''
end --End of if @intEnableSalesDrilldown=1
exec sp_Executesql @strsql
--print @strsql
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionUserWise]    Script Date: 10/06/2012 14:17: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].[spDailySalesCollectionUserWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on : 16/05/2003, 08/10/2003, 06/04/2004, 13/05/2004
--Created by : R Harikrishnan, Hariharan R, Hariharan R
--Comments : For Reports, Modified removing receiptvoucherdetails table usage for taking receipt and shopid selected as 0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 18/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
-- exec spDailySalesCollection 1,''R'',''20080708'',''20080708'',1,0,0
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 03/07/2011
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540
--               (defect id 33(b))
----------------------------------------------------------------------------------------------
--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 58)
-- spDailySalesCollection 1,''r'',''20110618'',''20110618'',0,0,0
----------------------------------------------------------------------------------------------
-- 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
--              : copy of spDailySalesCollection and modified
-- spDailySalesCollectionUserWise 1,''R'',''20110705'',''20110705'',1,0,1,0
------------------------------------------------------------------------------------------					  		
CREATE  procedure [dbo].[spDailySalesCollectionUserWise]
(
@intCompanyID  as int,
@strDateRangeType  as char(1),
@strFromDate   as varchar(10),
@strToDate   as varchar(10),
@intShopID   as int,
@intDeptID  as int,
@intChkDeptID  as int,
@intChkAllShops as int=0  --RefNo-4
)
as
set nocount on
create table #tempSales
(
companyid int,
departmentid int,
shopid int,
billdate datetime,
cashsales numeric(18,2),
dcashsales numeric(18,2),
ccashsales numeric(18,2),
creditcard numeric(18,2),
dcreditcard numeric(18,2),
ccreditcard numeric(18,2),
debitcard numeric(18,2),
ddebitcard numeric(18,2),
cdebitcard numeric(18,2),
receipts numeric(18,2),
dreceipts numeric(18,2),
creceipts numeric(18,2),
payments numeric(18,2),
dpayments numeric(18,2),
cpayments numeric(18,2),
creditsales numeric(18,2),
dcreditsales numeric(18,2),
ccreditsales numeric(18,2),
localpurchase numeric(18,2),
dlocalpurchase numeric(18,2),
clocalpurchase numeric(18,2),
--RefNo-2 start -----------
PdChequeSales numeric(18,2),
dPdChequeSales numeric(18,2),
cPdChequeSales numeric(18,2)
--RefNo-2 ends -----------
,UserID int  --RefNo-5
)
declare @strSQL as nvarchar(3000)
-- cashsales
set @strSQl = N'' insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, sum(actamount) cashsales,
sum(damount) dcashsales, sum(camount) 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, 0.0 as localpurchase,
0.0 as dlocalpurchase , 0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales,cs.UserID
from vwcashsalestruncated cs, aaccountmaster am  where
am.misc=''''CA'''' and cs.accountid = am.accountid and cs.companyid = am.companyid and cash = 1''
--set @strDateRangeType =''R''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intdeptid>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate,cs.UserID''
exec sp_Executesql @strSQl
--Credit Card
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2),sum(actamount)) as creditcard, convert(numeric(18,2),sum(damount)) as dcreditcard,
convert(numeric(18,2),sum(camount)) 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, 0.0 as localpurchase, 0.0 as dlocalpurchase,
0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales,cs.UserID
from vwcashsalestruncated cs, aaccountmaster am where
am.misc = ''''CC'''' and
cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate,cs.UserID''
exec sp_Executesql @strSQl
--debit card sales
set @strSQl = N''
insert into #tempSales
select cs.companyid,departmentid, shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, convert(numeric(18,2),sum(actamount))
as debitcard, convert(numeric(18,2),sum(damount)) as ddebitcard, convert(numeric(18,2),sum(camount))
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
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales,cs.UserID
from vwcashsalestruncated cs, aaccountmaster am where
am.misc =''''DC'''' and cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,departmentid, shopid, billdate,cs.UserID''
exec sp_Executesql @strSQl
--Receipts
set @strSQl = N''
insert into #tempSales
select drcompanyid,drdepartmentid departmentid, 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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
,ISNULL(rh.drUserID,0) as UserID
from losDummyReceiptHeader rh, acustomermaster cm where drcancelled=0 and rh.drcustomerid=
cm.customerid and rh.drcompanyid=cm.companyid ''
set @strSQL=@strSQL + N'' and drcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and drshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and drdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and drdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by drcompanyid, drdepartmentid, drshopid, drdate,ISNULL(rh.drUserID,0)''
exec sp_Executesql @strSQl
--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
if @intChkAllShops <> 1  --RefNo-4
Begin
	set @strSQl = N''
	insert into #tempSales
	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,2),sum(customeramount)) receipts,
	convert(numeric(18,2),sum(amount * depexrate)) dreceipts,
	convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
	,ISNULL(rh.UserID,0)as UserID
	from receiptvoucherheader rh
	where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
	(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is not null ''
	set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
	if @intDeptID>0
	 set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
	 set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
	
	set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate,ISNULL(rh.UserID,0)''
	
	exec sp_Executesql @strSQl
end
--FOR TAKING MULTICUSTOMER RECEIPTS - hari 040406
--for receipts of customers
-- RefNo-3 starts
/*
set @strSQl = N''
insert into #tempSales
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,2),sum(rcd.customeramount)) receipts,
convert(numeric(18,2),sum(rcd.amount * depexrate)) dreceipts,
convert(numeric(18,2),sum(rcd.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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
from receiptvoucherheader rh, receiptvouchercustomerdetails rcd
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is null and
rh.ReceiptId = rcd.ReceiptId and rh.CompanyId = rcd.CompanyId ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate''
*/
set @strSQl = N''
insert into #tempSales
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,2),sum(rh.customeramount)) receipts,
convert(numeric(18,2),sum(rh.Amount*rh.depexrate )) dreceipts,
convert(numeric(18,2),sum(rh.Amount*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
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
,ISNULL(rh.UserID,0) as UserID
from receiptvoucherheader rh, receiptvouchercustomerdetails rcd
where rh.cancelled=0 and ((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) and rh.customerid is null and
rh.ReceiptId = rcd.ReceiptId and rh.CompanyId = rcd.CompanyId ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, rh.receiptdate,ISNULL(rh.UserID,0)''
-- RefNo-3 ends
exec sp_Executesql @strSQl
set @strSQl = N''
insert into #tempSales
select phcompanyid,phdepartmentid departmentid, 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,2),sum(phAmount)) as payments, convert(numeric(18,2),sum(phAmount*
phdepexrate)) as dpayments, convert(numeric(18,2),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 PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
,ISNULL(ph.phUserID,0) as UserID
from LOsPaymentVoucherHeader ph where phcancelled=0  ''
set @strSQL=@strSQL + N'' and phcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and phshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and phdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and phPaymentDate between '''''' + @strFromDate + N'''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by phcompanyid,phdepartmentid, phshopid, phPaymentDate,ISNULL(ph.phUserID,0)''
exec sp_Executesql @strSQl
--credit sales
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 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, convert(numeric(18,2),sum(actamount)) as creditsales,
convert(numeric(18,2),sum(damount)) as dcreditsales, convert(numeric(18,2),sum(camount))
as ccreditsales, 0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
,cs.UserID as UserID
from vwcashsalestruncated cs where cash=0
and transtype <> ''''PD CHEQUE''''''   --RefNo-2
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,departmentid, shopid, billdate,cs.UserID''
exec sp_Executesql @strSQl
--RefNo-2 start --------------------------------------------------------			
-- PD Cheque Amount only
set @strSQl = N''
insert into #tempSales
select cs.companyid ,departmentid, shopid, billdate, 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,
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
convert(numeric(18,2),sum(actamount)) as PdChequeSales,
convert(numeric(18,2),sum(damount)) as dPdChequeSales,
convert(numeric(18,2),sum(camount)) as cPdChequeSales
,cs.UserID as UserID
from vwcashsalestruncated cs where cash=0 and transtype = ''''PD CHEQUE''''''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,departmentid, shopid, billdate,cs.UserID''
exec sp_Executesql @strSQl
--RefNo-2 ends --------------------------------------------------------
--local purchase - madhu 23/08/01
set @strSQl = N''
insert into #tempSales
select lh.lphcompanyid,lh.lphdepartmentid departmentid,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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),sum(lphbillamount*lphexchangerate)) as clocalpurchase
,0.0 as PdChequeSales, 0.0 as dPdChequeSales, 0.0 as cPdChequeSales
,ISNULL(lh.lphUserID,0) as UserID
from loslocalpurchaseheader lh,adepartmentmaster d where
lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0 ''
set @strSQL=@strSQL + N'' and lphcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
set @strSQL=@strSQL + N'' and lphshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
set @strSQL=@strSQL + N'' and lphdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
set @strSQL=@strSQL + N'' and lphbilldate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + N''group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate,ISNULL(lh.lphUserID,0)''
exec sp_Executesql @strSQl
if @intDeptID <> 0
Begin
select
companyid,departmentid, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
,UserID
from
#tempsales where departmentid = @intDeptID
group by
companyID,departmentID,Billdate,UserID
end
else
Begin
if @intShopId <> 0
Begin
select
companyid,0 departmentid, ShopID shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
,UserID
from
#tempsales where shopid = @intShopID
group by
companyID, ShopID, Billdate ,UserID
end
if @intShopId = 0
Begin
select
companyid,0 departmentid, 0 shopid, billdate,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
else convert(numeric(18,2),sum(dcashsales)) end cashsales,
convert(numeric(18,2),sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
else convert(numeric(18,2),sum(dreceipts)) end receipts,
convert(numeric(18,2),sum(dreceipts)) dreceipts,
convert(numeric(18,2),sum(creceipts)) creceipts,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
else convert(numeric(18,2),sum(dpayments)) end payments,
convert(numeric(18,2),sum(dpayments)) dpayments ,
convert(numeric(18,2),sum(cpayments)) cpayments ,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
--RefNo-2 start -------------------------
case when @intChkDeptID =0 then convert(numeric(18,2),sum(cPdChequeSales))
else convert(numeric(18,2),sum(dPdChequeSales)) end PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales))dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales))cPdChequeSales
--RefNo-2 ends -------------------------
,UserID
from
#tempsales group by companyID, Billdate,UserID
end
End
drop table #tempsales
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumBackup]    Script Date: 10/06/2012 14:17: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].[spCreditorAgeSumBackup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spcreditoragesum '''',''20060517'',84,9,0
-- Modified on   : 10/06/2003
-- Modified by          : Kishore
-- Comments             : (comment from v2)
--      giving  sum(a.pbhbillamount) instead of max(a.pbhbillamount)
--      at times when one bill is entered with multiple accounts
--     in detail table
--      Filtering those bills which have the bill amount settled completely
--      given max(pbhbillamount) <> sum(paidamount)
--     as there are some bills which are settled with more amount
--                        (on comparison with v2)
-- altered on   : 24/09/2002, 24/09/2003, 08/12/2004
-- Altered by   : venki, R Harikrishnan , Hariharan
-- comments  : added creditaccid
--    : Added account desc
-- Modified By :shinu
-- Modified ON :18062007
-- Comments : Removed Department Condition Because Bill Entered in One Department Can be settled in
--              another department.so if the condition is there then it will show as unsettled
-------------------------------------------------------------------------------------------------------------------------
-- adminv2.dbo.spCreditorAgeSum '''', ''20090101'', '''', 0
create PROCEDURE [dbo].[spCreditorAgeSumBackup] ( @dtstartdate varchar(11),@dtbilldate as varchar(11),
@strvendorid varchar(500), @intdepartid int,@intageTodate int=0 )
as
set ansi_Warnings off
set nocount on
begin
Create table #tmpBills
(CompanyID int,
shopid int,
DepartmentID int,
billsid int,
pbhVendorID int,
Billsno varchar(50),
pbhremarks varchar(1000),
Referenceno varchar (100),
pbhBilldate datetime,
duedate datetime ,
pbhBillAmount numeric(18,2),
Due varchar(7),
Type varchar(4),
updatetime datetime,
age int  )
Create Table #tmpSettlements
(
companyid int,
departmentid int,
billsid  int,
settleddate datetime,
paidamount  numeric(18,2),
vendorid int,
shopid int,
Type varchar(50))
declare @strquery as nvarchar(4000)
declare @SettleVendId as varchar(1500), @BillVendid as varchar(1500)
SET @SettleVendId = ''''
set @BillVendid = ''''
if @strvendorid <>'' ''    --hari given to handle with out customerid also
Begin
--set @strvendorid = '' a.pbhvendorid in ('' + @strvendorid + '')''
set @SettleVendId = '' vendorid in ('' + @strvendorid + '') and ''
set @BillVendid = '' vwBills.pbhVendorID in ('' + @strvendorid + '') and ''
End
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and pbhbilldate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''' +
'''''' and pbhbilldate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' +
@SettleVendId + '' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where ''
+ @SettleVendId + '' settleddate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' + @SettleVendId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where '' + @SettleVendId +
''  settleddate <='''''' + @dtbilldate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
--select * from #tmpSettlements
--select * from #tmpBills
set @strquery = ''select max(a.pbhbillamount) billamount,
sum(a.paidamount) paidamount , a.pbhvendorid ,
a.shopid,a.departmentid,a.billsid,a.type,a.due, a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,
creditoraccid,b.AccountDesc from (SELECT
vwbills.companyid, vwbills.shopid, vwbills.departmentid,
vwbills.billsid,vwbills.pbhVendorID, vwbills.billsno,
vwbills.pbhremarks, vwbills.referenceno,
vwbills.pbhbilldate, vwbills.duedate, vwbills.pbhBillAmount,
vwbills.Due,vwbills.type, vwbills.updatetime,
isnull(vwpayments.PaidAmount,0) paidamount,
aVendorMaster.VendorName,
aCurrencyMaster.CurrencyName, aCurrencyMaster.Symbol,creditoraccid
FROM { oj ((#tmpBills vwbills INNER JOIN aVendorMaster
aVendorMaster ON vwbills.pbhVendorID = aVendorMaster.VendorID)
LEFT OUTER JOIN #tmpSettlements vwpayments ON
vwbills.companyid = vwpayments.companyid AND
vwbills.billsid = vwpayments.billsid AND
vwbills.pbhVendorID = vwpayments.vendorid AND
vwbills.shopid = vwpayments.shopid and
vwbills.type = vwpayments.type and
/*vwbills.departmentid = vwpayments.departmentid and  */
(vwpayments.settleddate <='''''' + @dtbilldate + '''''' or
vwpayments.settleddate is null))
INNER JOIN aCurrencyMaster aCurrencyMaster ON
aVendorMaster.CurrencyID = aCurrencyMaster.CurrencyID AND
aVendorMaster.CompanyID = aCurrencyMaster.CompanyID})  a,
aAccountMaster b
where a.CreditorAccID = b.AccountID and a.pbhbilldate<='''''' + @dtbilldate + '''''''' +
''group by a.pbhvendorid , a.shopid,a.departmentid,a.billsid,a.type,a.due,a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,creditoraccid,b.AccountDesc
having max(a.pbhbillamount) <> sum(a.paidamount)''
if @intageTodate=1
begin
update #tmpBills set age=datediff(day,pbhBilldate,CONVERT(DATETIME, @dtbilldate,102))
update #tmpBills 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
drop table #tmpBills
drop table #tmpSettlements
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumAllBills]    Script Date: 10/06/2012 14:17: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].[spCreditorAgeSumAllBills]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This SP spCreditorAgeSumAllBills was created to display all bill details including settled bills.
-- spCreditorAgeSum was just copied and below condition was removed.
-- Condition [having max(a.pbhbillamount) <> sum(a.paidamount)] is removed.
--------------------------------------------------------------------------------
-- This SP is going to be used by spPOPaymentStatus to generate PO Payment Status Report
-- This report model is given by Sonee
--------------------------------------------------------------------------------
-- Coded By: Regin T.
-- Coded On: 07-05-2009
--------------------------------------------------------------------------------
-- Caution: If this sp is changed, spPOPaymentStatus may not work.
--------------------------------------------------------------------------------
--exec spcreditoragesum '''',''20060517'',84,9,0
-- Modified on   : 10/06/2003
-- Modified by          : Kishore
-- Comments             : (comment from v2)
--      giving  sum(a.pbhbillamount) instead of max(a.pbhbillamount)
--      at times when one bill is entered with multiple accounts
--     in detail table
--      Filtering those bills which have the bill amount settled completely
--      given max(pbhbillamount) <> sum(paidamount)
--     as there are some bills which are settled with more amount
--                        (on comparison with v2)
-- altered on   : 24/09/2002, 24/09/2003, 08/12/2004
-- Altered by   : venki, R Harikrishnan , Hariharan
-- comments  : added creditaccid
--    : Added account desc
-- Modified By :shinu
-- Modified ON :18062007
-- Comments : Removed Department Condition Because Bill Entered in One Department Can be settled in
--              another department.so if the condition is there then it will show as unsettled
-------------------------------------------------------------------------------------------------------------------------
-- adminv2.dbo.spCreditorAgeSumAllBills '''', ''20090101'', '''', 0
CREATE PROCEDURE [dbo].[spCreditorAgeSumAllBills] ( @dtstartdate varchar(11),@dtbilldate as varchar(11),
@strvendorid varchar(500), @intdepartid int=0,@intageTodate int=0 )
as
set ansi_Warnings off
set nocount on
begin
Create table #tmpBills
(CompanyID int,
shopid int,
DepartmentID int,
billsid int,
pbhVendorID int,
Billsno varchar(50),
pbhremarks varchar(1000),
Referenceno varchar (100),
pbhBilldate datetime,
duedate datetime ,
pbhBillAmount numeric(18,2),
Due varchar(7),
Type varchar(4),
updatetime datetime,
age int  )
Create Table #tmpSettlements
(
companyid int,
departmentid int,
billsid  int,
settleddate datetime,
paidamount  numeric(18,2),
vendorid int,
shopid int,
Type varchar(50))
declare @strquery as nvarchar(4000)
declare @SettleVendId as varchar(1500), @BillVendid as varchar(1500)
SET @SettleVendId = ''''
set @BillVendid = ''''
if @strvendorid <>'' ''    --hari given to handle with out customerid also
Begin
--set @strvendorid = '' a.pbhvendorid in ('' + @strvendorid + '')''
set @SettleVendId = '' vendorid in ('' + @strvendorid + '') and ''
set @BillVendid = '' vwBills.pbhVendorID in ('' + @strvendorid + '') and ''
End
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and pbhbilldate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''' +
'''''' and pbhbilldate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' +
@SettleVendId + '' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where ''
+ @SettleVendId + '' settleddate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' + @SettleVendId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where '' + @SettleVendId +
''  settleddate <='''''' + @dtbilldate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
--select * from #tmpSettlements
--select * from #tmpBills
set @strquery = ''select max(a.pbhbillamount) billamount,
sum(a.paidamount) paidamount , a.pbhvendorid ,
a.shopid,a.departmentid,a.billsid,a.type,a.due, a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,
creditoraccid,b.AccountDesc from (SELECT
vwbills.companyid, vwbills.shopid, vwbills.departmentid,
vwbills.billsid,vwbills.pbhVendorID, vwbills.billsno,
vwbills.pbhremarks, vwbills.referenceno,
vwbills.pbhbilldate, vwbills.duedate, vwbills.pbhBillAmount,
vwbills.Due,vwbills.type, vwbills.updatetime,
isnull(vwpayments.PaidAmount,0) paidamount,
aVendorMaster.VendorName,
aCurrencyMaster.CurrencyName, aCurrencyMaster.Symbol,creditoraccid
FROM { oj ((#tmpBills vwbills INNER JOIN aVendorMaster
aVendorMaster ON vwbills.pbhVendorID = aVendorMaster.VendorID)
LEFT OUTER JOIN #tmpSettlements vwpayments ON
vwbills.companyid = vwpayments.companyid AND
vwbills.billsid = vwpayments.billsid AND
vwbills.pbhVendorID = vwpayments.vendorid AND
vwbills.shopid = vwpayments.shopid and
vwbills.type = vwpayments.type and
/*vwbills.departmentid = vwpayments.departmentid and  */
(vwpayments.settleddate <='''''' + @dtbilldate + '''''' or
vwpayments.settleddate is null))
INNER JOIN aCurrencyMaster aCurrencyMaster ON
aVendorMaster.CurrencyID = aCurrencyMaster.CurrencyID AND
aVendorMaster.CompanyID = aCurrencyMaster.CompanyID})  a,
aAccountMaster b
where a.CreditorAccID = b.AccountID and a.pbhbilldate<='''''' + @dtbilldate + '''''''' +
''group by a.pbhvendorid , a.shopid,a.departmentid,a.billsid,a.type,a.due,a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,creditoraccid,b.AccountDesc''
--   having max(a.pbhbillamount) <> sum(a.paidamount)''            --This line is commented to show all bills
if @intageTodate=1
begin
update #tmpBills set age=datediff(day,pbhBilldate,CONVERT(DATETIME, @dtbilldate,102))
update #tmpBills 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
drop table #tmpBills
drop table #tmpSettlements
end' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnHourRange]    Script Date: 10/06/2012 14:17: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].[fnHourRange]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
---select * from dbo.fnHourRange(0,23)
CREATE function [dbo].[fnHourRange] (@StartH int,@EndH int)
returns @output table
(
Hint  int,
HRange varchar(12)
)
as
begin
declare @Hint as int
set @Hint=0
;with cte(Hint,HRange)  -- Common Table Expression for recurcive
as
(
select @Hint,convert(varchar,@Hint)+'':00-''+convert(varchar,@Hint+1)+'':00''
union all
--select Hint=Hint+1,convert(varchar,Hint)+'':00-''+  convert(varchar,Hint+1)+  '':00'' from cte where Hint<@EndH
select Hint=Hint+1,convert(varchar,Hint+1)+'':00-''+ case when Hint+1=23 then ''00:00'' else convert(varchar,Hint+2)+ '':00''  end HRange
from cte where Hint<@EndH
)
insert into @output select * from cte
return
end' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnSplit]    Script Date: 10/06/2012 14:17: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].[fnSplit]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--------------------------------------------------------
--Created By   : Prasanth Joseph
--Created on   : 25-01-2009
--Created For  : To get Split up from a string
--Modified By  :
----------------------------------------------------------
CREATE  FUNCTION [dbo].[fnSplit](
@sInputList VARCHAR(8000) -- List of delimited items
,@sDelimiter VARCHAR(8000) = '' '' -- delimiter that separates items
) RETURNS @List TABLE (Cid VARCHAR(1500))
BEGIN
DECLARE @intID VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@intID=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@intID) > 0
INSERT INTO @List SELECT @intID
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList
RETURN
end' 
END
GO
/****** Object:  View [dbo].[vwCompanyTotalStock]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyTotalStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Shinu
-- Created on  : 02/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Stock of the Company
------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCompanyTotalStock] AS
select companyId,ai.ItemID,ItemCode,ai.ItemDescription,UnitName,ItemCategoryID,Brand,ShopID LocationID,ShopName LocationName,Type,
isnull(CompStock.Stock,0)Stock,max(ItemCostPrice)ItemCostPrice,openingStock  FROM
(SELECT companyId,ash.ShopID,ShopName,''S''Type,ItemID,Stock,max(ItemCostPrice)ItemCostPrice,openingStock FROM vwInquiryShopStock vw
INNER JOIN aShops ash ON vw.ShopID=ash.ShopID
group By companyId,ash.ShopID,ItemID,Stock ,ShopName,openingStock
UNION ALL
SELECT companyId,gsGodownID,GodownName,''G'',gsItemID,gsStock,max(gsItemCost) ,gsopeningStock FROM vwInquiryGodownStock
INNER JOIN aGodown ON GodownID=gsGodownID
group By companyId,gsGodownID,gsItemID,gsStock,GodownName,gsopeningStock) COMPSTOCK
LEFT OUTER JOIN (SELECT ait.ItemID,ItemCode,ait.ItemDescription,UnitName,ItemCategoryID,Brand FROM aItem ait INNER JOIN aUnit au
ON ait.UnitsID=au.UnitID) AI ON ai.ItemID=CompStock.ItemID
group by companyId,ai.ItemID,ai.ItemDescription,CompStock.ItemID,Stock,UnitName,ShopID,ShopName,Type,
ItemCategoryID,Brand,ItemCode ,openingStock'
GO
/****** Object:  StoredProcedure [dbo].[spMag_LocationwiseStock]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_LocationwiseStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--CREATED BY: NIDHEESH PV
--CREATED ON: 02/09/2011
--COMMENTS: TO LIST LOCATION WISE STOCK
--TO USE IN LOCATION WISE SSRS REPORT
--spMag_LocationwiseStock 1,'''','' No Brand''
CREATE PROC [dbo].[spMag_LocationwiseStock](
@intCompId AS INT,@strCateId AS VARCHAR(max) ='''',@strBrand AS VARCHAR(max)='''')
AS
BEGIN
SET NOCOUNT ON
--if patindex(''%No Brand%'',@strBrand) > 0
--begin
SELECT * into #tempItemBrand FROM dbo.fnSplit(@strBrand,'','') where cid<>''No Brand''
--end
SELECT companyId,ItemID,ItemCode,ItemDescription,LocationID,LocationName,Stock,openingStock,Brand,ItemCategoryID,ItemCostPrice
INTO #tempCmpstock
FROM vwCompanyTotalStock
WHERE ((ItemCategoryID IN (SELECT * FROM dbo.fnSplit(@strCateId,'',''))) OR (@strCateId=''''))
--AND ((Brand IN (SELECT * FROM dbo.fnSplit(@strBrand,'',''))) OR (@strBrand=''''))
--AND ((isnull(Brand,'''') IN (SELECT * FROM dbo.fnSplit(@strBrand,'',''))) OR (@strBrand=''''))
AND (@strBrand<>'' No Brand'' and (isnull(Brand,'''') IN (SELECT * FROM #tempItemBrand)) or
(@strBrand='' No Brand'' and isnull(Brand,'''')='''') )
AND companyId= @intCompId
SELECT
temp.companyId,temp.ItemCode, temp.ItemDescription
,temp.LocationName,temp.Stock,Brand,ItemCategoryID,ItemCostPrice
FROM
#tempCmpstock temp
ORDER BY temp.ItemDescription ASC
DROP TABLE #tempCmpstock
drop table #tempItemBrand
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnMultipleSplit]    Script Date: 10/06/2012 14:17: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].[fnMultipleSplit]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--select * from dbo.fnMultipleSplit(''2:1:-1:12.85:'','':'',''-'')
--------------------------------------------------------
--Created By   : Nidheesh P V
--Created on   : 15-07-2011
--Created For  : To get Split up from a string in to a table with more than one columns.
----------------------------------------------------------
CREATE  FUNCTION [dbo].[fnMultipleSplit](
@sInputList VARCHAR(8000) -- List of delimited items
,@sDelimiter VARCHAR(8000) = '' '' -- delimiter that separates items
,@ColDelimiter VARCHAR(8000) = '' '' -- column delimiter that separates columns
) RETURNS @List TABLE (Cid1 VARCHAR(1500),Cid2 VARCHAR(1500))
BEGIN
--DECLARE @intID VARCHAR(8000)
DECLARE @intIDCol1 VARCHAR(8000)
DECLARE @intIDCol2 VARCHAR(8000)
DECLARE @sInputListCol1 VARCHAR(8000)
DECLARE @sInputListCol2 VARCHAR(8000)
SET @sInputListCol1=SUBSTRING(@sInputList,0,charindex(@ColDelimiter,@sInputList)-1)
SET @sInputListCol2=REVERSE(SUBSTRING(REVERSE(@sInputList),2,charindex(@ColDelimiter,REVERSE(@sInputList))-2))
WHILE CHARINDEX(@sDelimiter,@sInputListCol1,0) <> 0
BEGIN
SET @intIDCol1=RTRIM(LTRIM(SUBSTRING(@sInputListCol1,1,CHARINDEX(@sDelimiter,@sInputListCol1,0)-1)))
SET @sInputListCol1=RTRIM(LTRIM(SUBSTRING(@sInputListCol1,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputListCol1))))
SET @intIDCol2=RTRIM(LTRIM(SUBSTRING(@sInputListCol2,1,CHARINDEX(@sDelimiter,@sInputListCol2,0)-1)))
SET @sInputListCol2=RTRIM(LTRIM(SUBSTRING(@sInputListCol2,CHARINDEX(@sDelimiter,@sInputListCol2,0)+LEN(@sDelimiter),LEN(@sInputListCol2))))
IF LEN(@intIDCol1) > 0
BEGIN
	INSERT INTO @List SELECT @intIDCol1,@intIDCol2
END
END
IF LEN(@sInputListCol1) > 0
BEGIN
INSERT INTO @List SELECT @sInputListCol1,@sInputListCol2
END
RETURN
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spsmsversion]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spsmsversion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spsmsversion    Script Date: 18/01/2003 9:45:43 PM ******/
--created by : hariharan
--created date :03/10/2002
--for getting the version of the database used for sms
CREATE proc [dbo].[spsmsversion] as
select ''VERSION 2''
return 2.0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesAnalysisByItemGstSeparately]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAnalysisByItemGstSeparately]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesAnalysisByItem]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAnalysisByItem]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spSalesAnalysisByItem 1,0,'''',''20100101'',''20101231'',0,1,1,''''
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- 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
--------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSalesAnalysisByItem] (@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
FROM vwShopItemSales 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesAndStock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAndStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created On  : 01/05/2008
-- Created By  : Shinu
-- Comments    : Created for a new Report  [rptSalesAndStock]
----------------------------------
--Updated By   : Yogesh Joe
--Updated On   : 2009-10-23
--Purpose :
-- 1)The shopid was hardcoded.Now it has changed
-- 2)The isnull condition added for stock, to show 0 if stock is null
----------------------------------
--Updated By   : SHINE DAS
--Updated On   : 2011-07-13
--Purpose :
-- 1) Current Stock was populating without Column name. In report it
-- needs to display
----------------------------------------------------------------------------------------------------------------------------------------------------------------
--spSalesAndStock 1,20061007,20081008
CREATE Proc [dbo].[spSalesAndStock] (@intShopId as int,@strFromdate as varchar(10),@strTodate as varchar(10))as
declare @strsql as nVarchar(4000)
set @strSql=''SELECT vwshopitemshipmentdetail.SellingPrice, vwshopitemshipmentdetail.WholeSalePrice,
vwshopitemshipmentdetail.DiscountPrice,
vwShopItemStockitemsItemDtls.ItemCode, vwShopItemStockitemsItemDtls.ItemDescription,
vwShopItemStockitemsItemDtls.ItemRate, vwShopItemStockitemsItemDtls.Part_code,
vwShopItemStockitemsItemDtls.PackingTypeName, vwShopItemStockitemsItemDtls.Quantity,
aCurrencyMaster.Symbol, aShopItemDetail.ShopID,isnull(vwInquiryShopStock.stock,0) CurrentStock,VwItemSalesGrouped.ItemID,
VwItemSalesGrouped.Qty, VwItemSalesGrouped.soldDate,aItemCategory.CategoryNameDescription,
aColor.ColorName,aSize.SizeName
FROM
vwshopitemshipmentdetail vwshopitemshipmentdetail
INNER JOIN aCurrencyMaster aCurrencyMaster ON
vwshopitemshipmentdetail.currencyid = aCurrencyMaster.CurrencyID
INNER JOIN aShopItemDetail aShopItemDetail ON
vwshopitemshipmentdetail.shopid = aShopItemDetail.ShopID AND
vwshopitemshipmentdetail.itemid = aShopItemDetail.ItemID
LEFT OUTER  JOIN vwInquiryShopStock vwInquiryShopStock ON
vwshopitemshipmentdetail.shopid = vwInquiryShopStock.shopid AND
vwshopitemshipmentdetail.itemid = vwInquiryShopStock.itemid
LEFT OUTER JOIN VwItemSalesGrouped VwItemSalesGrouped ON
vwshopitemshipmentdetail.itemid = VwItemSalesGrouped.ItemID AND
vwshopitemshipmentdetail.shopid = VwItemSalesGrouped.ShopID AND
VwItemSalesGrouped.soldDate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''
INNER JOIN vwShopItemStockitemsItemDtls vwShopItemStockitemsItemDtls ON
vwshopitemshipmentdetail.itemid = vwShopItemStockitemsItemDtls.ItemID AND
vwshopitemshipmentdetail.packingtypeid = vwShopItemStockitemsItemDtls.packingtypeid
INNER JOIN aItemCategory aItemCategory ON
vwShopItemStockitemsItemDtls.ItemCategoryID = aItemCategory.ItemCategoryID
LEFT OUTER JOIN aSize aSize ON
vwShopItemStockitemsItemDtls.SizeID = aSize.SizeID
LEFT OUTER JOIN aColor aColor ON
vwShopItemStockitemsItemDtls.ColorID = aColor.ColorID ''
IF @intShopId > 0 --2009-10-23 Yogesh
BEGIN
SET @strSql = @strSql + '' WHERE  aShopItemDetail.ShopID = ''''''+convert(varchar(10),@intShopId)+''''''''
END
SET @strSql = @strSql + '' ORDER BY   aItemCategory.CategoryNameDescription ASC, VwItemSalesGrouped.ItemID ASC''
--print @strSql
exec sp_executesql @strSql' 
END
GO
/****** Object:  StoredProcedure [dbo].[sptemp]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptemp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sptemp    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.sptemp    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.sptemp    Script Date: 31/07/2002 2:00:34 PM ******/
CREATE proc [dbo].[sptemp] as
begin
declare @i  int,@fld varchar(100),
@str as varchar(250)
	create table #temp(nm  varchar(100))
--while(@i<=5)
--begin
set @i=1
set @fld=''a'' + cast(@i as varchar)
set @str=N''alter table #temp add '' + @fld + '' int''
print @str
--sp_executesql @str
--set @i=@i+1
--end
--insert into #temp values(''d'',1)
select * from #temp
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpTotalBinCardAudit]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpTotalBinCardAudit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--insert into aReports values(416,''Total Item Flow'',''TotItmFlow'',1,1,NULL)
--GO
--SpTotalBinCardAudit ''20070101'',''20080101'',0,'''','''',''1,2,3,4,5,6,7,8,9'',''1,2,3,4,5,6,7,8,9,10,11,12,13,15,14''
-- Created by  : Shinu
-- Created on  : 02/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Bincard in the Company
CREATE Procedure [dbo].[SpTotalBinCardAudit] (@strFromDate as varchar(10),@strTodate as varchar(10),@intItemID as int,
	@strCategoryID as varchar(50),@strBrandID as varchar(10),@strShopID as varchar(200),
	@strGodownID as Varchar(200)) As
Begin
	Set Ansi_Warnings Off
	Set Nocount On    Declare @strDateCond as varchar(200)
		Declare @strItemCond as Varchar(200)
		Declare @strCategoryCond as varchar(200)
		Declare @strBrandCond as varchar(200)
		Declare @strSql as nVarchar(4000)
		Declare @strShopCond as Varchar(200)
		Declare @strGodownCond as Varchar(200)
		set @strDateCond= ''''
		set @strItemCond= ''''
		set @strCategoryCond= ''''
		set @strBrandCond= ''''
		set @strShopCond= ''''
		set @strGodownCond= ''''
		set @strDateCond= '' Where sDate Between '''''' + @strFromDate + '''''' And  '''''' + @strTodate + ''''''''
		
		if @intItemID <> 0
			set @strItemCond= '' And TotalBinCardAudit.ItemID= '' + cast(@intItemID as varchar(10))
		
		if @strCategoryID <> ''''
			set @strCategoryCond= '' And ItemCategoryID in ('' + @strCategoryID + '')''
		
		if @strBrandID <> ''''
			set @strBrandCond= '' And Brand =('''''' + @strBrandID + '''''')''
		if @strShopID <> ''''
			set @strShopCond='' Where ShopID in ( '' + @strShopID + '' )''	
		if @strGodownID <> ''''
			set @strGodownCond='' Where GodownID in ( '' + @strGodownID + '' )''
		
		set @strSql=''Select  LocationID,Location,TotalBinCardAudit.ItemID,ItemCode,ItemDescription,ItemCategoryID,Brand,sDate,TransQty,Type,Mode,CostPrice,
			DepCostPrice,ConCostPrice From (
				Select ShopID LocationID,''''S'''' As Location,ItemID,sDate,sum(TransQty)TransQty,Type,Mode,CostPrice,
				DepCostPrice,ConCostPrice From vwshopbincardAudit  '' + @strShopCond  + '' Group By ShopID,ItemID,sDate,Type,Mode,CostPrice,
				DepCostPrice,ConCostPrice
				Union All
				Select GodownID,''''G'''',ItemID,GDate,sum(TransQty)TransQty,Type,Mode,CostPrice,DepCostPrice,ConCostPrice
				From vwgdnbincard '' + @strGodownCond  + '' Group by GodownID,ItemID,GDate,Type,Mode,CostPrice,DepCostPrice,ConCostPrice
			)TotalBinCardAudit Left Outer Join Aitem ai ON ai.ItemID=TotalBinCardAudit.ItemID '' +
			@strDateCond+ @strItemCond + @strCategoryCond + @strBrandCond
		--Print @strSql
		Exec sp_ExecuteSql @strSql
	Set NoCount Off
	Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrderingMonthlyWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockReOrderingMonthlyWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------------
--Created by    :  Shinu
--Created On :  28/03/2008
--Comments      :  Stock ReOrdering
------------------------------------------------------------------------------------------------------------------------
--Modified By   :
--Modified On   :
------------------------------------------------------------------------------------------------------------------------
--spStockReOrderingMonthlyWise 1,'''',''20070502'',''20081231'','''','''','''','''',0,''A'',0
--49  527
--49 549
CREATE Procedure [dbo].[spStockReOrderingMonthlyWise] (@intCompanyID as int ,@strVendorid  as varchar(10),@strStartDate as Varchar(10),
@strEndDate as Varchar(10),@strBrandId as Varchar(100),  @strCategoryID as Varchar(10),
@strShopId as Varchar(10),@strGodownID as varchar(10),@intReorder as int) As
Begin
Set Ansi_Warnings Off
Set Nocount On
--**********************************************************************************************************
-- Temporary Table For Storing Items Details
Create Table #aItem(
ItemID int,
ItemCode varchar(10),
ItemDescription varchar(100),
ItemCategoryID int,
UnitsID int,
Brand varchar(100),
ItemRate numeric(18,2) ,
ReorderQuantity numeric(18,2),
ReorderLevel numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Vedor Items Details
Create Table #TempItem(
VendorId int,
Itemid int,
VendorName varchar(250))
--**********************************************************************************************************
-- Temporary Table For Storing Last Purchased Items Details
Create Table #TempLastPurchase(
lpVendorId int,
lpVendorName varchar(250),
lpBillDate datetime,
lpItemID int,
lpPurchaseQty numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Godown Stock Details
Create Table #vwInquiryGodownStock(
gsItemid int,
GdwnStock numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Shop Stock Details
Create Table #vwInquiryShopStock(
Itemid int,
ShopStock numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Item Sales Details
Create Table #vwItemDetailedSales(
Itemid int,
SoldQty numeric(18,2),
SoldMonth int)
--**********************************************************************************************************
-- Temporary Table For Storing Godown Transation Details
Create Table #vwgdnbincard(
gsGdnItemid int,
gdnQty numeric(18,2))
--**********************************************************************************************************
Declare @strSql As nVarChar(4000)   -- For Storing Dynamic Queries
Declare @strSalesDtCondition as Varchar(100)    -- For From To Dates Sales Condition
Declare @strShopCondition1 as varchar(100)      -- For Shop Condition " Where "
Declare @strShopCondition2 as varchar(100)      -- For Shop Condition " And "
Declare @strShopCondition3 as varchar(100)      -- For Items For Shop Condition
Declare @strGodownCondition as varchar(100)     -- For Godown Condition " Where "
Declare @strGodownCondition1 as varchar(100)    -- For  Items For Godown Condition
Declare @strBrandCondition as varchar(100)      -- For Brand Condition
Declare @strCategoryCondition as Varchar(100)   -- For Category Condition
Declare @strReOrderCondition as Varchar(100)    -- For Reorder Condition
Declare @strLastImportCondition as Varchar(100) -- For Lase Import Condition
Declare @strGodownDtCondition as Varchar(100)   -- For Godown From To Date Condition
Declare @strMovingCondition as varchar(100)  -- For Item Movement Condition
Declare @strTopCondition as varchar(100)        -- For Getting Top Items Condition
--**********************************************************************************************************
-- Setting Initial Values
Set @strSql = ''''
set @strSalesDtCondition = ''''
Set @strShopCondition1 = ''''
Set @strShopCondition2 = ''''
Set @strShopCondition3 = ''''
Set @strGodownCondition = ''''
Set @strGodownCondition1 = ''''
Set @strBrandCondition = ''''
Set @strCategoryCondition = ''''
Set @strReOrderCondition =''''
Set @strLastImportCondition = ''''
Set @strGodownDtCondition = ''''
Set @strMovingCondition = ''''
Set @strTopCondition = ''''
--**********************************************************************************************************
-- Fetching All the Vedors From Table aVendorItem with Vendor Condition if Vendors are selected
If @strVendorid<>''''
Begin
Set @strSql=''Insert  #TempItem  select AV.VendorID,ItemID,VendorName from
aVendorItem AVI,aVendorMaster AV Where AV.vendorID=AVI.VendorID
And AV.VendorID in (''+ @strVendorid +'')''
End
else
Begin
Set @strSql=''Insert  #TempItem  select AV.VendorID,ItemID,VendorName from
aVendorItem AVI,aVendorMaster AV Where AV.vendorID=AVI.VendorID''
End
--Executing Vendors Condition
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
-- Clearing Values
Set @strSql=''''
-- Fetching Last Import Details For an Item
Set @strSql=''Insert  #TempLastPurchase
select pbhVendorID,VendorName,pbhBillDate,pbdItemID,pbdItemQuantity from (
select pbdItemID,pbhVendorID,pbhBillDate,pbdItemQuantity
From lospPurchaseBillHeader,lospPurchaseBillDetail where pbhCancelled=0 And pbhBillID=pbdBillID )A
Inner JOin (select pbdItemID ItemID ,max(pbhBillDate) BillDate from lospPurchaseBillHeader,lospPurchaseBillDetail
where pbhCancelled=0 And pbhBillID=pbdBillID
Group BY pbdItemID)B on B.ItemID=pbdItemID And pbhBillDate=B.BillDate
Left Outer Join aVendorMaster On pbhVendorID=VendorID''
--Executing Last Impoted Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Setting Last Import Condition to the Import Variable
set @strLastImportCondition=''Left Outer Join #TempLastPurchase TLP On TLP.lpItemID = SER.ItemID ''
--**********************************************************************************************************
--Adding Conditions when shops were Selected
If @strShopId <>''''
Begin
Set @strShopCondition1='' Where ShopID in (''+ @strShopId +'')''
Set @strShopCondition2='' And ShopID in (''+ @strShopId +'')''
Set @strShopCondition3='' And ItemID In ( Select ItemID  From aShopItemDetail Where ShopID in (''+ @strShopId +'') )''
End
--**********************************************************************************************************
--Adding Conditions when Godown were Selected
If @strGodownId <>''''
Begin
Set @strGodownCondition='' Where gsGodownID in (''+ @strGodownId +'')''
Set @strGodownCondition1='' And ItemID In ( Select ItemID From aGodownDetail Where GodownID in (''+ @strGodownId +'') )''
End
--**********************************************************************************************************
--Adding Conditions when Brands were Selected
If @strBrandId<>''''
Begin
Set @strBrandCondition='' And Brand in ('' + @strBrandId +'')''
End
--**********************************************************************************************************
--Adding Conditions when Categories were Selected
If @strCategoryID<>''''
Begin
Set @strCategoryCondition='' And ItemCategoryID in ('' + @strCategoryID +'')''
End
--**********************************************************************************************************
--Adding Conditions When Based on Reorder level.If Reorder =1 , will check with Reorder level Other wise with
-- Current Stock
If @intReorder=1
Begin
Set @strReOrderCondition='' And CurStock <= ReorderLevel ''
End
Else
Begin
--Set @strReOrderCondition='' And CurStock <= 0 ''
Set @strReOrderCondition='' ''
End
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Item Details Into Temporary Tables
set @strSql='' insert #aItem Select itemid,ItemCode,ItemDescription,ItemCategoryID,UnitsID,
Brand,ItemRate,ReorderQuantity,ReorderLevel
From aItem  Where Active = 1 '' + @strShopCondition3 + @strGodownCondition1 +
@strCategoryCondition + @strBrandCondition
--Executing Item Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Shop Stock Details
set @strSql='' insert #vwInquiryShopStock Select itemid,Sum(stock) ShopStock From vwInquiryShopStock ''+ @strShopCondition1 +''
Group By itemid ''
--Executing Shop Stock Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Godown Stock Details
set @strSql='' Insert #vwInquiryGodownStock  Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock '' + @strGodownCondition + ''
Group By gsitemid ''
--Executing Godown Stock Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Setting the sales date
Set @strSalesDtCondition = '' And SoldDate >='''''' + @strStartDate + '''' +  '''''' and  SoldDate <=''''''+ @strEndDate + ''''''''
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Godown Transation Qty Details
set @strSql=''Insert #vwgdnbincard select ItemID ,Sum(TransQty*Mode)GdnQty  From vwgdnbincard Where
GDate >='''''' + @strStartDate + '''' +  '''''' and  GDate <=''''''+ @strEndDate + '''''' Group By ItemID ''
-- Setting Codition for Godown Transation Qty Details
Set @strGodownDtCondition='' Left Outer Join #vwgdnbincard ON gsGdnItemid = SER.ItemID ''
--Executing Godown Transation Qty Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Shop Sold Qty Details
set @strSql='' Insert #vwItemDetailedSales Select ItemId,Sum(Qty),month(SoldDate) From vwItemDetailedSales
Where ItemID in ( Select ItemID from #aItem ) '' + @strSalesDtCondition +
@strShopCondition2 + ''Group By ItemId,month(SoldDate) order by month(SoldDate) ''
--Executing Shop Sold Qty Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--- Query For Fetching Details for Monthly Wise Sold In Condition
Set @strSql = ''Select '' + @strTopCondition + ''CompanyID,itemid ,VendorId,VendorName,ItemCode,ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,SoldMonth,ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,
ReorderQuantity,ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,lpVendorID VendorId,lpVendorName VendorName,ser.ItemCode,ser.ItemDescription,
IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,vs.SoldMonth,aic.ItemCategoryID,CategoryNameDescription,
0 ImportedDate,0 pbdItemQuantity,0 pbdItemUnitPrice,
ser.ReorderQuantity,ser.ReorderLevel,lpBillDate,lpPurchaseQty ,gdnQty ,UnitName
From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join  #TempItem av on av.itemid=ser.itemid
Left Outer Join  #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join  #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID From losShopitemShipmentDetail
Group By ItemId,CompanyID) SP On SP.itemid = SER.itemid
Right Outer Join  #vwItemDetailedSales vs on vs.itemid=ser.itemid
'' + @strLastImportCondition + @strGodownDtCondition + ''
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10)) + @strReOrderCondition  + '' Order by SoldMonth '' -- @strMovingCondition
--**********************************************************************************************************
-- Executing The Query For the Selected Condition
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
-- Droping All Temporary tables
Drop Table #TempItem
Drop Table #TempLastPurchase
Drop Table #vwInquiryShopStock
Drop Table #vwInquiryGodownStock
Drop Table #vwItemDetailedSales
Drop Table #vwgdnbincard
Drop Table  #aitem
--**********************************************************************************************************
Set NoCount Off
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrdering]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockReOrdering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------------
--Created by    :  Shinu
--Created On :  28/03/2008
--Comments      :  Stock ReOrdering
------------------------------------------------------------------------------------------------------------------------
--Modified By   :
--Modified On   :
------------------------------------------------------------------------------------------------------------------------
--Sold In
--spStockReOrdering 1,'''',''20080102'',''20081231'','''','''','''','''',''SI'','''','''',''4'',0,''A'',0
--spStockReOrdering 1,'''',''20080102'',''20081231'',''20080402'',''20080407'','''','''',''SI'',''II'','''','''',0,''F'',10
--spStockReOrdering 1,'''',''20080102'',''20081231'',''20080102'',''20081231'','''','''',''SI'',''NII'','''','''',0,''A'',0
--Not Sold In
--spStockReOrdering 1,'''',''20080102'',''20081231'','''','''','''','''',''NSI'','''','''','''',0,''A'',0
--spStockReOrdering 1,'''',''20080102'',''20081231'',''20080102'',''20081231'','''','''',''NSI'',''II'','''','''',0,''A'',0
--spStockReOrdering 1,'''',''20080102'',''20081231'',''20080102'',''20081231'','''','''',''NSI'',''NII'','''','''',0,''A'',0
-- Imported In
--spStockReOrdering 1,'''','''','''',''20080102'',''20081231'','''','''','''',''II'','''','''',0,''A'',0
-- Imported In
--spStockReOrdering 1,'''','''','''',''20080102'',''20081231'','''','''','''',''NII'','''','''',0,''A'',0
--49  527
--49 549
CREATE Procedure [dbo].[spStockReOrdering] (@intCompanyID as int ,@strVendorid  as varchar(10),@strSStartDate as Varchar(10),
@strSEndDate as Varchar(10),@strIStartDate as Varchar(10),@strIEndDate as Varchar(10),@strBrandId as Varchar(100),
@strCategoryID as Varchar(10),@strSType as varchar(10),@strIType as varchar(10),@strShopId as Varchar(10),
@strGodownID as varchar(10),@intReorder as int,@strMoving as varchar(10),@intNoOfItems as int) As
Begin
Set Ansi_Warnings Off
Set Nocount On
--**********************************************************************************************************
-- Temporary Table For Storing Items Details
Create Table #aItem(
ItemID int,
ItemCode varchar(10),
ItemDescription varchar(100),
ItemCategoryID int,
UnitsID int,
Brand varchar(100),
ItemRate numeric(18,2) ,
ReorderQuantity numeric(18,2),
ReorderLevel numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Vedor Items Details
Create Table #TempItem(
VendorId int,
Itemid int,
VendorName varchar(250))
--**********************************************************************************************************
-- Temporary Table For Storing Last Purchased Items Details
Create Table #TempLastPurchase(
lpVendorId int,
lpVendorName varchar(250),
lpBillDate datetime,
lpItemID int,
lpPurchaseQty numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Godown Stock Details
Create Table #vwInquiryGodownStock(
gsItemid int,
GdwnStock numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Shop Stock Details
Create Table #vwInquiryShopStock(
Itemid int,
ShopStock numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Item Sales Details
Create Table #vwItemDetailedSales(
Itemid int,
SoldQty numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing Godown Transation Details
Create Table #vwgdnbincard(
gsGdnItemid int,
gdnQty numeric(18,2))
--**********************************************************************************************************
-- Temporary Table For Storing ImportDetails
Create Table #TempImports(
pbditemid int,
ImportedDate datetime,
pbdItemQuantity numeric(18,2),
pbdItemUnitPrice numeric(18,2),
pbhVendorID int)
--**********************************************************************************************************
Declare @strSql As nVarChar(4000)   -- For Storing Dynamic Queries
Declare @strImportDtCondition as Varchar(100)   -- For From To Dates Import Condition
Declare @strSalesDtCondition as Varchar(100)    -- For From To Dates Sales Condition
Declare @strShopCondition1 as varchar(100)      -- For Shop Condition " Where "
Declare @strShopCondition2 as varchar(100)      -- For Shop Condition " And "
Declare @strShopCondition3 as varchar(100)      -- For Items For Shop Condition
Declare @strGodownCondition as varchar(100)     -- For Godown Condition " Where "
Declare @strGodownCondition1 as varchar(100)    -- For  Items For Godown Condition
Declare @strGodownCondition2 as varchar(100)    -- For  Items For Godown Condition
Declare @strGodownCondition3 as varchar(100)    -- For  Items For Godown Condition
Declare @strBrandCondition as varchar(100)      -- For Brand Condition
Declare @strCategoryCondition as Varchar(100)   -- For Category Condition
Declare @strReOrderCondition as Varchar(100)    -- For Reorder Condition
Declare @strLastImportCondition as Varchar(100) -- For Lase Import Condition
Declare @strGodownDtCondition as Varchar(100)   -- For Godown From To Date Condition
Declare @strMovingCondition as varchar(100)  -- For Item Movement Condition
Declare @strTopCondition as varchar(100)        -- For Getting Top Items Condition
Declare @strImportCondition as varchar(100)   -- For Imports Condition
--**********************************************************************************************************
-- Setting Initial Values
Set @strSql = ''''
Set @strImportDtCondition = ''''
set @strSalesDtCondition = ''''
Set @strShopCondition1 = ''''
Set @strShopCondition2 = ''''
Set @strShopCondition3 = ''''
Set @strGodownCondition = ''''
Set @strGodownCondition1 = ''''
Set @strGodownCondition2 = ''''
Set @strGodownCondition3 = ''''
Set @strBrandCondition = ''''
Set @strCategoryCondition = ''''
Set @strReOrderCondition =''''
Set @strLastImportCondition = ''''
Set @strGodownDtCondition = ''''
Set @strMovingCondition = ''''
Set @strTopCondition = ''''
Set @strImportCondition=''''
--**********************************************************************************************************
-- Fetching All the Vedors From Table aVendorItem with Vendor Condition if Vendors are selected
If @strVendorid<>''''
Begin
Set @strSql=''Insert  #TempItem  select AV.VendorID,ItemID,VendorName from
aVendorItem AVI,aVendorMaster AV Where AV.vendorID=AVI.VendorID
And AV.VendorID in (''+ @strVendorid +'')''
End
else
Begin
Set @strSql=''Insert  #TempItem  select 0,ItemID,null from aItem  ''
End
--Executing Vendors Condition
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
-- Clearing Values
Set @strSql=''''
-- Fetching Last Import Details For an Item
Set @strSql=''Insert  #TempLastPurchase
select pbhVendorID,VendorName,pbhBillDate,pbdItemID,pbdItemQuantity from (
select pbdItemID,pbhVendorID,pbhBillDate,pbdItemQuantity
From lospPurchaseBillHeader,lospPurchaseBillDetail where pbhCancelled=0 And pbhBillID=pbdBillID )A
Inner JOin (select pbdItemID ItemID ,max(pbhBillDate) BillDate from lospPurchaseBillHeader,lospPurchaseBillDetail
where pbhCancelled=0 And pbhBillID=pbdBillID
Group BY pbdItemID)B on B.ItemID=pbdItemID And pbhBillDate=B.BillDate
Left Outer Join aVendorMaster On pbhVendorID=VendorID''
--Executing Last Impoted Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Setting Last Import Condition to the Import Variable
set @strLastImportCondition=''Left Outer Join #TempLastPurchase TLP On TLP.lpItemID = SER.ItemID ''
--**********************************************************************************************************
--Adding Conditions when shops were Selected
If @strShopId <>''''
Begin
Set @strShopCondition1='' Where ShopID in (''+ @strShopId +'')''
Set @strShopCondition2='' And ShopID in (''+ @strShopId +'')''
Set @strShopCondition3='' And ItemID In ( Select ItemID  From aShopItemDetail Where ShopID in (''+ @strShopId +'') )''
End
--**********************************************************************************************************
--Adding Conditions when Godown were Selected
If @strGodownId <>''''
Begin
Set @strGodownCondition = '' Where gsGodownID in (''+ @strGodownId +'')''
Set @strGodownCondition1 = '' And ItemID In ( Select ItemID From aGodownDetail Where GodownID in (''+ @strGodownId +'') )''
Set @strGodownCondition2 = '' And GodownID in (''+ @strGodownId +'')''
Set @strGodownCondition3 = '' Where GodownID in (''+ @strGodownId +'')''
End
--**********************************************************************************************************
--Adding Conditions when Brands were Selected
If @strBrandId<>''''
Begin
Set @strBrandCondition='' And Brand in ('' + @strBrandId +'')''
End
--**********************************************************************************************************
--Adding Conditions when Categories were Selected
If @strCategoryID<>''''          	
Begin
if @strGodownId <>''''
begin
	set @strGodownCondition1=''''
	Set @strGodownCondition1 = '' And ItemID In ( Select ItemID From aGodownDetail Where itemid in (
	select itemid from aitem where ItemCategoryID in ('' + @strCategoryID +'')) and  godownid  in (''+ @strGodownId +'')) ''
end
Set @strCategoryCondition='' And ItemCategoryID in ('' + @strCategoryID +'')''
End
--**********************************************************************************************************
--Adding Conditions When Based on Reorder level.If Reorder =1 , will check with Reorder level Other wise with
-- Current Stock
If @intReorder=1
Begin
Set @strReOrderCondition='' And CurStock <= ReorderLevel ''
End
Else
Begin
--Set @strReOrderCondition='' And CurStock <= 0 ''
Set @strReOrderCondition='' ''
End
--**********************************************************************************************************
-- Addinf Conditions for Fast (F), Slow(S) and All
if @strMoving=''F''
Begin
set @strMovingCondition= '' Order by SoldQty desc ''
End
Else if @strMoving=''S''
Begin
set @strMovingCondition= '' Order by SoldQty asc ''
End
--**********************************************************************************************************
-- For Settings Max No of Items
If @intNoOfItems>0
Begin
set @strTopCondition= ''top '' + cast(@intNoOfItems as varchar(10))
End
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Item Details Into Temporary Tables
set @strSql='' insert #aItem Select itemid,ItemCode,ItemDescription,ItemCategoryID,UnitsID,
Brand,ItemRate,ReorderQuantity,ReorderLevel
From aItem  Where Active = 1 '' + @strShopCondition3 + @strGodownCondition1 +
@strCategoryCondition + @strBrandCondition
--Executing Item Details
print @strSql
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Shop Stock Details
set @strSql='' insert #vwInquiryShopStock Select itemid,Sum(stock) ShopStock From vwInquiryShopStock ''+ @strShopCondition1 +''
Group By itemid ''
--Executing Shop Stock Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Godown Stock Details
set @strSql='' Insert #vwInquiryGodownStock  Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock '' + @strGodownCondition + ''
Group By gsitemid ''
--Executing Godown Stock Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Setting the purchase date
If @strIType<>''''
Begin
Set @strImportDtCondition = '' And PbhbillDate >='''''' + @strIStartDate + '''' +  '''''' and  PbhbillDate<=''''''+ @strIEndDate + ''''''''
End
--**********************************************************************************************************
--Setting the sales date
If @strSType<>''''
Begin
Set @strSalesDtCondition = '' And SoldDate >='''''' + @strSStartDate + '''' +  '''''' and  SoldDate <=''''''+ @strSEndDate + ''''''''
End
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Godown Transation Qty Details
if @strSType<>''''
set @strSql=''Insert #vwgdnbincard select ItemID ,Sum(TransQty*Mode)GdnQty  From vwgdnbincard Where
GDate >='''''' + @strSStartDate + '''' +  '''''' and  GDate <=''''''+ @strSEndDate + '''''''' + @strGodownCondition2 + ''Group By ItemID ''
Else
set @strSql=''Insert #vwgdnbincard select ItemID ,Sum(TransQty*Mode)GdnQty  From vwgdnbincard '' + @strGodownCondition3 + '' Group By ItemID ''
-- Setting Codition for Godown Transation Qty Details
Set @strGodownDtCondition='' Left Outer Join #vwgdnbincard ON gsGdnItemid = SER.ItemID ''
--Executing Godown Transation Qty Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Shop Sold Qty Details
set @strSql='' Insert #vwItemDetailedSales Select ItemId,Sum(Qty) From vwItemDetailedSales
Where ItemID in ( Select ItemID from #aItem ) '' + @strSalesDtCondition +
@strShopCondition2 + ''Group By ItemId''
--Executing Shop Sold Qty Details
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
--Clearing Values
Set @strSql=''''
--Inserting Imported Details
set @strSql =''Insert #TempImports Select pbditemid,max(pbhBilldate)ImportedDate,
Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
From lospPurchaseBillheader h,lospPurchaseBilldetail d
Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0 '' + @strImportDtCondition + ''
Group  By pbditemid,pbhVendorID,pbdItemUnitPrice''
--Executing Shop Sold Qty Details
print @strSql
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
if @strIType=''II''
Set @strImportCondition='' Right Outer Join #TempImports a On a.pbditemid=ser.itemid ''
else if @strIType=''NII''
Set @strImportCondition='' Where Ser.ItemID Not In (Select distinct(pbditemid) From  #TempImports)''
else
Set @strImportCondition=''''
--**********************************************************************************************************
--- Query For Fetching Details for Sold In Condition
If @strSType=''SI''
Begin
Set @strSql = ''Select '' + @strTopCondition + ''CompanyID,itemid ,VendorId,VendorName,ItemCode,
ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,
ReorderQuantity,ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,VendorId,VendorName,ser.ItemCode,ser.ItemDescription,
IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,aic.ItemCategoryID,CategoryNameDescription,
0 ImportedDate,0 pbdItemQuantity,0 pbdItemUnitPrice,
ser.ReorderQuantity,ser.ReorderLevel,lpBillDate,lpPurchaseQty ,gdnQty ,UnitName
From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join #TempItem av on av.itemid=ser.itemid
Left Outer Join #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID
From losShopitemShipmentDetail Group By ItemId,CompanyID) SP On SP.itemid = SER.itemid
Right Outer Join  #vwItemDetailedSales vs on vs.itemid=ser.itemid
'' + @strLastImportCondition +
@strGodownDtCondition +
@strImportCondition + ''
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10)) + @strReOrderCondition + @strMovingCondition
End
--**********************************************************************************************************
--- Query For Fetching Details for Not Sold In Condition
if @strSType <>''''
Begin  --1
If @strSType=''NSI''
Begin  --2
If  @strIType=''NII''
Begin  --3
Set @strSql = ''Select CompanyID,itemid ,VendorId,VendorName,ItemCode,ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,ReorderQuantity,ReorderLevel,
lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,VendorId,VendorName,ser.ItemCode,
ser.ItemDescription,IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,0 SoldQty,aic.ItemCategoryID,CategoryNameDescription,
0 ImportedDate,0 pbdItemQuantity,0 pbdItemUnitPrice,
ser.ReorderQuantity,ser.ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName
From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join #TempItem av on av.itemid=ser.itemid
Left Outer Join #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID
From losShopitemShipmentDetail Group By ItemId,CompanyID) SP
On SP.itemid = SER.itemid
'' + @strLastImportCondition + @strGodownDtCondition + @strImportCondition + ''
And ser.Itemid not in (Select ItemId From #vwItemDetailedSales)
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10)) +  @strReOrderCondition
End --3
Else
Begin --4
Set @strSql = ''Select CompanyID,itemid ,VendorId,VendorName,ItemCode,ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,ReorderQuantity,ReorderLevel,
lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,VendorId,VendorName,ser.ItemCode,
ser.ItemDescription,IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,0 SoldQty,aic.ItemCategoryID,CategoryNameDescription,
0 ImportedDate,0 pbdItemQuantity,0 pbdItemUnitPrice,
ser.ReorderQuantity,ser.ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName
From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join #TempItem av on av.itemid=ser.itemid
Left Outer Join #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID
From losShopitemShipmentDetail Group By ItemId,CompanyID) SP
On SP.itemid = SER.itemid
'' + @strLastImportCondition + @strGodownDtCondition + @strImportCondition + ''
where ser.Itemid not in (Select ItemId From #vwItemDetailedSales)
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10)) +  @strReOrderCondition
End --4
End --2
End --1
Else
Begin --1
--**********************************************************************************************************
--- Query For Fetching Details for Imported In Condition
If @strIType=''II''
Begin  --2
Set @strSql = ''Select CompanyID,itemid ,VendorId,VendorName,ItemCode,ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,ItemCategoryID,CategoryNameDescription,ImportedDate,
pbdItemQuantity,pbdItemUnitPrice,ReorderQuantity,ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,VendorId,VendorName,ser.ItemCode,ser.ItemDescription,
IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,SoldQty,aic.ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,ser.ReorderQuantity,ser.ReorderLevel,
lpBillDate,lpPurchaseQty,gdnQty,UnitName From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join #TempItem av on av.itemid=ser.itemid
Left Outer Join #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID From
losShopitemShipmentDetail Group By ItemId,CompanyID) SP On SP.itemid = SER.itemid
Left Outer Join #vwItemDetailedSales vs on vs.itemid=ser.itemid ''
+ @strImportCondition + @strLastImportCondition + @strGodownDtCondition + ''
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10))  + @strReOrderCondition
End  --2
--**********************************************************************************************************
--- Query For Fetching Details for Not Imported In Condition
If @strIType=''NII''
Begin --3
Set @strSql = ''Select CompanyID,itemid ,VendorId,VendorName,ItemCode,ItemDescription,ShopStock,GdnStock,CurStock,
brand,itemrate,sellingprice,SoldQty,ItemCategoryID,CategoryNameDescription,
ImportedDate,pbdItemQuantity,pbdItemUnitPrice,ReorderQuantity,ReorderLevel,
lpBillDate,lpPurchaseQty,gdnQty,UnitName From
(Select Distinct(ser.itemid),SP.CompanyID,VendorId,VendorName,ser.ItemCode,ser.ItemDescription,
IsNull(SStk.ShopStock,0) + IsNull(GStk.GdwnStock,0)CurStock,
IsNull(SStk.ShopStock,0) ShopStock,IsNull(GStk.GdwnStock,0) GdnStock,
ser.brand,ser.itemrate,sp.sellingprice,SoldQty,aic.ItemCategoryID,CategoryNameDescription,
0 ImportedDate,0 pbdItemQuantity,0 pbdItemUnitPrice,
ser.ReorderQuantity,ser.ReorderLevel,lpBillDate,lpPurchaseQty,gdnQty,UnitName
From #aitem ser
Left Outer Join aUnit On UnitsID=UnitID
Left Outer Join aItemCategory aic ON ser.ItemCategoryID=aic.ItemCategoryID
Inner Join #TempItem av on av.itemid=ser.itemid
Left Outer Join #vwInquiryShopStock SStk On SStk.itemid=SER.itemid
Left Outer Join #vwInquiryGodownStock GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice,CompanyID From
losShopitemShipmentDetail Group By ItemId,CompanyID) SP On SP.itemid = SER.itemid
Left Outer Join #vwItemDetailedSales vs on vs.itemid=ser.itemid
'' + @strLastImportCondition + @strGodownDtCondition + @strImportCondition +''
)Reorder
Where CompanyID= '' + cast(@intCompanyID as varchar(10)) + @strReOrderCondition
End --3
End --1
--**********************************************************************************************************
Print @strSql
-- Executing The Query For the Selected Condition
Exec sp_ExecuteSql @strSql
--**********************************************************************************************************
-- Droping All Temporary tables
Drop Table #TempItem
Drop Table #TempLastPurchase
Drop Table #vwInquiryShopStock
Drop Table #vwInquiryGodownStock
Drop Table #vwItemDetailedSales
Drop Table #vwgdnbincard
Drop Table  #aitem
--**********************************************************************************************************
Set NoCount Off
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockOrderingOld]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrderingOld]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by    :  Vidya
--Comments      :  Stock Analysis
--Modified By   :  Aneesh [ Rewritten & Added conditions ]
--		:  Aneesh [ Added new Parameters ]
---------------------------------------------------------------------------------------------------
--spStockOrdering 28,0,0,''20040101'',''20050101'','''',0,3087
CREATE Procedure [dbo].[spStockOrderingOld] (@intCountryid as int,@Vendorid  as int,  @intItemId as int,
@strStartDate as Varchar(10), @strEndDate as Varchar(10), @strSearchCondition as Varchar(100),
@intBrandId as int,  @intSizeId as int ) As
Begin
	Set Ansi_Warnings Off
	Set Nocount On
	Create Table #TempVendorCom(
	CountryId int,
	VendorId int,
	VendorName varchar(500),
	CountryName varchar(500))
	Create Table #TempItem(
	Itemid int,
	VendorId int,
	VendorName varchar(250))
	
	Declare @strSql As nVarChar(2000)
	Declare @strImportDtCondition as Varchar(100)
	Declare @strSalesDtCondition as Varchar(100)
	
	--Variables declared for cursor
	Declare @tVendorId as int
	Declare @tVendorName as varchar(500)
	Declare @tempVendorId as varchar(250)
Declare @strCondition as nvarchar(2000)
	If @intCountryid > 0
		Begin
			If @Vendorid=0
				Begin
					Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
					VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
					v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar)
				End
			Else
				
				Begin 					
					Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
					VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
					v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar) +
					'' And v.VendorID='' + cast(@Vendorid as varchar)
		End
		End          	
	
	Else	
		Begin
			If @Vendorid=0
				Begin
					Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
					VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
					v.CountryId=c.CountryId''
				End
			Else
				
				Begin 					
					Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
					VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
					v.CountryId=c.CountryId And v.VendorID='' + cast(@Vendorid as varchar)
		End
		End
			
	Exec sp_ExecuteSql @strSql
	
	-- Inserting to #TempItem itemid, Vendorid and vendorname
		
	Declare CurVen Cursor  For Select vendorid ,VendorName From #TempVendorCom
	Open CurVen
		Fetch Next From CurVen InTo @tVendorId ,@tVendorName
		Set @tempVendorId=''''
		While @@Fetch_status = 0
			Begin
				Set @tempVendorId= '''''''' + ''%,'' + convert(varchar(250),@tVendorId) + '',%'' + ''''''''
				Set @tVendorName='''''''' + @tVendorName + ''''''''
				Set @strSql=''Insert  #TempItem  select itemid,'' + convert(varchar,@tVendorId) + '',
				'' + @tVendorName + '' from aitem where vendors like  '' + @tempVendorId
				
				Exec sp_ExecuteSql @strSql
				
				Fetch Next From CurVen InTo @tVendorId ,@tVendorName
			End
	Close CurVen
Deallocate CurVen
	
	Set @strSql=''''
If @VendorId > 0 And @intCountryid>0 And @intItemId>0
		Begin
			--Print ''AA''
			Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '''' +
			'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '''' +
			'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
		End
	If @VendorId > 0 And @intCountryid>0 And @intItemId=0  			
		Begin
			--Print ''AB''
			Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
			'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid) + '')'' + '' av ''
		End
	If @VendorId > 0 And @intCountryid=0 And @intItemId>0  			
		Begin
			--Print ''AC''
			Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
			'' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
		End
	If @VendorId > 0 And @intCountryid=0 And @intItemId=0
		Begin
			--Print ''AD''
			Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '')'' + '' av ''
		End
	If @VendorId = 0 And @intCountryid>0 And @intItemId>0
		Begin
			--Print ''BA''
			Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '''' +
			'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
		End
	If @VendorId = 0 And @intCountryid>0 And @intItemId=0
		Begin
			--Print ''BB''
			Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
		End
	If @VendorId = 0 And @intCountryid=0 And @intItemId>0
		Begin
			--Print ''BC''
			Set @strCondition ='' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
		End
	If @VendorId = 0 And @intCountryid=0 And @intItemId=0
		Begin
			--Print ''BD''
			Set @strCondition =''''
		End
		
		
		--If any Item search condition is passed....
		If @strSearchCondition<>''''
			Set @strSearchCondition='' and ser.SearchDescription like '' + '''''''' + @strSearchCondition + ''''''''
		--If Brand id is passed
		If @intBrandId<>0
			Set @strSearchCondition = @strSearchCondition + '' and ser.BrandId ='' + CONVERT(Varchar(20), @intBrandId) + ''''
		
		--If Size id is passed
		If @intSizeId<>0
			Set @strSearchCondition = @strSearchCondition + '' and ser.SizeId ='' + CONVERT(Varchar(20), @intSizeId) + ''''
		
		--Setting the purchase date
		Set @strImportDtCondition = '' And PbhbillDate >='''''' + @strStartDate + '''' +  '''''' and  PbhbillDate<=''''''+ @strEndDate + ''''''''
		--Setting the sales date
		Set @strSalesDtCondition = '' Where SoldDate >='''''' + @strStartDate + '''' +  '''''' and  SoldDate <=''''''+ @strEndDate + ''''''''
		
		
		If @strCondition<>''''
			Set @strSql = ''Select Distinct(ser.itemid),VendorId,VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
			ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
			From vwItemSearching ser Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
			Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid '' + @strCondition + '' on av.itemid=ser.itemid '' + @strSearchCondition + ''
			Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
			Group By itemid) SStk On SStk.itemid=SER.itemid
			Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock			
			Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
			Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From vwSellingFixAtHq Group By ItemId) SP On SP.itemid = SER.itemid
			Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
			Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
			Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
			From lospPurchaseBillheader h,lospPurchaseBilldetail d
			Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + ''
			Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
			a.pbditemid=ser.itemid''
		Else
			Set @strSql = ''Select Distinct(ser.itemid),VendorId,VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
			ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
			From vwItemSearching ser Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
			Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid) av on av.itemid=ser.itemid '' +  @strSearchCondition + ''
			Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
			Group By itemid) SStk On SStk.itemid=SER.itemid
			Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock			
			Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
			Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From vwSellingFixAtHq Group By ItemId) SP On SP.itemid = SER.itemid
			Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales  '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
			Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
			Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
			From lospPurchaseBillheader h,lospPurchaseBilldetail d
			Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + ''
			Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
			a.pbditemid=ser.itemid''
		           		
	Exec sp_ExecuteSql @strSql                		
	Set NoCount Off
	Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering1]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrdering1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------------
--Created by    :  Vidya
--Comments      :  Stock Analysis
--Modified By   :  Aneesh [ Rewritten & Added conditions ]
--  :  Aneesh [ Added new Parameters ]
---------------------------------------------------------------------------------------------------
--spStockOrdering 0,0,0,''20040101'',''20080101'','''',0,0
CREATE Procedure [dbo].[spStockOrdering1] (@intCountryid as int,@Vendorid  as int,  @intItemId as int,
@strStartDate as Varchar(10), @strEndDate as Varchar(10), @strSearchCondition as Varchar(100),
@intBrandId as int,  @intSizeId as int ) As
Begin
Set Ansi_Warnings Off
Set Nocount On
Create Table #TempVendorCom(
CountryId int,
VendorId int,
VendorName varchar(500),
CountryName varchar(500))
Create Table #TempItem(
Itemid int,
VendorId int,
VendorName varchar(250))
Declare @strSql As nVarChar(2000)
Declare @strImportDtCondition as Varchar(100)
Declare @strSalesDtCondition as Varchar(100)
--Variables declared for cursor
Declare @tVendorId as int
Declare @tVendorName as varchar(500)
Declare @tempVendorId as varchar(250)
Declare @strCondition as nvarchar(2000)
If @intCountryid > 0
Begin
If @Vendorid=0
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar)
End
Else
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar) +
'' And v.VendorID='' + cast(@Vendorid as varchar)
End
End
Else
Begin
If @Vendorid=0
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId''
End
Else
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.VendorID='' + cast(@Vendorid as varchar)
End
End
Exec sp_ExecuteSql @strSql
-- Inserting to #TempItem itemid, Vendorid and vendorname
Declare CurVen Cursor  For Select vendorid ,VendorName From #TempVendorCom
Open CurVen
Fetch Next From CurVen InTo @tVendorId ,@tVendorName
Set @tempVendorId=''''
While @@Fetch_status = 0
Begin
Set @tempVendorId= '''''''' + ''%,'' + convert(varchar(250),@tVendorId) + '',%'' + ''''''''
Set @tVendorName='''''''' + Replace(@tvendorname, '''''''', '''''''''''') + ''''''''
Set @strSql=''Insert  #TempItem  select itemid,'' + convert(varchar,@tVendorId) + '',
'' + @tVendorName + '' from aitem ''--where vendors like  '' + @tempVendorId
Exec sp_ExecuteSql @strSql
Fetch Next From CurVen InTo @tVendorId ,@tVendorName
End
Close CurVen
Deallocate CurVen
Set @strSql=''''
If @VendorId > 0 And @intCountryid>0 And @intItemId>0
Begin
--Print ''AA''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '''' +
'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '''' +
'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid>0 And @intItemId=0
Begin
--Print ''AB''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid) + '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid=0 And @intItemId>0
Begin
--Print ''AC''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
'' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid=0 And @intItemId=0
Begin
--Print ''AD''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid>0 And @intItemId>0
Begin
--Print ''BA''
Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '''' +
'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid>0 And @intItemId=0
Begin
--Print ''BB''
Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid=0 And @intItemId>0
Begin
--Print ''BC''
Set @strCondition ='' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid=0 And @intItemId=0
Begin
--Print ''BD''
Set @strCondition =''''
End
--If any Item search condition is passed....
If @strSearchCondition<>''''
Set @strSearchCondition='' and ser.SearchDescription like '' + '''''''' + @strSearchCondition + ''''''''
--If Brand id is passed
If @intBrandId<>0
Set @strSearchCondition = @strSearchCondition + '' and ser.BrandId ='' + CONVERT(Varchar(20), @intBrandId) + ''''
--If Size id is passed
If @intSizeId<>0
Set @strSearchCondition = @strSearchCondition + '' and ser.SizeId ='' + CONVERT(Varchar(20), @intSizeId) + ''''
--Setting the purchase date
Set @strImportDtCondition = '' And PbhbillDate >='''''' + @strStartDate + '''' +  '''''' and  PbhbillDate<=''''''+ @strEndDate + ''''''''
--Setting the sales date
Set @strSalesDtCondition = '' Where SoldDate >='''''' + @strStartDate + '''' +  '''''' and  SoldDate <=''''''+ @strEndDate + ''''''''
If @strCondition<>''''
Set @strSql = ''Select Distinct(ser.itemid),VendorId,VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
From vwItemSearching ser Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid '' + @strCondition + '' on av.itemid=ser.itemid '' + @strSearchCondition + ''
Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
Group By itemid) SStk On SStk.itemid=SER.itemid
Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock
Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From losShopitemShipmentDetail Group By ItemId) SP On SP.itemid = SER.itemid
Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
From lospPurchaseBillheader h,lospPurchaseBilldetail d
Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + '' and  pbhBilldate is not null
Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
a.pbditemid=ser.itemid and a.pbhvendorid=ser.vendorid''
Else
Set @strSql = ''Select Distinct(ser.itemid),a.pbhVendorId,a.VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
From vwItemSearching ser
/* Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid) av on av.itemid=ser.itemid '' +  @strSearchCondition + ''   */
Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
	 Group By itemid) SStk On SStk.itemid=SER.itemid
Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock
	Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From losShopitemShipmentDetail Group By ItemId) SP On SP.itemid = SER.itemid
Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales  '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
	Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID,av.Vendorname
	 From lospPurchaseBillheader h,lospPurchaseBilldetail d,avendormaster av
	Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + '' and  pbhBilldate is not null
	and av.VendorID=pbh.vendorID
	Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
	a.pbditemid=ser.itemid''
--print @strSql
Exec sp_ExecuteSql @strSql
Set NoCount Off
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOrdering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------------
--Created by    :  Vidya
--Comments      :  Stock Analysis
--Modified By   :  Aneesh [ Rewritten & Added conditions ]
--  :  Aneesh [ Added new Parameters ]
---------------------------------------------------------------------------------------------------
--spStockOrdering 0,0,0,''20040101'',''20080101'','''',0,0
CREATE Procedure [dbo].[spStockOrdering] (@intCountryid as int,@Vendorid  as int,  @intItemId as int,
@strStartDate as Varchar(10), @strEndDate as Varchar(10), @strSearchCondition as Varchar(100),
@intBrandId as int,  @intSizeId as int ) As
Begin
Set Ansi_Warnings Off
Set Nocount On
Create Table #TempVendorCom(
CountryId int,
VendorId int,
VendorName varchar(500),
CountryName varchar(500))
Create Table #TempItem(
Itemid int,
VendorId int,
VendorName varchar(250))
Declare @strSql As nVarChar(2000)
Declare @strImportDtCondition as Varchar(100)
Declare @strSalesDtCondition as Varchar(100)
--Variables declared for cursor
Declare @tVendorId as int
Declare @tVendorName as varchar(500)
Declare @tempVendorId as varchar(250)
Declare @strCondition as nvarchar(2000)
If @intCountryid > 0
Begin
If @Vendorid=0
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar)
End
Else
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.CountryId='' + cast(@intCountryid as varchar) +
'' And v.VendorID='' + cast(@Vendorid as varchar)
End
End
Else
Begin
If @Vendorid=0
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId''
End
Else
Begin
Set @strSql='' Insert #TempVendorCom select c.countryId ,vendorId,
VendorName,CountryName From avendorMaster  v, aCountryMaster c Where
v.CountryId=c.CountryId And v.VendorID='' + cast(@Vendorid as varchar)
End
End
Exec sp_ExecuteSql @strSql
-- Inserting to #TempItem itemid, Vendorid and vendorname
Declare CurVen Cursor  For Select vendorid ,VendorName From #TempVendorCom
Open CurVen
Fetch Next From CurVen InTo @tVendorId ,@tVendorName
Set @tempVendorId=''''
While @@Fetch_status = 0
Begin
Set @tempVendorId= '''''''' + ''%,'' + convert(varchar(250),@tVendorId) + '',%'' + ''''''''
Set @tVendorName='''''''' + Replace(@tvendorname, '''''''', '''''''''''') + ''''''''
Set @strSql=''Insert  #TempItem  select itemid,'' + convert(varchar,@tVendorId) + '',
'' + @tVendorName + '' from aitem where vendors like  '' + @tempVendorId
Exec sp_ExecuteSql @strSql
Fetch Next From CurVen InTo @tVendorId ,@tVendorName
End
Close CurVen
Deallocate CurVen
Set @strSql=''''
If @VendorId > 0 And @intCountryid>0 And @intItemId>0
Begin
--Print ''AA''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '''' +
'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '''' +
'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid>0 And @intItemId=0
Begin
--Print ''AB''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
'' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid) + '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid=0 And @intItemId>0
Begin
--Print ''AC''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId) + '''' +
'' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId > 0 And @intCountryid=0 And @intItemId=0
Begin
--Print ''AD''
Set @strCondition ='' and tcom.vendorid='' + CONVERT(Varchar(9), @VendorId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid>0 And @intItemId>0
Begin
--Print ''BA''
Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '''' +
'' and tmp.Itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid>0 And @intItemId=0
Begin
--Print ''BB''
Set @strCondition ='' and tcom.countryid='' + CONVERT(Varchar(9), @intCountryid)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid=0 And @intItemId>0
Begin
--Print ''BC''
Set @strCondition ='' and tmp.itemid='' + CONVERT(Varchar(9), @intItemId)+ '')'' + '' av ''
End
If @VendorId = 0 And @intCountryid=0 And @intItemId=0
Begin
--Print ''BD''
Set @strCondition =''''
End
--If any Item search condition is passed....
If @strSearchCondition<>''''
Set @strSearchCondition='' and ser.SearchDescription like '' + '''''''' + @strSearchCondition + ''''''''
--If Brand id is passed
If @intBrandId<>0
Set @strSearchCondition = @strSearchCondition + '' and ser.BrandId ='' + CONVERT(Varchar(20), @intBrandId) + ''''
--If Size id is passed
If @intSizeId<>0
Set @strSearchCondition = @strSearchCondition + '' and ser.SizeId ='' + CONVERT(Varchar(20), @intSizeId) + ''''
--Setting the purchase date
Set @strImportDtCondition = '' And PbhbillDate >='''''' + @strStartDate + '''' +  '''''' and  PbhbillDate<=''''''+ @strEndDate + ''''''''
--Setting the sales date
Set @strSalesDtCondition = '' Where SoldDate >='''''' + @strStartDate + '''' +  '''''' and  SoldDate <=''''''+ @strEndDate + ''''''''
If @strCondition<>''''
Set @strSql = ''Select Distinct(ser.itemid),VendorId,VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
From vwItemSearching ser Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid '' + @strCondition + '' on av.itemid=ser.itemid '' + @strSearchCondition + ''
Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
Group By itemid) SStk On SStk.itemid=SER.itemid
Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock
Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From losShopitemShipmentDetail Group By ItemId) SP On SP.itemid = SER.itemid
Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
From lospPurchaseBillheader h,lospPurchaseBilldetail d
Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + ''
Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
a.pbditemid=ser.itemid''
Else
Set @strSql = ''Select Distinct(ser.itemid),VendorId,VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
From vwItemSearching ser Inner Join (Select tcom.VendorId,tcom.VendorName,tmp.Itemid  From  #TempItem tmp
Inner Join  #TempVendorCom tcom on tcom.vendorid=tmp.vendorid) av on av.itemid=ser.itemid '' +  @strSearchCondition + ''
Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
Group By itemid) SStk On SStk.itemid=SER.itemid
Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock
Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From losShopitemShipmentDetail Group By ItemId) SP On SP.itemid = SER.itemid
Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales  '' + @strSalesDtCondition + '' Group By ItemId) vs on vs.itemid=ser.itemid
Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID
From lospPurchaseBillheader h,lospPurchaseBilldetail d
Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  '' + @strImportDtCondition + ''
Group  By pbditemid,pbhVendorID,pbdItemUnitPrice) a On
a.pbditemid=ser.itemid''
--print @strSql
Exec sp_ExecuteSql @strSql
Set NoCount Off
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSales]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthWiseProductSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spMonthWiseProductSales ''20090731'',''20090731'',''gg'',''42'',''4'',3
--altered by :Nidheesh
--altered on :05-08-09
--comments   :At first MonthSales inner joins the view vwinquiryshopstock.Evenif there is no opening stock an item
--can be used in the case of special inv.Sometime it may show null values in the report after being done a special inv.
--So its changed to MonthSales left outer join to vwinquiryshopstock
--comments   :changed the size of @strQry
CREATE PROCEDURE [dbo].[spMonthWiseProductSales] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@strBrand as varchar(250),
@strCategoryId as varchar(250),
@strShopId as varchar(250),
@intDepartmentId as int = 0)  AS
Begin
declare @strQry as nvarchar(3000)
set @strQry = N''select MonthSales.MonthName, MonthSales.MonthCode,
MonthSales.YearName, MonthSales.posdItemId,
convert(numeric(18,2),sum(MonthSales.amount))  UnitPrice,
convert(numeric(18,2),sum(MonthSales.damount)) dUnitPrice,
convert(numeric(18,2),sum(MonthSales.camount)) cUnitPrice,
sum(MonthSales.quantity) Quantity,
MonthSales.poshShopId,
a.ItemCode, ltrim(rtrim(left(vw.itemdescription,250))) ItemDescription, a.Brand,
a.ModelNo, a.ItemCategoryId, MonthSales.MonthNo,au.UnitName,isnull(inq.Stock,0) Stock
from
(select datename(month,poshbilldate) monthname,
substring(datename(month,poshbilldate),1,3)
+ ''''-'''' + substring(convert(varchar(4),year(poshbilldate)),3,2) monthcode,
year(poshbilldate) yearname, posditemid, avg(posdunitprice) unitprice,
avg(dunitprice) dunitprice, avg(cunitprice) cunitprice,
sum(posdquantity) quantity, poshShopID, month(poshbilldate) monthno ,
sum(amount)amount,sum(camount)camount,sum(damount)damount
from vwshopitemsales
where poshbilldate >= '''''' + @strfromdate + '''''' and poshbilldate <= ''''''+ @strtodate + ''''''
group by  poshshopid, posditemid, year(poshbilldate), month(poshbilldate), poshbilldate)
MonthSales left outer join vwinquiryshopstock inq on inq.itemid=MonthSales.posditemid and inq.shopid=MonthSales.poshShopID
, aitem a, vwitemdescription vw, aShops,aunit au
where vw.itemid = a.itemid and MonthSales.posditemid = a.itemid
and MonthSales.poshShopId = aShops.ShopId and a.UnitsID=au.UnitId ''
if (ltrim(rtrim(@strbrand)) <> '''')
Begin
set @strQry = @strQry + N'' and a.brand in ('''''' + @strbrand +'''''')''
End
if (ltrim(rtrim(@strcategoryid)) <> '''')
Begin
set @strQry = @strQry + N'' and a.itemcategoryid in('' + @strcategoryid + '')''
End
--/*
if (ltrim(rtrim(@strShopId)) <> '''')
Begin
set @strQry = @strQry + N'' and poshshopid in ( '' + @strShopId + '')''
End
-- */
if @intDepartmentId <> 0
Begin
Set @strQry = @strQry + N'' and aShops.DepartmentId = '' + str(@intDepartmentId)
End
set @strQry = @strQry + N'' group by MonthSales.yearname,
MonthSales.monthno, MonthSales.monthname, MonthSales.monthcode, MonthSales.posditemid,a.itemcode, vw.itemdescription, a.brand,
a.modelno, MonthSales.poshShopID, a.itemcategoryid ,au.UnitName,inq.Stock order by MonthSales.yearname,MonthSales.monthno asc''
--print @strQry
exec sp_executesql @strQry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnoliaReturnExrate]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnoliaReturnExrate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created By: Nidheesh P V
--created no: 20/07/2011
--comments: To get the exchange rate for a given currency.
--used in spl. invoice reports to show the amoun in USD for MRF customers.
--spMagnoliaReturnExrate 1,''2:1:-1:12.85:''
CREATE proc [dbo].[spMagnoliaReturnExrate]
@intCurid  as int,
@strExrates  as varchar(250)
as
begin
set nocount on
declare @intposition as int,
@strcurrenciesonly as varchar(200),
@strexratesonly as varchar(200),
@intcoloncount as int,
@intcounter as int,
@intcolonposition as int,
@numexrate  as numeric(18,8)
--finding the postion of seperator hypen in the string
set @intposition = patindex(''%-%'',@strexrates)
--extracting only the currency string part from main string
set @strcurrenciesonly = ltrim(rtrim(substring(@strexrates,1,@intposition-1)))
--extracting only the exrates string part from main string
set @strexratesonly = ltrim(rtrim(substring(@strexrates,@intposition+1,
len(@strexrates)-@intposition)))
--to find the postion of the currencyid in the currency string
set @intposition = patindex(''%''+ ltrim(rtrim(str(@intcurid))) + '':%'',@strcurrenciesonly)
set @intcounter =1
set @intcoloncount =0
while @intcounter < @intposition
begin
--to find how many colon it has to skip in the exrate string
if substring(@strcurrenciesonly,@intcounter, 1) = '':''
set @intcoloncount = @intcoloncount +1
set @intcounter = @intcounter +1
end
set @intposition =1
set @intcounter
= @intcoloncount
while @intcounter <>  0
begin
--to find how many colon it has to skip in the exrate string
if substring(@strexratesonly,@intposition, 1) = '':''
set @intcounter = @intcounter - 1
set @intposition = @intposition +1
end
-- in @intposition the start of the respective ex rate will be there
set @numexrate = substring(@strexratesonly,@intposition,
charindex('':'',@strexratesonly,@intposition) - @intposition)
set nocount off
select @numexrate as ExRate
end' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetIndexColumnOrder]    Script Date: 10/06/2012 14:17: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].[GetIndexColumnOrder]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- Returns whether the column is ASC or DESC
CREATE FUNCTION [dbo].[GetIndexColumnOrder]
(
@object_id INT,
@index_id TINYINT,
@column_id TINYINT
)
RETURNS NVARCHAR(5)
AS
BEGIN
DECLARE @r NVARCHAR(5)
SELECT @r = CASE INDEXKEY_PROPERTY
(
@object_id,
@index_id,
@column_id,
''IsDescending''
)
WHEN 1 THEN N'' DESC''
ELSE N''''
END
RETURN @r
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHPDebtorAgeSum]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPDebtorAgeSum]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by :  Shinu
Created on : 12/12/2007
Modified by : Prasanth
Modified on : 02-09-2008 Add ShopID and remaining parameteres
Purpose      : For Debtor Age Analysis Report
*/
CREATE PROCEDURE [dbo].[spHPDebtorAgeSum] (@dtstartdate varchar(11),@dtinvdate as varchar(11),
@intcustid varchar(1000),@intdepartid int,@intageTodate int=0,
@strCatName as Varchar(30)='''',@intShopID int=0 , @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(7),
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),
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)
SET @SettleCustId = ''''
set @Invcustid = ''''
if @intcustid<>''''    --hari given to handle with out customerid also
Begin
set @SettleCustId = '' customerid in ('' + @intcustid + '') and''
set @Invcustid = ''vwHPInvoices.customerid in ('' + @intcustid + '') and''
End
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwHPinvoices where '' + @Invcustid +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwHPinvoices where '' + @Invcustid +
'' invoicedate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwHPinvoices where '' + @Invcustid +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwHPinvoices where '' + @Invcustid +
'' invoicedate <='''''' + @dtinvdate + '''' +
'''''' and invoicedate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwHPsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwHPsettlements where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwHPsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwHPsettlements 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 FROM
#tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements
vwHPsettlements ON #tmpInvoices.customerid = vwHPsettlements.customerid AND
#tmpInvoices.CompanyID = vwHPsettlements.companyid AND
#tmpInvoices.InvoiceID = vwHPsettlements.invoiceid AND
/*#tmpInvoices.type = vwHPsettlements.type AND */
#tmpInvoices.shopid = vwHPsettlements.shopid  and
(vwHPsettlements.settleddate<='''''' + @dtinvdate +
'''''' or vwHPsettlements.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
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
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
drop table #tmpInvoices
drop table #tmpSettlements
end
set nocount off
set ansi_Warnings on' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownCheck]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownCheck]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.SpUpdateGodownCheck    Script Date: 18/01/2003 9:45:43 PM ******/
--Verified By Hariharan on 04/01/2003
--Not used
CREATE proc [dbo].[SpUpdateGodownCheck](@fromDate as varchar(10),@Godownid as int,
@locationid as int,@itemid as int,@shipmentid as int) as
return 0
/*
declare
@tmpOpeningGoodStock as numeric(18,3),
@tmpClosingGoodStock as numeric(18,3),
@tmpOpeningBadStock  as numeric(18,3),
@tmpClosingBadStock  as numeric(18,3),
@tmpDate	     as datetime,
@opGoodStock 	     as numeric(18,3),	
@opBadStock          as numeric(18,3),
@diffGoodStock       as numeric(18,3),		
@diffBadStock        as numeric(18,3),
@GoodStockDiff       as numeric(18,3),
@BadStockDiff	     as numeric(18,3),
@dtfromDate as datetime
set nocount on
set @dtfromdate = @fromdate
if @dtfromdate = (select packagedate from apackagesettings)
begin
	return 0
end
declare cursor_Godown scroll cursor for
select gsOpeningStock,gsStock,gsOpeningBadStock,
gsBadStock,gsstockdate from MoiGodownStock
where gsgodownid = @godownid and gslocationid = @locationid and
gsitemid = @Itemid and gsshipmentid = @shipmentid and
gsstockdate >= @dtFromDate
open cursor_Godown
fetch next from cursor_Godown into
@tmpOpeningGoodStock,@tmpClosingGoodStock,
@tmpOpeningBadStock,@tmpClosingBadStock,@tmpdate
/* For storing the Opening stock of Good and Bad quantity
	select @opGoodStock = @tmpClosingGoodStock
	select @opBadStock = @tmpClosingBadStock
while @@fetch_status = 0
begin
	fetch next from cursor_Godown into
	@tmpOpeningGoodStock,@tmpClosingGoodStock,
	@tmpOpeningBadStock,@tmpClosingBadStock,@tmpdate*/
/* For storing the Stock difference between the Opening and closing of Good and Bad Quantity
	select @diffGoodStock = @tmpOpeningGoodStock - @tmpClosingGoodStock
	select @diffBadStock = 	@tmpOpeningBadStock -  @tmpClosingBadStock
	
	select @GoodStockDiff = @opGoodStock - @diffGoodStock
	select @BadStockDiff = @opBadStock - @diffBadStock
	if (@GoodStockDiff < 0  or @BadStockDiff < 0 )
	begin
	close cursor_godown
	deallocate cursor_godown	
	return 1
	end
	update MoiGodownStock set gsOpeningStock = @opGoodStock,
	gsOpeningBadStock = @opBadStock,gsstock = @GoodStockDiff,
	gsbadstock = @BadStockDiff where
	gsgodownid = @godownid and gslocationid = @locationid and
	gsitemid = @itemid and gsshipmentid = @shipmentid and
	gsstockdate = @tmpdate
	
	select @opGoodStock = @GoodStockDiff
	select @opBadStock = @BadStockDiff
end
close cursor_godown
deallocate cursor_godown*/
return 0*/' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownGoodCheck]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownGoodCheck]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.SpUpdateGodownGoodCheck    Script Date: 18/01/2003 9:45:43 PM ******/
--Verified By hariharan on 04/01/2003
CREATE proc [dbo].[SpUpdateGodownGoodCheck](@fromDate as varchar(10),@Godownid as int,
@locationid as int,@itemid as int,@shipmentid as int) as
return 0
/*declare
@tmpOpeningGoodStock as numeric(18,3),
@tmpClosingGoodStock as numeric(18,3),
@tmpDate	     as datetime,
@opGoodStock 	     as numeric(18,3),	
@diffGoodStock       as numeric(18,3),		
@GoodStockDiff       as numeric(18,3),
@dtfromDate as datetime
set nocount on
set @dtfromdate = @fromdate
declare cursor_Godown scroll cursor for
select gsOpeningStock,gsStock,
gsstockdate from MoiGodownStock
where gsgodownid = @godownid and gslocationid = @locationid and
gsitemid = @Itemid and gsshipmentid = @shipmentid and
gsstockdate >= @dtFromDate
open cursor_Godown
fetch next from cursor_Godown into
@tmpOpeningGoodStock,@tmpClosingGoodStock,
@tmpdate
/* For storing the Opening stock of Good quantity */
/*	select @opGoodStock = @tmpClosingGoodStock
while @@fetch_status = 0
begin
	fetch next from cursor_Godown into
	@tmpOpeningGoodStock,@tmpClosingGoodStock,@tmpdate*/
/* For storing the Stock difference between the Opening and closing of Good Quantity */
/*	select @diffGoodStock = @tmpOpeningGoodStock - @tmpClosingGoodStock
	
	select @GoodStockDiff = @opGoodStock - @diffGoodStock
	if (@GoodStockDiff < 0)
	begin
	close cursor_godown
	deallocate cursor_godown	
	return 1
	end
	update MoiGodownStock set gsOpeningStock = @opGoodStock,
	gsstock = @GoodStockDiff where
	gsgodownid = @godownid and gslocationid = @locationid and
	gsitemid = @itemid and gsshipmentid = @shipmentid and
	gsstockdate = @tmpdate
	
	select @opGoodStock = @GoodStockDiff
	
end
close cursor_godown
deallocate cursor_godown
return 0*/
*/' 
END
GO
/****** Object:  StoredProcedure [dbo].[spYearSalesShopWise]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearSalesShopWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---spYearSalesShopWise ''20080101'',''20090101'',''TO'',1,0,''1,2''
CREATE  PROCEDURE [dbo].[spYearSalesShopWise]  (@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitShopWise as int = 1,
@intDepartmentId as int = 0,@strShopId AS varchar(20)='''')  AS
Begin
set nocount on
declare @strSql as nvarchar(1000)
declare @minYear as datetime,
@dtDate as datetime,@strShopCond as varchar(100)
set @dtDate = cast ( @strfromdate as datetime )
set @minYear = year( @dtDate  ) -1
if @strShopID    <>''''
	set @strShopCond='' where shopname in (select ShopName from Ashops where shopID in (''+ @strShopId + ''))''
Else
	set @strShopCond=''''
Create table #YearSales( Years varchar(10), BillDate datetime , ShopName varchar(100),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2),
yearno int)
if @strType = ''CA''
begin
if (@bitshopwise = 1)
begin
set  @strSql = N'' Select  tyear , billdate, ShopName ,
actamount, dAmount, cAmount, tyear
from vwSalesAnalysisByYear vsa , ashops S where
vsa.cash = 1 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
else
begin
set  @strSql = N'' Select  tyear , billdate, departmentName ,
actamount, dAmount, cAmount, tYear
from vwSalesAnalysisByYear vsa , adepartmentmaster d
where vsa.cash = 1 and d.departmentiD= vsa.departmentid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
end
else if @strType = ''CR''
begin
if (@bitshopwise =1)
begin
set  @strSql = N'' Select  tyear , billdate, ShopName,
actamount, dAmount, cAmount, tyear
from vwSalesAnalysisByYear vsa , ashops S
where vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
else
begin
set  @strSql = N'' Select  tyear , billdate, departmentName,
ActAmount, dAmount, cAmount, tYear
from vwSalesAnalysisByYear vsa , adepartmentmaster d
where  vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
end
else if @strType = ''TO''
begin
if (@bitshopwise =1)
begin
set  @strSql = N'' Select  tyear , billdate, ShopName ,
actamount, dAmount, cAmount, tyear from
vwSalesAnalysisByYear vsa , ashops S where
s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate + ''''''  and ''''''
+ @strToDate + ''''''''
end
else
begin
set  @strSql = N'' Select  tyear , billdate, departmentName ,
actamount, dAmount, cAmount, tyear from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate + ''''''  and ''''''
+ @strToDate + ''''''''
end
end
---Department Filteration
if (@intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
insert into #YearSales exec sp_executesql  @strSql
update   #YearSales  set Years =  cast ((cast(Years as int)- year(cast(@strfromdate as
datetime))+1) as varchar)
set  @strSql=  N''select * from #YearSales '' + @strShopCond + '' order by yearno, billdate ''
exec sp_executesql  @strSql
set nocount off
end ----end of sp' 
END
GO
/****** Object:  StoredProcedure [dbo].[spYearSales]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified By  : Lawrence.J
-- Modification  : Department Filteration
-- Modified Date : June-05-2003
------------------------------------------------------------------------------------
-- Modified by  : Kishore, hariharan
-- Modified on  : 18/06/2003, 11/11/2003
-- Comments  : Added dTotalSales and cTotalSalesColumns
--                        Removed the filtaration by department id in the query
--   included department condition
------------------------------------------------------------------------------------------
-- Modified by : Bijesh.B
-- Date        : 04/07/2011
-- RefNo       : RefNo-2
-- Comments    : PD Cheque feature added
--  exec spWeekSales ''20080707'',''20080707'',''pd'',1,0,1
------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spYearSales]  (@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitShopWise as bit = 1,
@intDepartmentId as int = 0)  AS
Begin
set nocount on
declare @strSql as nvarchar(1000)
declare @minYear as datetime,
@dtDate as datetime
set @dtDate = cast ( @strfromdate as datetime )
set @minYear = year( @dtDate  ) -1
Create table #YearSales( Years varchar(10), BillDate datetime , ShopName varchar(100),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2),
yearno int)
if @strType = ''CA''
begin
if (@bitshopwise = 1)
begin
set  @strSql = N'' Select  tyear , billdate, ShopName ,
actamount, dAmount, cAmount, tyear
from vwSalesAnalysisByYear vsa , ashops S where
vsa.cash = 1 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
else
begin
set  @strSql = N'' Select  tyear , billdate, departmentName ,
actamount, dAmount, cAmount, tYear
from vwSalesAnalysisByYear vsa , adepartmentmaster d
where vsa.cash = 1 and d.departmentiD= vsa.departmentid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
end
else if @strType = ''CR''
begin
if (@bitshopwise =1)
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
set  @strSql = N'' Select  tyear , billdate, ShopName,
actamount, dAmount, cAmount, tyear
from vwSalesAnalysisByYear vsa , ashops S where
transtype <> ''''PD CHEQUE'''' and
vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
else
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
set  @strSql = N'' Select  tyear , billdate, departmentName,
ActAmount, dAmount, cAmount, tYear
from vwSalesAnalysisByYear vsa , adepartmentmaster d where
transtype <> ''''PD CHEQUE'''' and
vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
end
--RefNo-2 start --------------------------------------------------------
-- PD Cheque Amount only
else if @strType = ''PD''
begin
if (@bitshopwise =1)
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
set  @strSql = N'' Select  tyear , billdate, ShopName,
actamount, dAmount, cAmount, tyear
from vwSalesAnalysisByYear vsa , ashops S where
transtype = ''''PD CHEQUE'''' and
vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
else
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
set  @strSql = N'' Select  tyear , billdate, departmentName,
ActAmount, dAmount, cAmount, tYear
from vwSalesAnalysisByYear vsa , adepartmentmaster d where
transtype = ''''PD CHEQUE'''' and
vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate
+ ''''''  and '''''' + @strToDate + ''''''''
end
end
--RefNo-2 ends --------------------------------------------------------
else if @strType = ''TO''
begin
if (@bitshopwise =1)
begin
set  @strSql = N'' Select  tyear , billdate, ShopName ,
actamount, dAmount, cAmount, tyear from
vwSalesAnalysisByYear vsa , ashops S where
s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate + ''''''  and ''''''
+ @strToDate + ''''''''
end
else
begin
set  @strSql = N'' Select  tyear , billdate, departmentName ,
actamount, dAmount, cAmount, tyear from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate + ''''''  and ''''''
+ @strToDate + ''''''''
end
end
---Department Filteration
if (@intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
insert into #YearSales exec sp_executesql  @strSql
update   #YearSales  set Years =  cast ((cast(Years as int)- year(cast(@strfromdate as
datetime))+1) as varchar)
select * from #YearSales order by yearno, billdate
set nocount off
end ----end of sp' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSalesAllShops]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthWiseProductSalesAllShops]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spMonthWiseProductSalesAllShops ''20080101'',''20080301'','''','''',''3,4'',0
CREATE PROCEDURE [dbo].[spMonthWiseProductSalesAllShops] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@strBrand as varchar(250),
@strCategoryId as varchar(250),
@intShopId as varchar(250),
@intDepartmentId as int = 0)  AS
Begin
declare @strQry as nvarchar(2000)
set @strQry = N''select MonthSales.MonthName, MonthSales.MonthCode,
MonthSales.YearName, MonthSales.posdItemId,
convert(numeric(18,2),sum(MonthSales.amount))  UnitPrice,
convert(numeric(18,2),sum(MonthSales.damount)) dUnitPrice,
convert(numeric(18,2),sum(MonthSales.camount)) cUnitPrice,
sum(MonthSales.quantity) Quantity,
MonthSales.poshShopId,
a.ItemCode, ltrim(rtrim(left(vw.itemdescription,250))) ItemDescription, a.Brand,
a.ModelNo, a.ItemCategoryId, MonthSales.MonthNo,au.UnitName,inq.Stock
from
(select datename(month,poshbilldate) monthname,
substring(datename(month,poshbilldate),1,3)
+ ''''-'''' + substring(convert(varchar(4),year(poshbilldate)),3,2) monthcode,
year(poshbilldate) yearname, posditemid, avg(posdunitprice) unitprice,
avg(dunitprice) dunitprice, avg(cunitprice) cunitprice,
sum(posdquantity) quantity, poshShopID, month(poshbilldate) monthno ,
sum(amount)amount,sum(camount)camount,sum(damount)damount
from vwshopitemsales
where poshbilldate >= '''''' + @strfromdate + '''''' and poshbilldate <= ''''''+ @strtodate + ''''''
group by  poshshopid, posditemid, year(poshbilldate), month(poshbilldate), poshbilldate)
MonthSales, aitem a, vwitemdescription vw, aShops,aunit au, vwinquiryshopstock inq
where vw.itemid = a.itemid
and MonthSales.posditemid = a.itemid
and MonthSales.poshShopId = aShops.ShopId
and a.UnitsID=au.UnitId and a.itemid =inq.itemid and aShops.ShopId =inq.shopid''
if (ltrim(rtrim(@strbrand)) <> '''')
Begin
set @strQry = @strQry + N'' and a.brand in ('''''' + @strbrand +'''''')''
End
if (ltrim(rtrim(@strcategoryid)) <> '''')
Begin
set @strQry = @strQry + N'' and a.itemcategoryid in('' + @strcategoryid + '')''
End
if @intshopid > ''''
Begin
set @strQry = @strQry + N'' and poshshopid in ('' + @intshopid + '')''
End
if @intDepartmentId <> 0
Begin
Set @strQry = @strQry + N'' and aShops.DepartmentId = '' + str(@intDepartmentId)
End
set @strQry = @strQry + N'' group by MonthSales.yearname,
MonthSales.monthno, MonthSales.monthname, MonthSales.monthcode, MonthSales.posditemid,
a.itemcode, vw.itemdescription, a.brand,
a.modelno, MonthSales.poshShopID, a.itemcategoryid ,au.UnitName,inq.Stock order by MonthSales.yearname,
MonthSales.monthno asc''
--print @strQry
exec sp_executesql @strQry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRebatePayment]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebatePayment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spRebatePayment 1,1,''20030101'',''20030530'',0,0,''o''
------------------------------------------------------------------------
--Created  on 	: 25/05/2003
--Created  by	: R Harikrishnan
--Comments	: For Rebate Payment Report
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
------------------------------------------------------------------------
CREATE procedure [dbo].[spRebatePayment]
	@intCompanyID		as int,
	@intShopID 		as int,
	@strFromDate 		as varchar(8),
	@strToDate		as varchar(8),
	@intCustomerID		as int=0,
	@intSalesPersonID 	as int=0,
	@strType		as char(1)--if @strType=''O'' then means outstanding
as
--set @intCompanyID=1
--set @intShopID =1
--set @strFromDate =''20030101''
--set @strToDate=''20030530''
--set @intCustomerID=0
--set @intSalesPersonID=0
declare @strSql as nVarchar(4000)
set @strSql=N''select
	a.rcshopid, a.rcapprovedid, a.rcapprovedno, a.rcapproveddate, a.rcRebatePerson,
	avg(a.RebateAmt) Rebateamt,a.SalesPerson, a.PONo,a.ihCustomerID,
	a.CustomerName,a.CurrencyID,sum(isnull(b.SettleAmt,0)) SettleAmt,
	sum(isnull(b.CustEquivalentAmount,0)) CustEquivalentAmount, b.UpdateTime
From
	(select
		rc.rcshopid, rc.rcapprovedid, rc.rcapprovedno,
		rc.rcapproveddate,rc.rcRebatePerson,
		sum(rcd.rcdrebateamount*rcd.rcdQuantity) RebateAmt,sm.SperName SalesPerson,
		ih.ihInvoiceNo PONo,ih.ihCustomerID, cm.CustomerName,cm.CurrencyID
	From
		losRebateConfirmHeader rc, losRebateConfirmDetail rcd,
		losRebateRequest rr,losInvoiceHeader ih, aSalesPersonMaster sm,
		aCustomerMaster cm
	Where
		rc.rcshopid=rcd.rcdshopid and rc.rcapprovedid =rcd.rcdapprovedid and
		rc.rcshopid=rr.rrshopid and rc.rcreqid=rr.rrreqid and
		rr.rrshopid=ih.ihShopID and rr.rrpoid=ih.ihInvoiceID and
		rr.rrsalespersonID = sm.sperID And ih.ihCustomerID = cm.CustomerID and
		isnull(rccancelled,0)=0 and isnull(rrCancelled,0)=0 and rc.rcshopid='' +
		convert(varchar(10),@intShopID)
	if @strType<>''O''
		set @strSql=@strSql + N'' and rc.rcapproveddate between "'' +
		@strFromDate + ''" and "'' + @strToDate +N''"''
	if @intCustomerID>0
		set @strSql=@strSql + N'' and ih.ihCustomerID ='' + convert(varchar(10),@intCustomerID)
	if @intSalesPersonID>0
		set @strSql=@strSql + N'' and rr.rrsalespersonID ='' + convert(varchar(10),@intSalesPersonID)
	set @strSql=@strSql + N'' Group By
		rc.rcshopid, rc.rcapprovedid, rc.rcapprovedno, rc.rcapproveddate, rc.rcRebatePerson,
		sm.SperName, ih.ihInvoiceNo, ih.ihCustomerID,cm.CustomerName,cm.CurrencyID) a
	Left Outer Join
	(select
		pd.*, ph.UpdateTime
	from
		aHQPaymentVoucherRebateDetails pd,aHQPaymentVoucherHeader ph
	where
		pd.PaymentID=ph.phPaymentID and pd.CompanyID=ph.phCompanyID and
		ph.phCancelled=0 and pd.companyID='' + convert(varchar(10),@intCompanyID)
	if @intCustomerID>0
	set @strSql= @strSql + N'' and pd.CustomerID='' + convert(varchar(10),@intCustomerID)
set @strSql =@strSql + N'') b
	on a.rcshopid = b.ShopID And a.rcapprovedid = b.RebateApprovalID
Group By
	a.rcshopid, a.rcapprovedid, a.rcapprovedno,a.rcapproveddate, a.rcRebatePerson,a.SalesPerson ,
	a.PONo,a.ihCustomerID, a.CustomerName,a.CurrencyID, b.UpdateTime ''
if @strType=''O''
	set @strSql=@strSql + N''having avg(a.RebateAmt)>sum(isnull(b.CustEquivalentAmount,0))''
exec sp_executesql @strSql' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRebuildAllIndex]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebuildAllIndex]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- To rebuild all indexes in adminv2 db
-- Prepared by: Regin
CREATE procedure [dbo].[spRebuildAllIndex]
@fillfactor as int = 90
as
begin
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)
-- create table cursor
DECLARE TableCursor CURSOR FOR
SELECT table_catalog + ''.'' + table_schema + ''.'' + table_name as tableName
FROM adminv2.INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE''
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
-- SQL 2005 command
SET @cmd = ''ALTER INDEX ALL ON '' + @Table + '' REBUILD WITH (FILLFACTOR = '' + CONVERT(VARCHAR(3),@fillfactor) + '')''
EXEC (@cmd)
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
end -- end of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRatioDetails]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRatioDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- spRatioDetails 1,5,2
------------------------------------------------------------
-- Created by   : R Harikrishnan
-- Created ON   : 16/09/2003
-- Comments     : For Ratio Analysis Report
------------------------------------------------------------
CREATE PROCEDURE [dbo].[spRatioDetails]
	@intCompanyID 	AS INT,
	@intRatioID 	AS INT = 0,
	@intLevel 	AS INT = 0
AS
BEGIN
	DECLARE @strSQL	AS NVARCHAR(3000)
	SET @strSQL=N''SELECT
		RTM.companyID, RTM.Lev1GroupID, RTM.Lev1GroupDesc, RTM.Lev2GroupID,
		RTM.Lev2GroupDesc, RTM.Lev3GroupID, RTM.Lev3GroupDesc, RTM.LastGroupID,
		RTM.LastLevel, RTM.LastGroupDesc, ETM.EntityId, ETM.EntityDesc, ETM.Numerator,ETM.RatioType,
		ETM.Multiplier, ETM.AccountID, ETM.CalcType, ETM.AccountDesc,
		ETM.AccountType, ETM.AccountGroup
	FROM
		(SELECT
			Lev1.companyID, Lev1.GroupID Lev1GroupID, Lev1.GroupDesc Lev1GroupDesc,
			Lev23.Lev2GroupID, Lev23.Lev2GroupDesc, Lev23.Lev3GroupID,
			Lev23.Lev3GroupDesc,
			CASE 	WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN Lev23.Lev3GroupID
				WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN Lev23.Lev2GroupID
				ELSE Lev1.GroupID END LastGroupID,
			CASE 	WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN Lev23.Lev3GroupDesc
				WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN Lev23.Lev2GroupDesc
				ELSE Lev1.GroupDesc END LastGroupDesc,
			CASE 	WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN 3
				WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN 2
				ELSE 1 END LastLevel
		FROM
			aAccRatioGroupmaster Lev1 LEFT OUTER JOIN
			(SELECT
				Lev2.CompanyID,Lev2.GroupID Lev2GroupID,Lev2.GroupDesc
				Lev2GroupDesc, Lev2.ParentGroupID Lev2ParentGroupID,
				Lev3.GroupID Lev3GroupID, Lev3.GroupDesc Lev3GroupDesc
			FROM
				(SELECT
					companyID,GroupID,GroupDesc,ParentGroupID
				FROM
					aAccRatioGroupmaster
				WHERE
					LevelCode=2) Lev2 LEFT OUTER JOIN
				(SELECT
					companyID,GroupID,GroupDesc,ParentGroupID
				FROM
					aAccRatioGroupmaster
				WHERE
					LevelCode=3) Lev3
				ON lev2.companyID=lev3.companyID AND
				Lev2.GroupID=Lev3.ParentGroupID) Lev23
			ON lev1.companyID=lev23.companyID AND
			Lev1.GroupID=Lev23.Lev2ParentGroupID
		WHERE
			LevelCode=1) RTM,
		(SELECT
			em.CompanyID, em.EntityId, em.GroupID, em.EntityDesc, em.Numerator,
			rm.RatioType, rm.Multiplier, ea.AccountID, ea.CalcType, am.AccountDesc,
			gm.AccountType, gm.GroupDesc AccountGroup
		FROM
			AAccRatioEntitiesMaster em, aAccRatioGroupmaster rm,
			AAccRatioEntitiesAccounts ea, aAccountMaster am,
			aGroupMaster gm
		WHERE
			em.CompanyID=rm.CompanyID and em.GroupID=rm.GroupID and
			em.CompanyID=ea.CompanyID and em.EntityID=ea.EntityID and
			ea.CompanyID=am.CompanyID and ea.AccountID=am.AccountID and
			am.CompanyID= gm.CompanyID and am.GroupID=gm.GroupID) ETM
	WHERE
		RTM.CompanyID=ETM.CompanyID and RTM.LastGroupID=ETM.GroupID and
		RTM.CompanyID='' + CONVERT(VARCHAR(12),@intCompanyID)
	IF @intLevel=1
		SET @strSQL=@strSQL + '' and RTM.Lev1GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
	IF @intLevel=2
		SET @strSQL=@strSQL + '' and RTM.Lev2GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
	IF @intLevel=3
		SET @strSQL=@strSQL + '' and RTM.Lev3GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
	EXECUTE sp_executeSQL @strSQL
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSetupLastYearData]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetupLastYearData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By   : Hariharan
--Created Date : 08/08/2004
CREATE Proc [dbo].[spSetupLastYearData] (@sintYear as int,
				 @intDepartmentId as int,
				 @intCompanyId as int,
				 @strHeaderOut as varchar(50) output,
				 @strDetailOut as varchar(50) output,
				 @Time as varchar(50))
as
Set nocount on
Declare @strHeaderTableName as varchar(50), @strDetailTableName as Varchar(50)
Declare @CreateQuery as nvarchar(4000)
set @strHeaderTableName = ''##Tempjournalheader'' + convert(varchar(3),@intDepartmentId) + @Time
set @strDetailTableName = ''##vwJournalDetails'' + convert(varchar(3),@intDepartmentId) + @Time
Begin
set @CreateQuery = ''Create table '' +  @strDetailTableName + '' (companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)''
exec sp_Executesql @CreateQuery
set @CreateQuery = ''Create table '' +  @strHeaderTableName + ''
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)''
	exec sp_Executesql @CreateQuery
	Set @CreateQuery = '' insert ''  + @strHeaderTableName  +
	'' Select H.* from moajournalheader h (nolock) where year(journaldate) = '' +
	convert(varchar(4),@sintYear) + '' and h.CompanyId = '' +
	convert(varchar(2),@intCompanyId)
	exec sp_Executesql @CreateQuery
	Set @CreateQuery = ''insert '' + @strDetailTableName +
	'' Select d.* from '' + @strHeaderTableName + '' h, vwJournalDetails d (nolock) where
	year(Journaldate) = '' + convert(varchar(4),@sintYear) + '' and
	h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
	h.CompanyId = '' + convert(varchar(2),@intCompanyId) + '' and d.departmentid  =''
	+ convert(varchar(2),@intDepartmentId)
	exec sp_Executesql @CreateQuery
	set @strHeaderOut = @strHeaderTableName
	set @strDetailOut = @strDetailTableName
Set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSettledInvoice]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSettledInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Purpose     : Adding Currencyid
--------------------------------------------------------------------------
--  spSettledInvoice ''20100101'',''20100805'',0,0      3171
create PROCEDURE [dbo].[spSettledInvoice] (
@dtstartdate varchar(11),@dtinvdate as varchar(11),
@intdepartid int,@intShopID 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)
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(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))
if @intShopID > 0
Begin
set @strShop='' And  #tmpInvoices.shopid = '' + cast(@intShopID As varchar)
end
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwInvoices where '' +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' +
'' invoicedate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' +
'' invoicedate <='''''' + @dtinvdate + '''' +
'''''' and invoicedate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwsettlements where '' +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  ''''''''
else                             set @strquery  = ''insert #tmpSettlements  Select * from vwsettlements where '' +
'' settleddate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwsettlements where '' +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwsettlements where '' +
'' settleddate <='''''' + @dtinvdate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
set @strquery = ''SELECT  #tmpInvoices.invoiceid,  #tmpInvoices.invoiceno, max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,
#tmpInvoices.type,#tmpInvoices.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(#tmpInvoices.SalesPersonID,0)SalesPersonID,slp.Spername 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   slp on  slp.Sperid  = #tmpInvoices.SalesPersonID    ,
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,#tmpInvoices.remarks,
customername,currencyname,symbol, #tmpInvoices.duedate,
address1, address2, address3, #tmpInvoices.referenceno,
debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID ,SalesPersonID ,slp.Spername
having max(invamt) = sum(isnull(settledamt,0))''
exec sp_Executesql @strquery
drop table #tmpInvoices
drop table #tmpSettlements
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spServiceSalesDateWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spServiceSalesDateWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created BY 	: Hariharan
--Created Date	: 28/01/2004
CREATE Proc [dbo].[spServiceSalesDateWise] @intShopId as int, @strFromDate as varchar(8),
@strToDate as varchar(8), @strCategory as varchar(2000)
as
Set NOCount on
Begin
	Declare @strSql As nVarchar(4000)
Create Table #ServiceSales(
	companyid int,
	shopid int,
	sDate datetime,
	parts numeric(18,2),
	dparts numeric(18,2),
	cparts numeric(18,2),
	pService numeric(18,2),
	dService numeric(18,2),
	cService numeric(18,2),
	Sales numeric(18,2),
	dSales numeric(18,2),
	cSales numeric(18,2) )
	if @strCategory <>''''
		set @strCategory = '' and ai.itemcategoryid in ( '' + @strCategory + '')''
set @strSql = N''select
	serinvhcompanyid, serinvhshopid, serinvhdate,
	0 parts, 0 dparts, 0 cparts, convert(numeric(18,2), sum(serinvhserviceamt)) Service,
	convert(numeric(18,2), sum(serinvhserviceamt * seinvhdepexrate)) dService,
	convert(numeric(18,2), sum(serinvhserviceamt * serinvhcmpexrate)) cService,
	 0, 0, 0
from
	losserviceinvheader left outer join aitem ai on serinvhItemid = ai.itemid
where
	serinvhcancelled = 0 and serinvhserviceamt>0 and serinvhamount<>0
	'' + @strCategory + '' and serinvhdate >='''''' + @strFromDate +
	'''''' and serinvhdate <='''''' + @strToDate +
	'''''' and serinvhshopid = '' + convert(varchar(2), @intShopId ) +
	'' Group BY serinvhcompanyid, serinvhshopid, serinvhdate ''
insert  #ServiceSales
	exec sp_executesql @strSql
set @strSql = N''select
	serinvhcompanyid, serinvhshopid, serinvhdate, 	
	convert(numeric(18,2), sum(repinvdrate * repinvpackqty)) parts,
	convert(numeric(18,2), sum(repinvdrate * repinvpackqty * seinvhdepexrate)) dparts,
	convert(numeric(18,2), sum(repinvdrate * repinvpackqty * serinvhcmpexrate)) cparts,
	0, 0, 0, 0, 0, 0
from
	losserviceinvheader, losInvoicedPartsReplaceDetails left outer join aitem ai on repinvdpartsid = ai.Itemid
where
	serinvhCompanyId = repinvcompanyid and serinvhShopID = repinvdshopid
	and serinvhId = repinvinvoiceid and
	serinvhcancelled = 0 and serinvhamount<>0  '' + @strCategory +
	'' and serinvhdate >='''''' + @strFromDate +  '''''' and serinvhdate <='''''' + @strToDate +
	'''''' and serinvhshopid = '' + convert(varchar(2), @intShopId ) +
	''Group BY serinvhcompanyid, serinvhdepartmentid, serinvhshopid, serinvhdate''
insert  #ServiceSales
	exec sp_executesql @strSql
set @strSql = N''select
	poshCompanyId, poshShopId, poshBillDate,
	0, 0, 0, 0, 0, 0,
	convert(numeric(18,2), sum(posdunitprice)) Sales,
	convert(numeric(18,2), sum(posdunitprice*poshdepexrate)) dSales,
	convert(numeric(18,2), sum(posdunitprice*poshExchangeRate)) cSales
from
	losPosHeader, losPosDetail, aitem ai
where
	poshShopId = posdSHopId and poshBillId = posdBillId and poshCancelled = 0
	and posditemid = ai.itemid '' + @strCategory + '' and poshbilldate >='''''' +
	@strFromDate + 	'''''' and poshBillDate <='''''' + @strToDate +
	'''''' and poshShopID = '' + convert(varchar(2), @intShopId ) +
	''Group by poshCompanyId, poshShopId, poshBillDate''
insert  #ServiceSales
	exec sp_executesql @strSql
set @strSql = N''select
	ihCompanyId, ihShopId, ihInvoiceDate,
	0, 0, 0, 0, 0, 0,
	convert(numeric(18,2), sum(idunitprice)) Sales,
	convert(numeric(18,2), sum(idunitprice*ihdepexrate)) dSales,
	convert(numeric(18,2), sum(idunitprice*ihExchangeRate)) cSales
from
	losInvoiceHeader, losInvoiceDetail, aitem ai
where
	ihShopId = idSHopId and IhInvoiceId = idInvoiceId and ihCancelled = 0
	and idItemId = ai.ItemId  '' + @strCategory + '' and ihInvoiceDate >='''''' +
	@strFromDate + 	'''''' and ihInvoiceDate <='''''' + @strToDate +
	'''''' and ihShopID = '' + convert(varchar(2), @intShopId ) +
	''Group by ihCompanyId, ihDepartmentId, ihShopId, ihInvoiceDate''
insert  #ServiceSales
	exec sp_executesql @strSql
set @strSql = N''select
	ihCompanyId, ihShopId, ihInvoiceDate,
	0, 0, 0, 0, 0, 0,
	convert(numeric(18,2), sum(idunitprice)) Sales,
	convert(numeric(18,2), sum(idunitprice*ihdepexrate)) dSales,
	convert(numeric(18,2), sum(idunitprice*ihExchangeRate)) cSales
from
	losSpecialInvoiceHeader, losSpecialInvoiceDetail , aitem ai
where
	ihShopId = idSHopId and IhInvoiceId = idInvoiceId and ihCancelled = 0
	and idRatetype = 0 and reqqty <> 0 and idItemId = ai.itemid ''
	+ @strCategory + '' and ihInvoiceDate >='''''' +
	@strFromDate + 	'''''' and ihInvoiceDate <='''''' + @strToDate +
	'''''' and ihShopID = '' + convert(varchar(2), @intShopId ) +
	''Group by ihCompanyId, ihDepartmentId, ihShopId, ihInvoiceDate''
insert  #ServiceSales
	exec sp_executesql @strSql
Select companyid , shopid , sDate , sum(parts) parts, sum(dparts) dparts, sum(cparts) cparts,
	sum(pService) pService, sum(dService) dService, sum(cService) cService,
	sum(Sales) Sales, sum(dSales) dSales, sum(cSales) cSales from #ServiceSales
	group by companyid , shopid , sDate
End
Set NOCount OFf' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPaymentWithChequeDetails]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPaymentWithChequeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  on	: 16/05/2003
--Created  by	: R Harikrishnan
--Comment	: For MIS Report
----------------------------------------------------------------------
--modified by 	:venki 16/06/03
--comment 	:for blank chq option
-----------------------------------------------------------------------
CREATE Procedure [dbo].[spPaymentWithChequeDetails]
	@intCompanyID 		as int,
	@intAccID 		as int,
	@intDeptID		as int,
	@strDateRangeType	as char(1),
	@strFromDate 		as varchar(8),
	@strTodate		as varchar(8)
as
declare @strSQl as nvarchar(2500)
set @strSQl=N''select  ph.phcompanyid companyid, ph.phpaymentid paymentid, ph.phpaymentno,
	ph.phpaymentdate paymentdate, ph.phPayee Payee,  ph.phremarks remarks,
	ph.phbankcashid bankcashid, case when ph.phCancelled=1 then "Y" else "N" end Cancelled,
	ph.phDepartmentID, ph.phPosted, d.DepartmentName, ph.phAmount,
	c.symbol, ph.phChequeDetails,isnull(ph.phallowblancheque,0)phallowblancheque
from
	ahqpaymentvoucherheader ph, aaccountmaster acc,
	aDepartmentMaster d, acurrencymaster c
where
	ph.phcompanyid = acc.companyid and ph.phbankcashid = acc.accountid and
	ph.phDepartmentID = d.DepartmentID and ph.phCompanyID=d.CompanyID and
	acc.companyid = c.companyid and acc.currencyid = c.currencyid and
	ph.phcompanyID='' + convert(varchar(10),@intCompanyID) + N'' and ph.phbankcashid =''
	+ convert(varchar(20),@intAccID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and ph.phDepartmentID='' + convert(varchar(10),@intDeptID)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and ph.phpaymentdate between "'' + @strFromDate + ''" and "'' +
	@strToDate + ''"''
set @strSql =@strSql + N'' Union all ''
set @strSql =@strSql + N'' select
	c.CompanyID, c.contraID, c.contrano, c.contradate, a.AccountDesc,
	c.remarks, c.ToAccountID, case when c.cancelled =1 then "Y" else "N" end Cancelled,
	c.DepartmentID, c.Posted, dm.departmentName, c.contraamount, cm.Symbol, c.chequeno,0
from
	contra c, aAccountMaster a, aCurrencyMaster cm, aDepartmentMaster dm
where
	c.CompanyID=a.CompanyID and c.ToAccountID=a.AccountID and
	a.CompanyID=cm.CompanyID and a.CurrencyID=cm.CurrencyID and
	c.companyID=dm.companyID and c.DepartmentID=dm.DepartmentID and
	c.CompanyID='' ++ convert(varchar(10),@intCompanyID) + '' and c.fromaccountid=''
	+ convert(varchar(20),@intAccID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and c.DepartmentID='' + convert(varchar(10),@intDeptID)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and c.contradate between "'' + @strFromDate + ''" and "'' +
	@strToDate + ''"''
exec sp_executesql @strSQl' 
END
GO
/****** Object:  StoredProcedure [dbo].[spnonmovingitems]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spnonmovingitems]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------
-- Modified on  : 13/04/2009
-- Modified by  : Regin T.
-- Comments     : User is enabled to select more than one shop in the HQ Reports interface.
--                So this SP is modified to accept a list of Shop IDs as input.
--                Input argument @intshopid is modified as @strShopID.
--------------------------------------------------------------------------------------
--spnonmovingitems ''20070101'', ''20070102'', 0, 0, ''11''
CREATE  proc [dbo].[spnonmovingitems] @strstartdate as varchar(10), @strtodate as varchar(10),
@numpricerangemin as numeric(18,2), @numpricerangemax as numeric(18,2),
@strShopID as varchar(250), @strBrand as varchar(250) ='''',@NoOfBackDays as int=0 as
begin
set nocount on
create table #itemstockstart(
shopid int,
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2)
)
create table #itemstockend(
shopid int,
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2)
)
create table #itemstocktrans(
shopid int,
itemid int,
sdstock numeric(18,2),
edstock numeric(18,2),
transstock numeric(18,2)
)
create table #itemstock(
shopid 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 @strBrandCondition as varchar(250)
declare @dtMaxBillDateforDead as varchar(10)
declare @strShopCond as nvarchar(250)
if @strShopID <> ''''
set @strShopCond = '' in ('' + @strShopID + '')''  -- To select given shops
else
set @strShopCond = '' not in (-1)''  -- To select all shops
set @dtMaxBillDateforDead=(select convert(varchar(8),dateadd("d",-@NoOfBackDays,convert(datetime,@strToDate,120)),112))
if @numpricerangemin<>0 and @numpricerangemax <>0
begin
set @strwhere = '' and i.sellingprice >= '' + CONVERT(varchar(20),@numpricerangemin) +
''and i.sellingprice <= '' + convert(varchar(20), @numpricerangemax )
end
else
begin
set @strwhere = '' ''
end
set @strsql = N''select shopid, vw.itemid, sum(transqty * mode), 0.0, 0.0  from vwshopbincardauditwithopening vw,
(select sp.itemid, max(sellingprice) sellingprice from losshopitemshipmentdetail sp,
vwItemRetailPacking vw where sp.itemid = vw.itemid group by sp.itemid ) i
where i.itemid = vw.itemid and (sdate <'''''' +  @strstartdate + '''''' or sdate is null) and shopid ''
+ @strShopCond +   @strwhere + '' group by shopid, vw.itemid ''
insert into #itemstockstart
exec sp_Executesql @strsql
set @strsql = N''select shopid, vw.itemid, 0.0, sum(transqty * mode), 0.0  from vwshopbincardauditwithopening vw,
(select sp.itemid, max(sellingprice) sellingprice from losshopitemshipmentdetail sp,
vwItemRetailPacking vw where sp.itemid = vw.itemid group by sp.itemid ) i
where i.itemid = vw.itemid and (sdate <= '''''' + @strtodate + '''''' or sdate is null) and shopid '' +
@strShopCond + @strwhere + ''group by shopid, vw.itemid''
insert into #itemstockend
exec sp_Executesql @strsql
set @strsql = N''select shopid, vw.itemid, 0.0,  0.0, sum(transqty * mode)  from vwshopbincardaudit vw,
(select sp.itemid, max(sellingprice) sellingprice from losshopitemshipmentdetail sp,
vwItemRetailPacking vw where sp.itemid = vw.itemid group by sp.itemid ) i
where i.itemid = vw.itemid and (sdate >='''''' +  @strstartdate + '''''' and sdate <= '''''' +  @strtodate + '''''' )
and shopid '' + @strShopCond + @strwhere +
'' and type <> ''''Exchange Out'''' and type <> ''''Credit Sales''''
and type <> ''''Cash Sales'''' group by shopid, vw.itemid''
insert into #itemstocktrans
exec sp_Executesql @strsql
insert into #itemstock
select shopid, itemid, sum(sdstock), sum(edstock), sum(transstock) from (
select shopid, itemid, sdstock, edstock, transstock from #itemstockstart
union all
select shopid, itemid, sdstock, edstock, transstock from #itemstockend
union all
select shopid, itemid, sdstock, edstock, transstock from #itemstocktrans) a
group by shopid, itemid
if @strBrand<>''''
set @strBrandCondition = '' and i.Brand ='''''' + @strBrand +'''''' ''
else
set @strBrandCondition=''''
if @NoOfBackDays <> 0
begin
set @strsql = N''select vw1.* from(select s.*,u.unitname, ic.itemcategoryid, ic.CategoryNameDescription, vw.itemdescription,
isnull(sellpr.sellingprice,0) sellingprice,i.brand, i.itemcode from
aitem i, aitemcategory ic, aunit u, vwitemdescription vw, #itemstock s
left outer join (select sp.itemid, max(sellingprice) sellingprice from
losshopitemshipmentdetail sp, vwItemRetailPacking vw where sp.itemid = vw.itemid
group by sp.itemid ) sellpr on s.itemid = sellpr.itemid
where vw.itemid = s.itemid and s.itemid = i.itemid and i.ItemCategoryID = ic.ItemCategoryID and
u.unitid = i.unitsid and (sdstock + transstock ) = edstock and edstock > 0 ''+ @strBrandCondition +''
)vw1
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 + '''''' order by vw1.CategoryNameDescription, vw1.itemcategoryid, vw1.itemdescription''
end
else -- if @NoOfBackDays = 0
begin
set @strsql = N''select s.*,u.unitname, ic.itemcategoryid, ic.CategoryNameDescription, vw.itemdescription,
isnull(sellpr.sellingprice,0) sellingprice,i.brand, i.itemcode from
aitem i, aitemcategory ic, aunit u, vwitemdescription vw, #itemstock s
left outer join (select sp.itemid, max(sellingprice) sellingprice from
losshopitemshipmentdetail sp, vwItemRetailPacking vw where sp.itemid = vw.itemid
group by sp.itemid ) sellpr on s.itemid = sellpr.itemid
where vw.itemid = s.itemid and s.itemid = i.itemid and i.ItemCategoryID = ic.ItemCategoryID and
u.unitid = i.unitsid and (sdstock + transstock ) = edstock and edstock > 0 ''+ @strBrandCondition +''
order by ic.CategoryNameDescription, ic.itemcategoryid, vw.itemdescription''
end
--print @strsql
exec sp_Executesql @strsql
drop table #itemstockstart
drop table #itemstockend
drop table #itemstocktrans
drop table #itemstock
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spQuoteItReplace]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuoteItReplace]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Last Modified By : Kishore
Modified Date    : 12/06/2003
Comments         : Added the condition - ''Active = 1''
Changed the join to left outer
(On comparison with v2)
- Modified date    :  11-07-2008
-Modified By       : Prasanth Joseph
-  Add ItemCode
- Modified date    : 03.02.2011
-Modified By       : SHINE DAS
-  Add ItemId
*/
CREATE PROCEDURE [dbo].[spQuoteItReplace] (@itemid as varchar(20),@strIn  varchar(250) , @strItemCode as varchar(250)='''' ) AS
declare @strItemCodeCond as Varchar(1000)
declare @strsql as nVarchar(4000)
if   @strItemCode<>''''
set @strItemCodeCond='' and itemcode ='''''' + @strItemCode + ''''''''
else
set @strItemCodeCond=''''
print @itemid
set @strSql=''SELECT DISTINCT a.ItemId, aip.PackingBarcode
FROM aItemPackingDetail aip  LEFT OUTER JOIN aItem a
ON aip.ItemId = a.ItemId
where  a.ItemId in ('' + @itemid + '') and REPLACE(a.ItemDescription, '''''''', 1) ='''''' + @strIn +'''''''' + @strItemCodeCond
exec sp_executesql  @strSql' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopItemSales]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopItemSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 12/12/02
-- Modified by  : leo
-- Comments  : v3
--------------------------------------------------------------------------------------
-- Modified on  : 12/06/2033
-- Modified by  : Kishore  shinu
-- Comments  : sp altered including amount column of vwShopItemSales
--                        and to include in reports of daily item sales
--                        (On comparison with v2)  ,,, Added Brand Condition
--------------------------------------------------------------------------------------
-- Modified on  : 13/04/2009
-- Modified by  : Regin T.
-- Comments     : User is enabled to select more than one shop in the interface.
--                So this SP is modified to accept a list of Shop IDs as input.
-- Reference No : RefNo-1
-- Modified on  : 04/09/2009 06/05/2010
-- Modified by  : Jyothish SR
-- Comments    : stock is added to the output
---is null cheking added  the codition isnull(sum(posdquantity),0)>0
--------------------------------------------------------------------------------------
-- Reference No : RefNo-2
-- Modified on  : 06/02/2012
-- Modified by  : AADYAKUMAR.D.V
-- Comments     : ItemRate is added to the output
--------------------------------------------------------------------------------------
-- spShopItemSales ''20120102'', ''20120102'', 50, ''F'', '''', 0, 0, 0, ''1,2,3,4,5'',''''
CREATE   PROCEDURE [dbo].[spShopItemSales] (@startdate varchar(10), @enddate
varchar(10), @count int, @movtype as varchar(1), @strcategoryid varchar(250),
@numpricefrom numeric(18,2), @numpriceto numeric(18,2), @numQtylimit as numeric(18,3),
@strShopID varchar(250), @strBrand as Varchar(250)='''')
as
declare @sdate as varchar(10),
@edate as varchar(10),
@intnum as int,
@quantity as numeric(18,3),
@UnitPrice as numeric(18,2),
@dUnitPrice as numeric(18,2),
@cUnitPrice as numeric(18,2),
@intshopid as int,
@intitemid as int,
@unit as varchar(15),
@itemdesc as varchar(50),
@categoryid int,
@categoryname as varchar(30),
@shopname as varchar(30),
@ItemRate as numeric(18,2),--RefNo-2
@strSql as nvarchar(3000),
@strBrandCondition as varchar(250),
@strSql2 as nvarchar(3000),
@strstock as numeric(18,2)
-- RefNo-1 Starts here --
declare @strCategoryCond as nvarchar(250) --Category Condition: The condition to be met by all categories
declare @strShopCond as nvarchar(250)     --Shop Condition: The condition to be met by all shops
declare @strQtyLimitCond as nvarchar(250) --Quantity Limit Condition: The condition to be met by all sales quantities
declare @strPriceFromCond as nvarchar(250)--Price Lower Limit Condition
declare @strPriceToCond as nvarchar(250)  --Price Upper Limit Condition
declare @strAscOrDesc as nvarchar(250)    --Stores Asc or Desc
declare @strShopsCond as nvarchar(250)
-- RefNo-1 Ends here --
create table #tempshopitemsales
(itemdesc  varchar(50),
shopid int,
itemid int,
unit varchar(15),
quantity  numeric(18,3),
UnitPrice numeric(18,2),
dUnitPrice numeric(18,2),
cUnitPrice numeric(18,2),
Categoryid int,
categoryname varchar(30),
shopname  varchar(50) ,
ItemRate  numeric(18,2)    --RefNo-2
)
begin
set nocount on
set @sdate= @startdate
set @edate= @enddate
set @intnum=0
set @quantity =0.00
set @UnitPrice =0.00
set @dUnitPrice =0.0
set @cUnitPrice =0.0
set @intshopid =0
set @intitemid =0
-- RefNo-1 Starts --
if @strcategoryid<>''''
set @strCategoryCond = '' in ('' + @strcategoryid + '')'' -- To select Specified Categories
else
set @strCategoryCond = '' not in (-1)''   -- To select All Categories
if @strShopID <> ''''
set @strShopCond = '' in ('' + @strShopID + '')''         -- To select given shops
-- set @strShopsCond = @strShopID
else
set @strShopCond = '' not in (-1)''    -- To select all shops
-- set @strShopsCond =-1
if @numQtylimit <>  0
if @movtype=''F''
set @strQtyLimitCond = '' >= '' + convert(varchar(21),@numqtylimit)
else -- Slow Moving Items
set @strQtyLimitCond = '' <= '' + convert(varchar(21),@numqtylimit)
else
set @strQtyLimitCond = '' <> -1000''    -- This trick is used to select all items
if @numPriceFrom <> 0
set @strPriceFromCond = '' >= '' + convert(varchar(20),@numPriceFrom)
else
set @strPriceFromCond = '' <> -1000''    -- This trick is used to select all items
if @numPriceTo <> 0
set @strPriceToCond = '' <= '' + convert(varchar(20),@numPriceTo)
else
set @strPriceToCond = '' <> -1000''     -- This trick is used to select all items
if @MovType = ''F''   -- For Fast Moving Items
set @strAscOrDesc = '' DESC''
else    -- For Slow Moving Items
set @strAscOrDesc = '' ASC''
set @strsql= ''declare curitemsales cursor for
select vwi.itemdescription,vws.poshShopID,vws.posditemid, au.unitname,
sum(posdquantity) Quantity,
avg(posdUnitPrice) posdUnitPrice,
avg(dUnitPrice) dUnitPrice,
avg(cUnitPrice) cUnitPrice,
ac.itemcategoryid,
ac.CategoryNameDescription,ash.ShopName,ai.ItemRate  --RefNo-2
from vwshopitemsales vws, vwitemdescription vwi ,aitem ai,aunit au,aitemcategory ac,
ashops ash where poshBilldate>= '''''' + @sdate + '''''' and poshBilldate<= '''''' + @edate +
'''''' and vws.posditemid=vwi.itemid and vws.poshShopID '' + @strShopCond + '' and
vws.posditemid=ai.itemid and ai.unitsid=au.unitid and
vws.poshShopID=ash.shopid and ai.itemcategoryid=ac.itemcategoryid
and ac.itemcategoryid '' + @strCategoryCond +
'' group by vwi.itemdescription,vws.poshShopID,vws.posditemid,au.unitname,
ac.itemcategoryid, ac.CategoryNameDescription,ash.shopname,ai.ItemRate --RefNo-2
having  isnull(sum(posdquantity),0)>0 and round((sum(posdUnitPrice)/ case when sum(posdquantity)= 0 then 1 else sum(posdquantity) end ),2)'' + @strPriceFromCond + '' and
round((sum(posdUnitPrice)/ case when sum(posdquantity)= 0 then 1 else sum(posdquantity) end),2) '' + @strPriceToCond +  '' and
sum(posdquantity) '' + @strQtyLimitCond +
'' order by sum(posdquantity) '' + @strAscOrDesc
execute sp_executesql @strsql
--print @strsql
-- RefNo-1 Ends --
open curitemsales
fetch next from curitemsales
into @itemdesc,@intshopid,@intitemid,@unit,@quantity, @UnitPrice, @dUnitPrice, @cUnitPrice,
@categoryid,@categoryname,@shopname,@ItemRate --RefNo-2
set @intnum=0
while @@fetch_status=0 and  @intnum<@count
begin
insert into #tempshopitemsales
values(@itemdesc,@intshopid,@intitemid,@unit,@quantity, @UnitPrice,
@dUnitPrice, @cUnitPrice, @categoryid, @categoryname,@shopname,@ItemRate)   --RefNo-2
set @intnum= @intnum + 1
fetch next from curitemsales
into @itemdesc,@intshopid ,@intitemid,@unit,@quantity, @UnitPrice, @dUnitPrice,
@cUnitPrice, @categoryid,@categoryname,@shopname,@ItemRate  --RefNo-2
end
close curitemsales
deallocate curitemsales
if  @strBrand <>''''
set @strBrandCondition = '' and ai.Brand ='''''' + @strBrand +'''''' ''
else
set @strBrandCondition=''''
set @strsql = N''select tmp.*,ai.itemcode,ai.brand ,vw.stock from  #tempshopitemsales tmp
left outer join aitem ai on tmp.itemid=ai.itemid  left outer join (select   itemid,  isnull(sum(stock),0) as stock   from vwInquiryShopStock  where shopid '' + @strShopCond + ''  group by itemid)vw on   vw.itemid=tmp.itemid '' + @strBrandCondition
execute sp_executesql @strsql
drop table #tempshopitemsales
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwPostingTransType]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPostingTransType]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
-- Modified by  : hariharan
-- Modified on  : 03/03/2004
-- Comments  : added payrollaccounts linking and asset module transactions
--   : ADDED REEXPORT
--Verified by       : Hariharan
--Verified Date      : 03/05/2004 (verified From Client DB)
-------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwPostingTransType] AS
--
SELECT ''SCI'' Type, ''Credit Invoice'' TransName
UNION ALL
SELECT ''POSGRN'',''Goods Return Note''
UNION ALL
SELECT ''spmt'', ''Shop Petty Cash Payments''
UNION ALL
SELECT ''sswo'', ''Shop Stock Writeoff''
UNION ALL
SELECT ''PACB'', ''HQ Purchase Bill''
UNION ALL
SELECT ''AI'', ''Accounts Invoice''
UNION ALL
SELECT ''isv'', ''Godown Stock Verification''
UNION ALL
SELECT ''lp'', ''Local Purchase''
UNION ALL
SELECT ''iswo'', ''Godown Stock WriteOff''
UNION ALL
SELECT ''strin'', ''Shop Transfer In''
UNION ALL
SELECT ''ssv'', ''Shop Stock Verification''
UNION ALL
SELECT ''B'', ''Accounts Bills''
UNION ALL
SELECT ''DCN'', ''HQ Debit Credit Note''
UNION ALL
SELECT ''pos'', ''Point of Sales''
UNION ALL
SELECT ''sga'', ''Shop Goods Arrival''
UNION ALL
SELECT ''C'', ''Contra''
UNION ALL
SELECT ''SAI'', ''Shop Service Invoice''
UNION ALL
SELECT ''SPI'', ''Shop Special Invoice''
UNION ALL
SELECT ''COST'', ''Costing''
UNION ALL
SELECT ''hqswo'', ''HQ Stock WriteOff''
UNION ALL
SELECT ''EXC'', ''Goods Exchange''
UNION ALL
SELECT ''P'', ''HQ Payments''
UNION ALL
SELECT ''ispd'', ''Special Despatch To Shop''
UNION ALL
SELECT ''iga'', ''Godown Goods Arrival''
UNION ALL
SELECT ''J'', ''Journal''
UNION ALL
SELECT ''R'', ''HQ Receipt''
UNION ALL
SELECT ''strout'', ''Transfer Out''
UNION ALL
SELECT ''invdts'', ''Despatch To Shop''
UNION ALL
SELECT ''gdntogdn'', ''Godown To Godown Transfer''
UNION ALL
SELECT ''sdtog'', ''Shop To Godown Tranfer''
UNION ALL
SELECT ''posrec'', ''Shop Recovery''
UNION ALL
SELECT ''isrec'', ''Godown Recovery''
UNION ALL
SELECT ''SB'', ''Service Booking''
UNION ALL
SELECT ''SB'', ''Service Booking''
UNION ALL
SELECT ''SBI'', ''Service Booking Invoice''
UNION ALL
SELECT ''POSDCN'', ''Shop Debit Credit Note''
UNION ALL
select ''sintpur'', ''Inter division Purchase''
UNION ALL
select ''sintsale'', ''Inter division Sales''
UNION ALL
SELECT ''sdep'', ''Agreement''
UNION ALL
--dheena add this query
SELECT ''UTB'',''Utility Billing''
UNION ALL
SELECT ''PO'', ''Purchase Order''
union all
SELECT ''CHOR'',''Apartment Check Out''
union all
select ''RBI'', ''Room Billing''
union all
select ''AST'', ''Fixed Asset Register''
union all
select ''invascnv'', ''Asset Conversion''
union all
select ''PAY'', ''Payroll Accounts Posting''
union all
select ''ASTR'', ''Asset Transfer''
union all
select ''ASD'', ''Asset Disposal''
union all
select ''ASDP'', ''Depreciation''
union all
select ''RE'', ''Export Invoice''
union all
select ''HQPCP'', ''Petty Cash Payments''
union all
select ''scon'', ''Inhouse Consumption''
union all
select ''pcret'', ''HQ Purchase Return''
union all
select ''sret'', ''Shop Purchase Return''
union all
select ''invret'', ''Godown Purchase Return''
union all
select ''HPI'', ''HP Shop Invoice''
union all
select ''HPP'', ''HP HQ Payments''
union all
select ''HPR'', ''HP HQ Receipts''
union all
select ''HPSR'', ''HP Shop Receipts''
union all
select ''HPSRPOS'', ''HP Repossession/Termination''
union all
select ''HPSRES'', ''HP ReSale''
union all
select ''HPSDP'', ''HP Down Payment''
union all
select ''BP'', ''Business Promotion''
union all
select ''WC'', ''Warrenty Claim'''
GO
/****** Object:  View [dbo].[vwOpeningStockValue]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOpeningStockValue]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- view Created  for automatically populating the opening balance w.r.t the figures
-- entered in system thru opening stock
--MODIFIED BY : hariharan
-- date	      : 22/07/2003
--COmments    : Removed the references of lossettings and loisettings for openingstockdate
--reference like v2
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
-------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwOpeningStockValue] AS
select 0 stockvalue, '''' departmentname, 0 departmentid
/*select sum(sval.stkvalue) stockvalue, sval.departmentname, sval.departmentid from
(Select sum(gsopeningstock*cdCostingPrice) stkvalue, departmentname, dm.departmentid
from  agodown a, moigodownstock gs, loacostingdetail cd,
adepartmentmaster dm
where a.godownid = gsgodownid
and gsitemid = cd.cditemid
and a.departmentid = dm.departmentid
and a.companyid = dm.companyid
and cdcostingid = 0
and gsopeningstock > 0
group by departmentname,  dm.departmentid
union all
Select sum(openingstock*cdCostingPrice) stkvalue, departmentname, dm.departmentid from
ashops a, mosshopstock gs, loacostingdetail cd, adepartmentmaster dm
where a.shopid = gs.shopid
and gs.itemid = cd.cditemid
and a.departmentid = dm.departmentid
and a.companyid = dm.companyid
and cdcostingid = 0
and openingstock > 0
group by departmentname, dm.departmentid ) sval
group by departmentname, departmentid*/'
GO
/****** Object:  StoredProcedure [dbo].[spLCRegister]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegister]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spLCRegister 1,1,''20030101'',''20030531'',0,0,''n''
------------------------------------------------------------------------
--Created on 	: 25/05/2003
--Created by	: R Harikrishnan
--Comments	: For LC Register
------------------------------------------------------------------------
CREATE  procedure [dbo].[spLCRegister]
	@intCompanyID		as int,
	@strFromDate 		as varchar(8),
	@strToDate		as varchar(8),
	@intVendorID		as int=0,
	@intAccountID	 	as int=0,
	@strType		as char(1)=''D'',--If passing ''N'' date Range will not be considered
	@intDepartmentID	as int=0
as
declare @strSql as nVarchar(3000)
set @strSql=N''select
	ph.pohpono, ph.pohPodate, vm.VendorName, vcm.Symbol VenCurr,
	lcm.Symbol LCMarginCurr,lcm.AccountDesc LCMarginAccount,
	Avg(pohLCAmount) LCAmount, sum(pd.podQty * pd.podUnitPrice) POAmt
from
	loPurchaseOrderHeader ph Left outer join
	(select
		am.CompanyID, am.AccountID,am.AccountDesc,cm.currencyName,cm.Symbol
	from
		aAccountMaster am,aCurrencyMaster cm
	where
		am.CompanyID=cm.companyID and am.currencyID=cm.currencyID and
		am.CompanyID=1) lcm
	on ph.pohcompanyid=lcm.companyID and ph.pohPurchaseAccountid=lcm.accountID,
	loPurchaseOrderDetail pd,aVendorMaster vm,aCurrencyMaster vcm
where
	ph.pohPoid=pd.podPoid and ph.pohVendorID=vm.VendorID and
	ph.pohcompanyid=vm.CompanyID and
	vm.CompanyID=vcm.companyID and vm.currencyID=vcm.currencyID and
	ph.pohcompanyid=1 and ph.pohLcOpened=1 and ph.pohCompanyID='' +
	convert(varchar(10),@intCompanyID)
if @intDepartmentID>0
	set @strSql=@strSql + N'' and ph.pohDepartmentID='' +
		convert(varchar(10),@intDepartmentID)
if @intVendorID>0
	set @strSql=@strSql + N'' and ph.pohVendorID='' +
		convert(varchar(10),@intVendorID)
if @intAccountID>0
	set @strSql=@strSql + N'' and ph.pohPurchaseAccountid='' +
		convert(varchar(10),@intAccountID)
if @strType<>"N"
		set @strSql=@strSql + N'' and ph.pohPodate between "'' + @strFromDate +
		N''" and "'' + @strToDate + ''"''
set @strSQl=@strSQl + N'' group by
	ph.pohPoid,ph.pohpono, ph.pohPodate, vm.VendorName,
	vcm.Symbol, lcm.AccountDesc,lcm.Symbol''
exec sp_executesql @strSql' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSum]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDaySalesShopWise]    Script Date: 10/06/2012 14:17: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].[spDaySalesShopWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spDaySalesShopWise ''20080101'',''20090101'',''TO'',1,0,''1,2,3,4''
CREATE proc [dbo].[spDaySalesShopWise]   @strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitShopwise as bit =1, @intDepartmentID as int=0  , @intShopID as varchar(20) =''''  as
set nocount on
begin  --begin of sp
declare @strSql as nvarchar(1000)
declare @mindate as datetime
declare @strShopCond  as varchar(100)
CREATE table #daySales ( days varchar(20), billdate datetime , ShopName varchar(100),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2))
if @intShopID<>''''
	set @strShopCond= '' and  vsa.shopid  in (''+ @intShopID + '')''
else
	set @strShopCond=''''
if @strType = ''CA''
begin
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
vsa.cash = 1 and s.ShopID= vsa.shopid and  billdate between '''''' +
@strFromDate + ''''''  and '''''' + @strToDate + '''''''' +  @strShopCond
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount,
camount from vwSalesAnalysisByYear vsa , adepartmentmaster d where
vsa.cash = 1 and d.departmentID= vsa.departmentid and  billdate between '''''' +
@strFromDate + ''''''  and '''''' + @strToDate + ''''''''
end
else if @strType = ''CR''
begin
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''  +  @strShopCond
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''
end
else if @strType = ''TO''
begin
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate + ''''''  and '''''' +
@strToDate + ''''''''  +  @strShopCond
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
d.departmentiD= vsa.departmentid and  billdate between '''''' + @strFromDate + ''''''  and '''''' +
@strToDate + ''''''''
end
if (@bitShopwise =1 and @intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
if (@bitShopwise =0 and @intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
set @strsql  =  @strsql +  N'' OPTION (MAXDOP 1)''
insert into #daySales exec sp_executesql  @strSql
declare curmindate cursor for
select min(billdate) from #daysales
open curmindate
fetch next from curmindate into @mindate
update   #daySales  set days =  cast (  datediff(dd, cast( @strFromdate as
datetime),billdate ) + 1   as varchar)
close curmindate
deallocate curmindate
select * from #daySales    order by billdate ,ShopName
set nocount off
end ----end of sp' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGdnNonMovingItems]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGdnNonMovingItems]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDaySales]    Script Date: 10/06/2012 14:17: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].[spDaySales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 31/05/2003
--Modified by  : leo
--Verified By  : Hariharan
--Verified Date : 30/04/2004(updated from Devl Db)
--Comments  : v3
--   :
--spDaySales ''20070101'',''20090101'',''TO'',1,1
------------------------------------------------------------------------------------------
-- Modified by : Bijesh.B
-- Date        : 02/07/2011
-- RefNo       : RefNo-2
-- Comments    : PD Cheque feature added
--  exec spWeekSales ''20080707'',''20080707'',''pd'',1,0,1
------------------------------------------------------------------------------------------
CREATE proc [dbo].[spDaySales]  @strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitShopwise as bit =1, @intDepartmentID as int=0   as
set nocount on
begin  --begin of sp
declare @strSql as nvarchar(1000)
declare @mindate as datetime
create table #daySales ( days varchar(20), billdate datetime , ShopName varchar(100),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2))
if @strType = ''CA''
begin
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
vsa.cash = 1 and s.ShopID= vsa.shopid and  billdate between '''''' +
@strFromDate + ''''''  and '''''' + @strToDate + ''''''''
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount,
camount from vwSalesAnalysisByYear vsa , adepartmentmaster d where
vsa.cash = 1 and d.departmentID= vsa.departmentid and  billdate between '''''' +
@strFromDate + ''''''  and '''''' + @strToDate + ''''''''
end
else if @strType = ''CR''
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
transtype <> ''''PD CHEQUE'''' and
vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
transtype <> ''''PD CHEQUE'''' and
vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''
end
--RefNo-2 start --------------------------------------------------------
--PD Cheque Amount only
else if @strType = ''PD''
begin
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
transtype = ''''PD CHEQUE'''' and
vsa.cash = 0 and s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
transtype = ''''PD CHEQUE'''' and
vsa.cash = 0 and d.departmentID= vsa.departmentid and  billdate between '''''' + @strFromDate +
''''''  and '''''' + @strToDate + ''''''''
end
--RefNo-2 ends --------------------------------------------------------
else if @strType = ''TO''
begin
--RefNo-2 added -> transtype <> ''''PD CHEQUE'''' and
if (@bitshopwise = 1)
set  @strSql = N'' Select ''''day'''' , billdate  , ShopName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , ashops S where
transtype <> ''''PD CHEQUE'''' and
s.ShopID= vsa.shopid and  billdate between '''''' + @strFromDate + ''''''  and '''''' +
@strToDate + ''''''''
else
set  @strSql = N'' Select ''''day'''' , billdate  , departmentName , actamount, damount, camount from
vwSalesAnalysisByYear vsa , adepartmentmaster d where
d.departmentiD= vsa.departmentid and  billdate between '''''' + @strFromDate + ''''''  and '''''' +
@strToDate + ''''''''
end
if (@bitShopwise =1 and @intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
if (@bitShopwise =0 and @intdepartmentid > 0)
set  @strSql = @strSql + N'' and vsa.departmentid='' + convert(varchar(5),@intDepartmentID)
set @strsql  =  @strsql +  N'' OPTION (MAXDOP 1)''
insert into #daySales exec sp_executesql  @strSql
declare curmindate cursor for
select min(billdate) from #daysales
open curmindate
fetch next from curmindate into @mindate
update   #daySales  set days =  cast (  datediff(dd, cast( @strFromdate as
datetime),billdate ) + 1   as varchar)
close curmindate
deallocate curmindate
select * from #daySales    order by billdate ,ShopName
set nocount off
end ----end of sp' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAccoutReceivableAudit]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAccoutReceivableAudit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- CREATED BY   : PRASANTH JOSEPH
-- CREATED ON   : 29/07/2009
-- CREATED FOR  : TO GET INVOICE BETWEEN TWO PERIOD AND ITS SETTLEMENTS.
-----------------------------------------------------------------------------
-- spAccoutReceivableAudit ''20070419'',''20070419'','''',2,0,'''',''''
CREATE PROCEDURE [dbo].[spAccoutReceivableAudit] (@dtstartdate varchar(11),@dtinvdate as varchar(11),
@intcustid varchar(1000),@intdepartid int,@intShopID int=0 ,
@strCatName as Varchar(30)='''', @strGroupName as Varchar(30)='''' )
as
set ansi_Warnings off
set nocount on
begin
--declare @intcustid  as varchar(50)
--declare @intdepartid as varchar(50)
--declare @intShopID as int
--declare @strCatName as varchar(50)
--declare @strGroupName as varchar(50)
--set @intcustid=''''
--set @intdepartid=0
--set @intShopID=0
--set  @strCatName=''''
--set @strGroupName=''''
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(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)
declare @strsettled as varchar(20)
declare @strnotsettled as varchar(20)
SET @strsettled=''Settled''
SET @strnotsettled=''Not Settled''
SET @SettleCustId = ''''
set @Invcustid = ''''
set @strShop = ''''
set @strCatCond=''''
set @strGroupCond=''''
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 *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpInvoices
Select *,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 vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) + ''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwsettlements'' --where '' + @SettleCustId +
--'' settleddate <=getdate()''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) + ''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwsettlements'' --where '' + @SettleCustId +
--'' settleddate <=getdate()''
End
exec sp_Executesql @strquery
set @strquery = ''SELECT  #tmpInvoices.invoiceid,
aCustomerMaster.Dueperiod,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,#tmpInvoices.duedate,
#tmpInvoices.invoiceno,vwsettlements.ReceiptNo,vwsettlements.settleddate,
max(invamt) invamt,SumSettled.Totalsettleamt Totalsettleamt,vwsettlements.settledamt,
case when  vwsettlements.settledamt > 0
then cast(datediff(dd,#tmpInvoices.duedate,vwsettlements.settleddate) as varchar)
when  isnull(vwsettlements.settledamt,0)=0  then ''''''+@STRNOTSETTLED+'''''' end  SettledOverdueage,
#tmpInvoices.type,remarks,customername,PhoneNo,currencyname,symbol,
case when max(#tmpInvoices.invamt)>isnull(vwsettlements.settledamt,0) then
cast(datediff(dd,#tmpInvoices.duedate, '''''' + @dtinvdate + '''''' )as varchar(20)) else ''''''+@STRSETTLED+'''''' end overduedays,
aCustomerMaster.CustomerCategory ,#tmpInvoices.CompanyID 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
INNER JOIN (
SELECT #tmpInvoices.invoiceid,#tmpInvoices.customerID,isnull(sum(settledamt),0) Totalsettleamt
FROM  #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
GROUP BY #tmpInvoices.invoiceid,#tmpInvoices.customerID
) SumSettled
ON  #tmpInvoices.invoiceid=SumSettled.invoiceid and #tmpInvoices.customerID=SumSettled.customerID
,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,invoiceno,invoicedate ,#tmpInvoices.customerid,#tmpInvoices.departmentid,
aCustomerMaster.Dueperiod, #tmpInvoices.shopid,due
,#tmpInvoices.type,remarks,
customername,currencyname,symbol, #tmpInvoices.duedate,
address1, address2, address3, #tmpInvoices.referenceno,
debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,vwsettlements.ReceiptNo,
vwsettlements.settleddate,vwsettlements.settledamt,#tmpInvoices.CompanyID ,PhoneNo,SumSettled.Totalsettleamt
--having max(invamt) <> sum(isnull(settledamt,0))''
exec sp_Executesql @strquery
drop table #tmpInvoices
drop table #tmpSettlements
end
set nocount off
set ansi_Warnings on' 
END
GO
/****** Object:  StoredProcedure [dbo].[spcompstockout]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcompstockout]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spcompstockout
--sp_helptext spcompstockout
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spcompstockout '''' ,0
--Last Modified on  : 11/12/02 ,06/07/2007
--Modified by   : leo,shinu(Added UnitName)
--Verified By   : Hariharan
--Verified Date  : 30/04/2004
--Comments  : v3, updated from Devl Db
CREATE proc [dbo].[spcompstockout] (@strcategory as varchar(500) ,@intdeptid as int=0 ) as
declare @strsql as nvarchar(4000)
declare @strdepcondition as varchar(100)
begin
set @strdepcondition= '' and dep.departmentid=''+convert(varchar(3),@intdeptid)+''''
if ltrim(rtrim(@strcategory)) <>''''
begin
set @strcategory = '' ('' + @strcategory + '') ''
set @strsql = N''select cstout.categorynamedescription, cstout.itemdescription, cstout.itemid,
isnull(cstout.stock,0) stock, cstout.reorderlevel, cstout.reorderquantity, cstout.itemcategoryid,
cstout.colorname, cstout.sizename, cstout.active, poqty, itemcode, brand ,UnitName
from (select ic.categorynamedescription, a.itemdescription, a.itemid, isnull(stock,0) stock, a.reorderlevel,
a.reorderquantity, a.itemcategoryid, isnull(colorname,'''''''') colorname,
isnull(sizename,'''''''') sizename,active, isnull(poqty,0) poqty, itemcode, brand ,UnitName
from aitem a
left outer join aUnit au on a.unitsID=au.UnitID
left outer join acolor cr on a.colorid= cr.colorid
left outer join asize z on a.sizeid=z.sizeid
left outer join vwsellingtotalstock vs on a.itemid = vs.itemid
left outer join vwitemorderedinpo on a.itemid = poditemid,
vwDepWiseItems dep,
aitemcategory ic where ic.itemcategoryid=a.itemcategoryid and a.active=1 and
a.itemid=dep.itemid and
a.onetimeshipment=0 and ic.itemcategoryid in '' + @strcategory + @strdepcondition +'') cstout
where isnull(cstout.stock,0)  <=cstout.reorderlevel and cstout.reorderlevel>=0''
--print  @strsql
exec sp_Executesql @strsql
end
else
begin
set @strsql= ''select cstout.categorynamedescription, cstout.itemdescription, cstout.itemid,
isnull(cstout.stock,0) stock, cstout.reorderlevel, cstout.reorderquantity,
cstout.itemcategoryid, cstout.colorname, cstout.sizename, cstout.active, poqty ,itemcode, brand ,UnitName
from (select ic.categorynamedescription, a.itemdescription, a.itemid, isnull(stock,0) stock,
a.reorderlevel, a.reorderquantity, a.itemcategoryid,
isnull(colorname,'''''''') colorname,
isnull(sizename,'''''''') sizename,active, isnull(poqty,0) poqty, itemcode, brand,UnitName
from aitem a
left outer join aUnit au on a.unitsID=au.UnitID
left outer join acolor cr on a.colorid= cr.colorid
left outer join asize z on a.sizeid=z.sizeid
left outer join vwsellingtotalstock vs on a.itemid = vs.itemid
left outer join vwitemorderedinpo on a.itemid = poditemid,
aitemcategory ic, vwDepWiseItems dep  where ic.itemcategoryid=a.itemcategoryid and a.active=1
and  a.itemid=dep.itemid and a.onetimeshipment=0'' + @strdepcondition +'' ) cstout
where isnull(cstout.stock,0)  <= cstout.reorderlevel and cstout.reorderlevel>=0''
-- print  @strsql
exec sp_Executesql @strsql
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardBadQtySummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwShopBincardBadQtySummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwShopBincardBadQtySummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
-- spMag_GenerateVwShopBincardBadQtySummary ''20091231''
CREATE PROC [dbo].[spMag_GenerateVwShopBincardBadQtySummary]
@strSummaryDate as varchar(8)
AS
BEGIN
EXEC (
''IF EXISTS ( SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V'''' AND NAME=''''vwShopBincardBadQtySummary'''')
DROP VIEW vwShopBincardBadQtySummary'')
EXEC (
''-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwShopBincardBadQtySummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwShopBincardBadQty.
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- ===============================================
CREATE VIEW vwShopBincardBadQtySummary AS
--stock verification add
select svdshopid shopid, svdItemid itemid, svhDate sdate, NULL transid, NULL transno,
svdVerifiedbadStock-svdAvailbadStock badtransqty,
''''Bad Verification Plus'''' [Type], 1 mode, NULL updatetime
from losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 and svhDate>''''''+@strSummaryDate+''''''
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,
wd.wdWriteoffQty, ''''Write off'''', 1 mode, NULL
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and wh.whType=''''W''''
and wh.whdate>''''''+@strSummaryDate+''''''
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, NULL, NULL,
Pd.wdPurchaseReturnQty, ''''Purchase Return'''', 1 mode, NULL
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whType=''''P''''
and Ph.whdate>''''''+@strSummaryDate+''''''
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, NULL, NULL,
svdAvailbadStock-svdVerifiedbadStock,
''''Bad Verification Minus'''', -1 mode, NULL
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock < svdAvailbadStock
and svhCancelled=0 and svhDate>''''''+@strSummaryDate+''''''
union all
--damage cleared
select dcdShopid, dcdItemID, dchClearingDate, NULL, NULL,
dcdWriteOffQty, ''''Damage Cleared'''', -1 mode, NULL
from LOsShopDamageClearingHeader, LOsShopDamageClearingdetails
where dchClearingID = dcdClearingID and dchShopid = dcdShopid
and dchcancelled = 0 and dchClearingDate>''''''+@strSummaryDate+'''''''')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardAuditSummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwShopBincardAuditSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwShopBincardAuditSummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
-- Referenc No  : Ref-No1
-- Modified by	: MANUNADH.U
-- Modified on	: 26/03/2012
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ===============================================
CREATE PROC [dbo].[spMag_GenerateVwShopBincardAuditSummary]
@strSummaryDate as varchar(8)
AS
BEGIN
-- Since a variable cannot store more than 8000 chars,
-- the query is directly executed using EXEC command.
EXEC (
''IF EXISTS ( SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V'''' AND NAME=''''vwShopBincardAuditSummary'''')
DROP VIEW vwShopBincardAuditSummary'')
EXEC (
''-- =============================================================================
-- This view was automatically generated
-- by spMag_GenerateVwShopBincardAuditSummary.
-- Alter above proc to make any change in this view.
-- =============================================================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwShopBincardAudit.
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- =============================================================================
CREATE VIEW vwShopBincardAuditSummary AS
SELECT h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,
NULL TransNo, NULL TransId,
d.gadItemGoodQuantityArrived TransQty,
''''Arrival From Godown'''' [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,
NULL DepCostPrice, NULL ConCostPrice
FROM losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d
WHERE h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1 and h.gaharrivaldate>''''''+@strSummaryDate+''''''
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
UNION ALL
SELECT grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate,
NULL, NULL, GRNDQuantity, ''''Goods Return'''', 1 as mode,
NULL, NULL, NULL, NULL
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0 and GrnhGoodsreturnnoteDate>''''''+@strSummaryDate+''''''
union all
--transfer in
select h.tihshopid,  d.tiditemid, h.tihdate, NULL, NULL,
d.TIDrecievedgoodqty, ''''Transfer In'''', 1 mode,
NULL, NULL, NULL, NULL
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
and h.tihdate>''''''+@strSummaryDate+''''''
union all
--recovery add
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.sraddstock) as recAdd, ''''Recovery Plus'''', 1 Mode,
NULL, NULL, NULL, NULL
from
losstockrecovery sr
where sr.srdate>''''''+@strSummaryDate+''''''
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock as svAddQty,
''''Verification Plus'''', 1 mode, NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''''t''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--TOTAL stock verification add
select svdshopid, svdItemid, svhDate, svhno, svhid,
svdVerifiedStock-svdAvailStock as svAddQty,
''''Verification Plus'''', 1 mode, NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''''tc''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--exchange in
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,
sedExchangeQty, ''''Exchanged In'''',1 mode, NULL, NULL, NULL, NULL
FROM losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''''B'''' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
and sehExchangeDate>''''''+@strSummaryDate+''''''
union all
--local purchase
select lphShopid,lpditemid,lphbilldate,NULL,NULL,lpdItemQuantity,''''Local Purchase'''',1 mode,NULL,NULL,NULL,NULL
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphbilldate>''''''+@strSummaryDate+''''''
	and lphConfirmed=1--<<Ref-No1>>
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,
wd.wdWriteoffQty, ''''Write off'''', -1 mode, NULL, NULL, NULL, NULL
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
and wh.whdate>''''''+@strSummaryDate+''''''
union all
--Deapatch
select dd.dgdshopid, dd.dgditemid, dh.dghDate, NULL, NULL,
dd.dgddespatchedgoodqty, ''''Despatch To Godown'''' TYpe, -1 mode,
NULL, NULL, NULL, NULL
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
and dh.dghDate>''''''+@strSummaryDate+''''''
union all
--Transferout
select todshopid, toditemid, tohDate, NULL, NULL,
todissuedgoodqty, ''''Transfer Out'''',-1 mode, NULL, NULL, NULL, NULL
from mestransferoutheader , mestransferoutdetail  where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
and tohDate>''''''+@strSummaryDate+''''''
union all
--recovery minus
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.srdedstock) as recAdd, ''''Recovery Minus'''',-1 Mode,
NULL, NULL, NULL, NULL from
losstockrecovery sr
where sr.srdate>''''''+@strSummaryDate+''''''
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid
having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdAvailStock-svdVerifiedStock, ''''Verification Minus'''', -1 mode,
NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''''t''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--Total stockverification minus
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdAvailStock-svdVerifiedStock, ''''Verification Minus'''', -1 mode,
NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''''tc''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--pos sales
select poshShopID, posditemid, poshBilldate, NULL, NULL,
posdquantity, ''''Cash Sales'''', -1 mode, NULL, NULL, NULL, NULL
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
and poshBilldate>''''''+@strSummaryDate+''''''
union all
--credit invoice
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,
idquantity, ''''Credit Sales'''', -1 mode, NULL, NULL, NULL, NULL
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''''I''''
and ihInvoicedate>''''''+@strSummaryDate+''''''
union all
--exchange out
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,
sedquantity, ''''Exchange Out'''', -1 mode, NULL, NULL, NULL, NULL
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''''E'''' and SEHCANCELLED=0
and sehExchangeDate>''''''+@strSummaryDate+''''''
union all
--special invoice return to shop
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,
-reqqty, ''''Special Invoice Return'''', 1 mode, NULL, NULL, NULL, NULL
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
and ihInvoicedate>''''''+@strSummaryDate+''''''
union all
select serinvhShopid, repinvdpartsid, serinvhdate, NULL, NULL,
repinvdqty, ''''Parts Replaced'''', -1 as mode, NULL, NULL, NULL, NULL
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
and serinvhdate>''''''+@strSummaryDate+''''''
union all
--Re-Exporting
select rehShopID, reditemid,  rehExportDate, NULL, NULL,
redquantity, ''''Re-Export'''', -1 mode, NULL, NULL, NULL, NULL
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''''I''''
and rehExportDate>''''''+@strSummaryDate+''''''
union all
--MerGing minus
select lsdShopID, lsdItemID, lshDate, NULL, NULL,
sum(lsdqty), ''''Merging Deduct'''', -1 as mode, NULL, NULL, NULL, NULL
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopid = mh.lshShopId
and lshCancelled=0
and lshDate>''''''+@strSummaryDate+''''''
group by lsdShopID, lsdItemID, lshDate, lshid
Having Sum(lsdQty) <> 0
union all
--MerGing Add
select lsdShopID, lshItemID, lshDate, NULL, NULL,
sum(lsdqty), ''''Merging Add'''', 1 as mode, NULL, NULL, NULL, NULL
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopID = mh.lshShopid
and lshCancelled = 0
and lshDate>''''''+@strSummaryDate+''''''
group by lsdShopID, lshItemID, lshDate, lshid
Having Sum(lsdQty) <> 0
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate, NULL, NULL,
Pd.wdPurchaseReturnQty, ''''Purchase Return'''', -1 mode, NULL, NULL, NULL, NULL
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1
and Ph.whdate>''''''+@strSummaryDate+''''''
union all
--Warrenty Claim/Business promotion
select wchShopID, wcditemid, wchdate, NULL, NULL,
wcdQty, ''''WC/BP'''', -1 mode, NULL, NULL, NULL, NULL
from losWarrentyClaimDetail,losWarrentyClaimHeader
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0
and wchdate>''''''+@strSummaryDate+''''''
union all
-----Hire Purchase Invoice
select hpqhShopid,hpqdItemId,hpqhQuotationDate, NULL, NULL,
1 as Qty, ''''Hire Purchase'''', -1 mode, NULL, NULL, NULL, NULL
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''''I''''
and hpqhQuotationDate>''''''+@strSummaryDate+'''''''')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryShopStockSummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwInquiryShopStockSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- spMag_GenerateVwInquiryShopStockSummary ''20100101''
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwInquiryShopStockSummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
CREATE PROC [dbo].[spMag_GenerateVwInquiryShopStockSummary]
@strSummaryDate as varchar(8)
AS
BEGIN
DECLARE @strQuery1 AS VARCHAR(4000);
DECLARE @strQuery2 AS VARCHAR(4000);
SET @strQuery1 =
''IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V'''' AND NAME=''''vwInquiryShopStockSummary'''')
DROP VIEW vwInquiryShopStockSummary''
SET @strQuery2 =
''-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwInquiryShopStockSummary.
-- Alter spMag_GenerateVwInquiryShopStockSummary
-- to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 22-07-2010
-- Description :
--    To compute shop stock using transactions summary.
--    This view is created based on vwInquiryShopStock.
--    Shop Transactions Summary part is additionally added.
-- ===============================================
CREATE VIEW vwInquiryShopStockSummary AS
SELECT
ShopId, ItemId, convert(numeric(18,3), sum(stock)) Stock
, sum(badstock) BadStock, sum(openingstock) OpeningStock
, sum(openingbadstock) OpeningBadStock, 1 ShipmentId
, max(itemcostprice) ItemCostPrice
FROM (
-- 1. Shop Transactions Summary
SELECT
ShopId, ItemId, Stock, BadStock, OpeningStock
, OpeningBadStock, ItemCostPrice
FROM losShopTransactionsSummary
UNION ALL
-- 2. Opening Stock
SELECT
shopid, itemid, openingstock stock, isnull(openingbadstock,0) badstock
, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
, itemcostprice
FROM mosshopstock
WHERE openingstock>'''''' + @strSummaryDate + ''''''
UNION ALL
-- 3. Shop Bin Card For Good Stock
SELECT
shopid,itemid, transqty * mode stock, 0
, 0, 0, 0
FROM vwShopBincardAuditSummary
-- 4. Shop Bin Card For Bad Stock
UNION ALL
SELECT
shopid,itemid,  0,  badtransqty * mode badstock
, 0, 0, 0
FROM vwShopBincardBadQtySummary
) inqstock
GROUP BY shopid, itemid ''
EXEC (@strQuery1)
EXEC (@strQuery2)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryGodownStockSummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwInquiryGodownStockSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwGdnBinCardBadQtySummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
-- spMag_GenerateVwInquiryGodownStockSummary ''20091231''
CREATE PROC [dbo].[spMag_GenerateVwInquiryGodownStockSummary]
@strSummaryDate as varchar(8)
AS
BEGIN
-- Since a variable cannot store more than 8000 chars,
-- the query is directly executed using EXEC command.
EXEC (
''IF EXISTS ( SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V'''' AND NAME=''''vwInquiryGodownStockSummary'''')
DROP VIEW vwInquiryGodownStockSummary'')
EXEC (
''-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwInquiryGodownStockSummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 28-07-2010
-- Description :
--   To compute godown stock using transactions summary.
--    This view is created based on vwInquiryGodownStock.
--    Godown Transactions Summary part is additionally added.
-- ===============================================
CREATE VIEW vwInquiryGodownStockSummary AS
SELECT
GodownId gsGodownId, ItemId gsItemId
, isnull(convert(numeric(18,3), sum(stock)),0) gsStock
, sum(badstock) gsBadStock, sum(openingstock) gsOpeningStock
, sum(openingbadstock) gsOpeningBadStock
, 1 gsShipmentId, 1 gsLocationId
, max(itemcostprice) gsItemCost
FROM (
-- 1. Godown Transactions Summary
SELECT
GodownId, ItemId, Stock, BadStock
, OpeningStock, OpeningBadStock, ItemCostPrice
FROM loiGodownTransactionsSummary
UNION ALL
-- 2. Opening Stock
SELECT  gsgodownid, gsitemid
, gsopeningstock gsstock, isnull(gsopeningbadstock,0) gsbadstock
, isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost
FROM moigodownstock
WHERE gsStockDate>''''''+@strSummaryDate+''''''
UNION ALL
-- 3. Godown Bin Card For Good Stock
SELECT godownid, itemid, transqty * mode gsstock, 0
, 0, 0, 0
FROM vwGdnBincardSummary
UNION ALL
-- 4. Godown Bin Card For Bad Stock
SELECT godownid, itemid, 0, badtransqty * mode gsbadstock
,0, 0, 0
FROM vwGdnBincardBadQtySummary
) inqstock
GROUP BY godownid, itemid'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardSummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwGdnBinCardSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwGdnBinCardSummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
-- spMag_GenerateVwGdnBinCardSummary ''20091231''
CREATE PROC [dbo].[spMag_GenerateVwGdnBinCardSummary]
@strSummaryDate as varchar(8)
AS
BEGIN
DECLARE @strQuery1 AS VARCHAR(4000);
SET @strQuery1 =
''IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V''''
AND NAME=''''vwGdnBinCardSummary'''')
BEGIN
DROP VIEW dbo.vwGdnBinCardSummary
END''
EXEC (@strQuery1)
-- Since the query has more than 8000 chars, the query cannot be stored into a variable.
-- So the query is directly executed using EXEC command.
EXEC (
''-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwGdnBinCardSummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwGdnBinCard
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- ===============================================
CREATE VIEW dbo.vwGdnBinCardSummary AS
--arrival from hq
select ad.adgodownid Godownid, ad.aditemid ItemId, ah.ahArrivaldate GDate,
NULL TransId, NULL TransNo,
ad.adReceivedQty * pk.quantity * counts TransQty ,
''''Shipment Arrival'''' as [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,
NULL DepCostPrice, NULL ConCostPrice
from  loiarrivalheader ah, loiarrivaldetail ad,
aitem ai, aPackingTypeCapacityDetail pk, aunit u
where ah.ahcancelled=0 and ah.ahtransfinished=1 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 ai.unitsid = u.unitid
and ah.ahArrivaldate>''''''+@strSummaryDate+''''''
union all
--Transfer in from shop or godown
select  gal.asdGodownID, gal.asdItemId, ah.ahArrivaldate, NULL,
NULL, gal.asdReceivedGoodQty, ''''Transfer In'''', 1 mode, NULL, NULL, NULL, NULL
from loiarrivalheader ah, loiArrivalShipmentDetail gal
where ah.aharrivalid = gal.asdArrivalID and
ah.ahlocalgodownid = gal.asdGodownId and ah.ahcancelled = 0 and ah.ahtransfinished = 1
and ah.ahArrivaldate>''''''+@strSummaryDate+''''''
union all
--recovery add
select sr.srgodownid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.sraddstock), ''''Recovery Plus'''', 1 mode, NULL, NULL, NULL, NULL
from loistockrecovery sr
where sr.srdate>''''''+@strSummaryDate+''''''
group by sr.srgodownid, sr.srid, sr.srdate,  sr.sritemid
having isnull(sum(sr.sraddstock),0) >0
union all
--itemsplitting adding
select isdgodownid, isditemid, ishdate, NULL, NULL, isdqty,
''''Splitting Add'''', 1 as mode, NULL, NULL, NULL, NULL
from LoiItemSplitDetail sd Left Outer Join (Select scfhItemSplitId,
scfhGodownId, scfdItemId, scfdCostprice
From loaItemSplitCostingDetail scfd, loaItemSplitCostingHeader scfh
Where scfhId = scfdId
And scfhCancelled = 0) scf
On sd.isdItemId = scf.scfdItemID
And sd.isdId = scf.scfhItemSplitId
And sd.isdGodownId = scf.scfhGodownid, LoiItemSplitheader sh, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=
sh.ishgodownid and sh.ishcancelled=0 and sd.isdIteMId = i.itemId
and ishdate>''''''+@strSummaryDate+''''''
union all
--write off
select wd.wdGodownid RGId, wd.wditemid RItemID, wh.whDate RDate,
NULL, NULL, wd.wdWriteoffQty, ''''Write Off'''', -1 mode, NULL, NULL, NULL, NULL
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid=wd.wdid and wh.whgodownid=wd.wdgodownid and wh.whcancelled=0
and wh.whDate>''''''+@strSummaryDate+''''''
union all
--Deapatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, NULL, NULL,
dd.dditemgoodqty, ''''Despatch To Shop'''', -1 mode, NULL, NULL, NULL, NULL
from meidespatchtoshopheader dh, meidespatchtoshopdetail dd
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0
and dhtransfinished = 1 --added for new concept (hari 021019)
and dh.dhDespatchDate>''''''+@strSummaryDate+''''''
union all
-- special despatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, NULL, NULL,
dd.dditemgoodqty, ''''Special Despatch'''', -1 mode, NULL, NULL, NULL, NULL
from meispecialdespatchtoshopheader dh, meispecialdespatchtoshopdetail dd
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0
and dh.dhDespatchDate>''''''+@strSummaryDate+''''''
union all
--Transferout
select gtdGodownid, gtditemid, gthDespatchDate, NULL, NULL,
gtdItemGoodQty, ''''Transfer Out'''', -1 mode, NULL, NULL, NULL, NULL
from meigodowntransferheader, meigodowntransferdetail
where gthdespatchid = gtddespatchid
and gthFromGodownid = gtdgodownid
and gthCancelled = 0
and gthtransfinished = 1 --added for new concept (hari 021019)
and gthDespatchDate>''''''+@strSummaryDate+''''''
union all
--recovery minus
select sr.srgodownid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.srdedstock), ''''Recovery Minus'''' as type, -1 mode, NULL, NULL, NULL, NULL
from loistockrecovery sr
where sr.srdate>''''''+@strSummaryDate+''''''
group by sr.srgodownid, sr.srid, sr.srdate, sr.sritemid
having isnull(sum(sr.srdedstock),0) >0
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock, ''''Verification Plus'''' as Type, 1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid
and svdVerifiedStock > svdAvailStock
and svhCancelled=0  and left(svhFutureVc, 1) <> ''''t''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--stockverification minus
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdAvailStock - svdVerifiedStock, ''''Verification Minus'''', -1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
and svhCancelled = 0    and left(svhFutureVc, 1) <> ''''t''''
and svhDate>''''''+@strSummaryDate+''''''
UNION ALL
--TOTAL stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock, ''''Verification Plus'''', 1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid
and svdVerifiedStock > svdAvailStock
and svhCancelled=0  and left(svhFutureVc, 2) = ''''tc''''
and svhDate>''''''+@strSummaryDate+''''''
union all
--ToTAL stockverification minus
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdAvailStock - svdVerifiedStock, ''''Verification Minus'''', -1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
and svhCancelled = 0 and left(svhFutureVc, 2) = ''''tc'''' and svhDate>''''''+@strSummaryDate+''''''
union all
--itemsplitting minus
select isdgodownid, ishSplititemid, ishdate, NULL, NULL,
isdqty, ''''Splitting Ded'''', -1 as mode, NULL, NULL, NULL, NULL
from LoiItemSplitDetail sd, LoiItemSplitheader sh
Left Outer Join loaItemSplitCostingHeader scfh
On sh.ishId = scfh.scfhItemSplitId
and sh.ishGodownId = scfh.scfhGodownId, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=
sh.ishgodownid and sh.ishcancelled=0 and ishSplitItemId =i.ItemId
and ishdate>''''''+@strSummaryDate+''''''
union all
--Merging minus
select lgdGodownID, lgdItemID, lghDate, NULL, NULL,
sum(lgsdqty), ''''Merging Deduct'''', -1 as mode, NULL, NULL, NULL, NULL
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid
and md.lgdgodownid = mh.lghgodownid
and lghCancelled = 0 and lghDate>''''''+@strSummaryDate+''''''
group by lgdGodownID, lgdItemID, lghDate, lghid
Having sum(lgsdqty) <> 0
union all
--Merging Add
select lgdGodownID, lghItemID, lghDate, NULL, NULL,
sum(lgsdqty), ''''Merging Add'''', 1 as mode, NULL, NULL, NULL, NULL
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid
and md.lgdgodownid = mh.lghgodownid
and lghCancelled = 0 and lghDate>''''''+@strSummaryDate+''''''
group by lgdGodownID, lghItemID, lghDate, lghid
Having sum(lgsdqty) <> 0'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
-- Generates vwGdnBinCardBadQtySummary with hardcoded summary date.
--  It is found that hardcoded date improves the performance of the view.
--  This view is created to increase the speed of calculating item stock.
-- ===============================================
-- spMag_GenerateVwGdnBinCardBadQtySummary ''20091231''
CREATE PROC [dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]
@strSummaryDate as varchar(8)
AS
BEGIN
-- Since a variable cannot store more than 8000 chars,
-- the query is directly executed using EXEC command.
EXEC (
''IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE=''''V'''' AND NAME=''''vwGdnBinCardBadQtySummary'''')
DROP VIEW vwGdnBinCardBadQtySummary'')
EXEC (
''-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwGdnBinCardBadQtySummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 28-07-2010
-- Description :
--    To compute godown bad stock in transactions summary method.
--    This view is created based on vwGdnBinCardBadQty.
--    Summary Date filtering is additionally added.
--    Group By clause was removed to improve performance.
-- ===============================================
CREATE VIEW dbo.vwGdnBinCardBadQtySummary AS
--write off
select wd.wdGodownid godownid, wd.wditemid ItemID, wh.whDate GDate,
NULL Transid, NULL TransNo, wd.wdWriteoffQty badtransqty,
''''Write Off'''' as [Type], 1 mode, NULL updatetime
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid = wd.wdid
and wh.whgodownid = wd.wdgodownid
and wh.whcancelled = 0
and wh.whType = ''''W'''' and wh.whDate>''''''+@strSummaryDate+''''''
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedbadStock-svdAvailbadStock,
''''Bad Verification Plus'''', 1 mode, NULL
from  loistockverificationheader, loistockverificationdetail where
svhid = svdid and svhgodownid = svdgodownid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 and svhDate>''''''+@strSummaryDate+''''''
union all
--stock verification deduct
select svdGodownid, svdItemid, svhDate, NULL, NULL SvAddNo,
svdAvailbadStock - svdVerifiedbadStock,
''''Bad Verification Minus'''', -1 mode, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdAvailbadStock > svdVerifiedbadStock
and svhCancelled=0 and svhDate>''''''+@strSummaryDate+''''''
union all
--damage qty clearance
select dcdgodownid, dcdItemID, dchClearingDate, NULL, NULL,
dcdWriteOffQty, ''''Damage Cleared'''', -1 mode, NULL
from  LOiDamageClearingHeader, LOiDamageClearingdetails
where dchClearingID = dcdClearingID and dchgodownid = dcdgodownid
and dchcancelled = 0 and dchClearingDate>''''''+@strSummaryDate+'''''''')
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[SplitStringByComma]    Script Date: 10/06/2012 14:17: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].[SplitStringByComma]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- Added by: Regin T.
-- Added on: 16-06-2010
--------------------------------------------------------------------------------
create FUNCTION [dbo].[SplitStringByComma]
(
@SuppliedRowData VARCHAR(MAX)
)
RETURNS @RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
--      Declare @Cnt int
--      Set @Cnt = 1
DECLARE  @SplitOn as VARCHAR(10)
DECLARE @RowData AS VARCHAR(MAX)
SET @SplitOn = '',''
SET @RowData = LTRIM(RTRIM(@SuppliedRowData))
While (CHARINDEX(@SplitOn, @RowData, 0) > 0)
BEGIN
INSERT INTO @RtnValue (Data)
SELECT
Data = LTRIM(RTRIM(SUBSTRING(@RowData,1,CHARINDEX(@SplitOn, @RowData)-1)))
SET @RowData = SUBSTRING(@RowData,CHARINDEX(@SplitOn,@RowData)+1, LEN(@RowData))
--Set @Cnt = @Cnt + 1
END
INSERT INTO @RtnValue (Data)
SELECT Data = LTRIM(RTRIM(@RowData))
RETURN
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLedgerPreviewAfterPosting]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLedgerPreviewAfterPosting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- spLedgerPreviewAfterPosting 1,''08/DSD/SW/PR/1'','''',''20030101'',''20031212''
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created By   : Kishore, Hariharan R
-- Created Date : 20/06/2003, 24/08/2003, 19/03/2004
-- TO get the preview of the posted transactions
-- from pos and inventory internally through the system
-- modified to take for any date any transaction
-- (Taken from v2)
-- 24/08/2003 Modified giving ramount as respective amount , camount as company amount column
-- modified to group with PostGroup
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spLedgerPreviewAfterPosting]  @intCompanyId as int,
@strTransId as varchar(4000), @strTransType as char(10)='''',
@strDate varchar(10) = '''', @strToDate varchar(10) = ''''
AS
Begin
set ansi_warnings off
Declare @strSql As nvarchar(4000)
DECLARE @strTransTypeWhere as varchar(2000)
set @strTransTypeWhere =''''
IF @strTransid <> ''''
Begin
set @strTransid =  '' and h.Referenceno in ('''''' + @strTransid + '''''')''
End
IF @strTransType <> ''''
Begin
set @strTransTypeWhere  = '' and h.Type = '''''' + ltrim(rtrim(@strTransType)) + ''''''''
End
if @strDate <>''''
Begin
set @strTransTypeWhere  = @strTransTypeWhere + '' and h.journaldate >= '''''' + @strDate + '''''''' +
'' and h.JournalDate <= '''''' + @strToDate + ''''''''
End
set @strSql = N''SELECT  h.JournalId, h.CompanyId, h.JournalDate,
h.Remarks, d.DepartmentId, dept.DepartmentName,
h.ReferenceNo, h.FinancialId,
h.Type,  d.ActualAmount rAmount,d.Amount camount, d.DepAmount dAmount,
case when d.accountid is not null then am.CurrencyID
when d.customerid  is not null then cm.CurrencyID
when d.vendorid  is not null then vm.currencyid end as rescurrid,
case when d.accountid is not null then accu.symbol
when d.customerid  is not null then cuac.symbol
when d.vendorid  is not null then venac.symbol end as resymbol ,
case when d.accountid is not null then AccountDesc
when d.customerid  is not null then CustomerName
when d.vendorid  is not null then vendorname end as Particulars ,
d.JournalCredit,depcur.symbol
FROM MoaJournalHeader h, MoaJournalDetails d
left outer join aAccountMaster am
on d.companyid = am.companyid and d.accountid = am.accountid
left outer join acurrencymaster accu
on accu.currencyid=am.currencyid and accu.companyid=am.companyid
left outer join acustomermaster cm
on d.companyid = cm.companyid and d.customerid = cm.customerid
left outer join acurrencymaster cuac
on cuac.currencyid=cm.currencyid and cuac.companyid=cm.companyid
left outer join avendormaster vm
on d.companyid = vm.companyid and d.vendorid = vm.vendorid
left outer join acurrencymaster venac
on venac.currencyid=vm.currencyid and venac.companyid=vm.companyid
left outer join aDepartmentMaster Dept
on d.DepartmentID = Dept.DepartmentID AND D.COMPANYID = DEPT.COMPANYID
left outer join acurrencymaster depcur
on depcur.currencyid=dept.depcurrencyid and depcur.companyid=dept.companyid
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
AND Cancel = 0 '' +
@strTransTypeWhere + @strTransid +
''order by Referenceno, PostGroup, JournalCredit''
exec sp_ExecuteSql @strSql
set ansi_warnings on
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_RebuildAllIndexes]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_RebuildAllIndexes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY: NIDHEESH PV
--CREATED ON: 04/05/2011
--COMMENTS: TO REBUILD ALL INDEXES IN A DATABASE
CREATE PROC [dbo].[spMag_RebuildAllIndexes](@fillfactor as int=80)
AS
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)
BEGIN
DECLARE CursTable CURSOR FOR SELECT NAME FROM SYSOBJECTS WHERE TYPE=''U''
OPEN CursTable
FETCH NEXT FROM CursTable INTO @TABLE
WHILE @@FETCH_STATUS=0
	BEGIN
	SET @cmd= ''ALTER INDEX ALL ON '' + @Table + '' REBUILD WITH (FILLFACTOR='' + CONVERT(VARCHAR(3),@fillfactor) + '')''
	--PRINT @cmd
	EXEC(@cmd)
	FETCH NEXT FROM CursTable INTO @TABLE
END
CLOSE CursTable
DEALLOCATE CursTable
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDishCategorySales]    Script Date: 10/06/2012 14:17: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].[spDishCategorySales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- 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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[usp_GetErrorInfo]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_GetErrorInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Create a procedure to retrieve error information.
CREATE PROCEDURE [dbo].[usp_GetErrorInfo]
AS
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[FnConvertCustomerStatementToHtml]    Script Date: 10/06/2012 14:17: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].[FnConvertCustomerStatementToHtml]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Rajesh Kamalakshan
-- Create date: <18-01-2010>
-- Description:	<To format customer summary to html format>
-- =============================================
create FUNCTION [dbo].[FnConvertCustomerStatementToHtml]
(
	-- Add the parameters for the function here
	@InputTable xml
)
RETURNS varchar(max)
AS
BEGIN
	--creating table varibale to store the @InputTable xml value
	Declare @TempTable table
	(
		CustomerId	int,
		DepartmentID int,
		DepartmentName	varchar(50),
		InvocieId	nchar(20),
		InvAmount	numeric(18,2),
		SettledAmt	numeric(18,2),
		BalanceAmt	numeric(18,2),
		Age	int,
		Due	char(10),
		Processed	bit,
		CurrencyName	nvarchar(40),
		Symbol	nvarchar(40),
		Invoicedate	datetime,
		Invoiceno	varchar(50),
		Referenceno	varchar(100),
		remarks	varchar(1000)
	)
--coverting @InputTable in XML format to table variable @TempTable
	insert into @TempTable
	SELECT Tbl.Col.value(''@CustomerId'', ''INT''),
	Tbl.Col.value(''@DepartmentID'', ''INT''),
	Tbl.Col.value(''@DepartmentName'', ''varchar(50)''),
	Tbl.Col.value(''@InvocieId'', ''nchar(20)''),
	Tbl.Col.value(''@InvAmount'', ''numeric(18,2)''),
	Tbl.Col.value(''@SettledAmt'', ''numeric(18,2)''),
	Tbl.Col.value(''@BalanceAmt'', ''numeric(18,2)''),
	Tbl.Col.value(''@Age'', ''INT''),
	Tbl.Col.value(''@Due'',	''char(10)''),
	Tbl.Col.value(''@Processed'',	''bit''),
	Tbl.Col.value(''@CurrencyName'',	''nvarchar(40)''),
	Tbl.Col.value(''@Symbol'',	''nvarchar(40)''),
	Tbl.Col.value(''@Invoicedate'',	''datetime''),
	Tbl.Col.value(''@Invoiceno'',	''varchar(50)''),
	Tbl.Col.value(''@Referenceno'',	''varchar(100)''),
	Tbl.Col.value(''@remarks'',	''varchar(1000)'')
	FROM   @InputTable.nodes(''//EmailList'') Tbl(Col)  order by Tbl.Col.value(''@Age'',''INT'')
	---Declaring Variables
	declare @InvocieId as int
	declare @Invoicedate as datetime
	declare @Invoiceno as	varchar(50)
	declare @Referenceno	as varchar(100)
	declare @remarks	as varchar(1000)
	declare @InvAmount	as numeric(18,2)
	declare @SettledAmt	as numeric(18,2)
	declare @BalanceAmt	as numeric(18,2)
	declare @SumInvAmount	as numeric(18,2)
	declare @SumSettledAmt	as numeric(18,2)
	declare @SumBalanceAmt	as numeric(18,2)
	declare @Age	as int
	declare @Due	as char(10)
	declare @outputs as varchar(max)
--Creating header part of the HTML table
	set @outputs=''<div style="font-family: Times New Roman, Times, serif; font-size: xx-small; font-weight: normal; font-style: normal; font-variant: normal;">''+
''<table cellpadding="0" cellspacing="0" width="100%"><tr><td colspan=9><u><b>Invoice Details</b></u></td> </tr> <tr><td colspan=9>&nbsp</td></tr><tr style="font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; background-color: #808080; font-weight: bold">''+
''<td>Date</td><td>Invoice No</td><td>Ref No</td>''+
''<td>Remarks</td><td align=right>Invoice Amount</td><td align=right>Settled</td><td align=right>Balance</td><td align=right>Due</td><td align=right>Age</td></tr> ''
	--Finding the total sum of balance amount,settled amount and invice amount
select @SumInvAmount=sum(InvAmount),@SumSettledAmt=sum(SettledAmt),@SumBalanceAmt=sum(BalanceAmt)	from @TempTable --where InvocieId=@InvocieId
	declare @summaryBalanceAmt as numeric(18,2)
declare @summaryThirty as numeric(18,2)
	declare @summaryThirtSixty as numeric(18,2)
	declare @summarySixtyNinty as numeric(18,2)
	declare @summaryNinty as numeric(18,2)
	--finding the sum of total balance ,sum of amount for bills with age <=30 ,sum of amount for bills with age >=31 and age <=60 and
	--sum of amount for bills with age>=61 and age<=90 and sum of amount for bills with age >=91. For the summary part.
	select @summaryBalanceAmt=sum(BalanceAmt),@summaryThirty=cast(sum(Thirty) as numeric(18,2)) ,@summaryThirtSixty=cast( sum(ThirtSixty) as numeric(18,2)) ,@summarySixtyNinty=cast(sum(SixtyNinty) as numeric(18,2)),@summaryNinty=cast( sum(Ninty) as numeric(18,2))from (
	select sum(BalanceAmt) as BalanceAmt
	,case when (age >=0 and age <= 30) then isnull(sum(InvAmount),0) else 0 end as Thirty
	,case when (age >=31 and age <= 60) then isnull(sum(InvAmount),0) else 0  end as ThirtSixty
	,case when (age >=61 and age <= 90) then isnull(sum(InvAmount),0) else 0  end as  SixtyNinty
	,case when (age >=91) then  isnull(sum(InvAmount),0) else 0  end as  Ninty
	from @TempTable  --where   CustomerId=18
	group by InvAmount,age)c
	--Looping through the @TempTable table varibale for each invoiceid
	--this loop will be continued until all the invoiceid are deleted from the @TempTable table variable
	while((select count(*) from @TempTable)<>0)
	begin
		--finding max of invoiceid
		select @InvocieId=max(InvocieId) from @TempTable
		--assigning the required fields in @TempTable to respective variables for each invoiceid in the while loop
		select @Invoicedate=Invoicedate,
			@Invoiceno=Invoiceno,
			@Referenceno=Referenceno,
			@remarks=remarks,
			@InvAmount=InvAmount,
			@SettledAmt=SettledAmt,
			@BalanceAmt=BalanceAmt,
			@Age=Age,
			@Due=Due
		from @TempTable where InvocieId=@InvocieId
		--coverting the values stored above to HTML format and assigns to the @outputs variable
		set @outputs=@outputs+''<tr><td>''+cast(@Invoicedate as varchar(12)) +''</td>''+
					 ''<td>''+@Invoiceno+''</td>''+
					 ''<td>''+@Referenceno+''</td>''+
					 ''<td>''+cast(@remarks as varchar(1000))+''</td>''+
					 ''<td align=right>''+cast(@InvAmount as varchar(20))+''</td>''+
					 ''<td align=right>''+cast(@SettledAmt as varchar(20))+''</td>''+
					 ''<td align=right>''+cast(@BalanceAmt as varchar(20))+''</td>''+
					 ''<td align=right>''+cast(@Age as varchar(10))+''</td>''+
					 ''<td align=right>''+@Due+''</td></tr>''
		--deleting the selected invoiceid from the @TempTable
		--this loop will be continued until all the invoiceid are deleted from the @TempTable table variable
		delete from @TempTable where InvocieId=@InvocieId
	end
	--converting the total part to HTML format and concatnating it with the @outputs varibale
set @outputs=@outputs+ ''<tr><td></td><td></td><td></td><td>Total Balance:</td><td align=right style="border-style: ridge none double none; border-width: thin thin medium thin; border-color: #000000">''+
cast( @SumInvAmount as varchar(20))+''</td><td align=right style="border-style: ridge none double none; border-width: thin thin medium thin; border-color: #000000">''+cast( @SumSettledAmt as varchar(20))+
''</td><td align=right style="border-style: ridge none double none; border-width: thin thin medium thin; border-color: #000000">''+
cast( @SumBalanceAmt as varchar(20))+''</td><td style="border-style: ridge none double none; border-width: thin thin medium thin; border-color: #000000">&nbsp;</td>''+
''<td style="border-style: ridge none double none; border-width: thin thin medium thin; border-color: #000000">&nbsp;</td></tr></table>''
	declare @Summary as varchar(max)
set @Summary=''''
--converting the summary  part to HTML format
	set @Summary=''<table align=center cellpadding="0" cellspacing="0" width="50% style="font-family: Arial, Helvetica, sans-serif; font-size: small"><tr style="font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; background-color: #808080; font-weight: bold">''+
''<td align=right>Balanace</td><td align=right>0-30 Days</td><td align=right>31-60 Days</td><td align=right>61-90 Days</td><td align=right>90 Days</td></tr>''+
''<tr><td align=right style="border-style: none none solid solid; border-width: 1px; border-color: #000000;">''+ cast(isnull(@summaryBalanceAmt,0) as varchar(20))+
''</td><td align=right style="border-style: none none solid solid; border-width: 1px; border-color: #000000;" >''+cast(isnull(@summaryThirty,0) as varchar(20))+
''</td><td align=right style="border-style: none none solid solid; border-width: 1px; border-color: #000000;">''+
cast(isnull(@summaryThirtSixty,0) as varchar(20))+''</td><td align=right style="border-style: none none solid solid; border-width: 1px; border-color: #000000;">''+
cast(isnull(@summarySixtyNinty,0) as varchar(20))+''</td><td align=right style="border-style: none solid solid solid; border-width: 1px; border-color: #000000;">''+
cast(isnull(@summaryNinty,0) as varchar(20))+''</td></tr></table></div>''
--concatnating @outputs with  @Summary varibale and returs to the calling sp .
	return @outputs --+''<br><br>''+@Summary--commented not to send the summary part--by rajesh Kamalakshan
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[ErrorDemo]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ErrorDemo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[ErrorDemo]
@Key1    INT,
@Key2   INT,
@Key3    INT,
@Value1  VARCHAR(255),
@Value2  VARCHAR(255),
@Value3  VARCHAR(255)
AS
SET NOCOUNT ON
UPDATE Table1 Set Col2=@Value1 WHERE Col1=@Key1
IF @@ERROR<>0
BEGIN
PRINT ''Handle error here''
END
UPDATE Table2 Set Col2=@Value2 WHERE Col1=@Key2
IF @@ERROR<>0
BEGIN
PRINT ''Handle error here''
END
UPDATE Table3 Set Col2=@Value3 WHERE Col1=@Key3
IF @@ERROR<>0
BEGIN
PRINT ''Handle error here''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spConvertCurrency]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertCurrency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------
--Created on  : 30/11/2002
--Created by : leo
--Comments : to do the currency conversion, this formula is tested
-------------------------------------------------------------------------------
--Modified on  : 24/09/2003
--Modified by : R Harikrishnan
--Comments : changed the output parameter precesion to 4
-------------------------------------------------------------------------------
--RefNo-1
--Modified on  : 19/04/2012
--Modified by  : MANUNADH. U
--Comments     : Change the precision from 4 to 9. otherwise the output will round
--				 in to 4 decimal places.This modofication is donefor the
--				 Task No: M_111 & M_112 specified in the Magnolia Issue Tracking System
------------------------------------------------------------------------------
CREATE proc [dbo].[spConvertCurrency]
@numfromer  as numeric(15,8),
@numtoer  as numeric(15,8),
@numAmount  as numeric(20,9),   --<<RefNo-1>>Change the precision from 4 to 9
@numequiamount  as numeric(20,9) output --<<RefNo-1>>Change the precision from 4 to 9
as
begin
set nocount on
set @numequiamount = round((@numtoer / @numfromer) * @numamount,9)   --<<RefNo-1>>Change the rounding from 4 to 9
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPoItemListOrGDN]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPoItemListOrGDN]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREARED BY : SREEJITH G A
--CREATED ON : 20101118
--PURPOSE : TO SHOW THE ITEM GROUPED DETAILS OF POs.
--spPoItemListOrGDN  23,''20100927'',''20100927'',''''
CREATE PROC [dbo].[spPoItemListOrGDN]
(
@intDepId int,
@fromdate varchar(10),
@Todate varchar(10),
@POId varchar(4000))
as
begin
Set ansi_warnings off
Set NoCount on
declare @strsql as nvarchar(4000)
set @strSql=N''SELECT
min(vwHqPurchaseOrder.pohPoid) MinPoId,  vwHqPurchaseOrder.itemid, sum(vwHqPurchaseOrder.podQty) PoQty, sum(vwHqPurchaseOrder.podUnitPrice*vwHqPurchaseOrder.podQty*pohcmpexrate) CmpAmt,  sum(vwHqPurchaseOrder.podUnitPrice*vwHqPurchaseOrder.podQty*pohdepexrate) DepAmt,vwHqPurchaseOrder.itemdescription,
aItem.ItemCode, aItem.brand
FROM
vwHqPurchaseOrder
LEFT OUTER JOIN AITEM
ON AITEM.ITEMID=vwHqPurchaseOrder.ITEMID
where
pohtype=''''P'''' and pohcancel=0 and pohpodate>= '''''' + @fromdate +'''''' and pohpodate<= '''''' + @Todate + ''''''''
if  @POId<> ''''
begin
set @strSql = @strSql+ N'' and pohpoid in ('' + @POId + '')''
end
if  @intDepId<> 0
begin
set @strSql = @strSql+ N''and  pohdepartmentid= '' + convert(varchar(10),@intDepId )
end
set @strSql = @strSql+ N'' group by vwHqPurchaseOrder.itemid, vwHqPurchaseOrder.itemdescription,
aItem.ItemCode, aItem.brand
order by MinPoId , vwHqPurchaseOrder.itemdescription''
print @strsql
exec sp_executesql @strSql
Set ansi_warnings on
Set NoCount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spContainedRecords]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spContainedRecords]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 18/01/2003 9:45:42 PM ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 17/11/2001 9:22:13 PM ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spContainedRecords    Script Date: 09/03/2001 02:32:28 ******/
CREATE proc [dbo].[spContainedRecords] @intAccID as int as
begin
	SELECT distinct(JournalID)
	FROM mosJournalDetails
	WHERE AccountID = @intAccID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spForwardCosting]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spForwardCosting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by 	: R Harikrishnan
--Created on	: 04/03/2003
--Purpose	: To print the Forward costing details
CREATE procedure [dbo].[spForwardCosting] as
select * from ##Temp' 
END
GO
/****** Object:  View [dbo].[vwshopstockitem]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockitem]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Last Modified on  : 11/12/02, 25/12/2003
--Modified by  : leo, Hariharan ,Shinu
--Comments  : v3, removed the stock >0 condition  ,,Removed MosShopStock and added  vwInquiryshopstock
--Verified by       : Hariharan
--Verified Date      : 04/05/2004 (verified From Dev Server(Fies))
CREATE view [dbo].[vwshopstockitem] as
select ''S'' as type, ss.shopid, i.itemcategoryid, ss.itemid,
convert(numeric(18,3), sum(ss.stock)) as stock,
convert(numeric(18,3), sum(ss.badstock)) badstock from
vwInquiryshopstock ss, aitem i, aitemcategory ic where
ss.itemid = i.itemid and i.itemcategoryid = ic.itemcategoryid
group by ss.shopid, i.itemcategoryid, ss.itemid --having sum(ss.stock) > 0'
GO
/****** Object:  StoredProcedure [dbo].[sp_sproc_columns]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_sproc_columns]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
alter procedure [dbo].[sp_sproc_columns]
(
@procedure_name         nvarchar(390) = ''%'',
@procedure_owner        nvarchar(384) = null,
@procedure_qualifier    sysname = null,
@column_name            nvarchar(384) = null,
@ODBCVer                int = 2,
@fUsePattern            bit = 1 -- To allow users to explicitly disable all pattern matching.
)
as
declare @group_num_lower smallint
declare @group_num_upper smallint
declare @semi_position int
declare @full_procedure_name nvarchar(775) -- 390 + 1 + 384
declare @procedure_id int
if @procedure_qualifier is not null
begin
if db_name() <> @procedure_qualifier
begin
if @procedure_qualifier = ''''
begin
-- in this case, we need to return an empty result set
-- because the user has requested a database with an empty name
select @procedure_name = ''''
select @procedure_owner = ''''
end
else
begin   -- If qualifier doesn''t match current database
raiserror (15250, -1,-1)
return
end
end
end
if @procedure_name is null
begin   -- If procedure name not supplied, match all
select @procedure_name = ''%''
end
-- first we need to extract the procedure group number, if one exists
select @semi_position = charindex('';'',@procedure_name)
if (@semi_position > 0)
begin   -- If group number separator (;) found
select @group_num_lower = convert(int,substring(@procedure_name, @semi_position + 1, 2))
select @group_num_upper = @group_num_lower
select @procedure_name = substring(@procedure_name, 1, @semi_position -1)
end
else
begin   -- No group separator, so default to all groups
select @group_num_lower = 0
select @group_num_upper = 32767
end
if @procedure_owner is null
begin   -- If unqualified procedure name
select @full_procedure_name = quotename(@procedure_name)
end
else
begin   -- Qualified procedure name
if @procedure_owner = ''''
begin   -- If empty owner name
select @full_procedure_name = quotename(@procedure_owner)
end
else
begin
select @full_procedure_name = quotename(@procedure_owner) + ''.'' + quotename(@procedure_name)
end
end
select @procedure_id = object_id(@full_procedure_name)
if (@fUsePattern = 1) -- Does the user want it?
begin
if ((isnull(charindex(''%'', @full_procedure_name),0) = 0) and
(isnull(charindex(''['', @procedure_name),0) = 0) and
(isnull(charindex(''['', @procedure_owner),0) = 0) and
(isnull(charindex(''_'', @full_procedure_name),0) = 0) and
(@procedure_id is not null))
begin
select @fUsePattern = 0 -- not a single wild char, so go the fast way.
end
end
if @fUsePattern = 0
begin
/* -- Debug output, do not remove it.
print ''*************''
print ''No pattern matching.''
print isnull(convert(sysname, @procedure_id),   ''@procedure_id = null'')
print isnull(@full_procedure_name,              ''@full_procedure_name = null'')
print isnull(@procedure_name,                   ''@procedure_name = null'')
print isnull(@procedure_owner,                  ''@procedure_owner = null'')
print isnull(@procedure_qualifier,              ''@procedure_qualifier = null'')
print isnull(@column_name,                      ''@column_name = null'')
print isnull(@ODBCVer,                          ''@ODBCVer = null'')
print ''*************''
*/
--
-- FAST!
--
select
PROCEDURE_QUALIFIER         = s_scov.PROCEDURE_QUALIFIER,
PROCEDURE_OWNER             = s_scov.PROCEDURE_OWNER,
PROCEDURE_NAME              = convert(nvarchar(134),
s_scov.PROCEDURE_NAME +'';''+ ltrim(str(s_scov.procedure_number,5))),
COLUMN_NAME                 = s_scov.COLUMN_NAME,
COLUMN_TYPE                 = s_scov.COLUMN_TYPE,
DATA_TYPE                   = s_scov.DATA_TYPE_28,
TYPE_NAME                   = s_scov.TYPE_NAME_28,
"PRECISION"                 = s_scov.PRECISION_28,
"LENGTH"                    = s_scov.LENGTH_28,
SCALE                       = s_scov.SCALE,
RADIX                       = s_scov.RADIX,
NULLABLE                    = s_scov.NULLABLE,
REMARKS                     = s_scov.REMARKS,
COLUMN_DEF                  = s_scov.COLUMN_DEF,
SQL_DATA_TYPE               = s_scov.SQL_DATA_TYPE_28,
SQL_DATETIME_SUB            = s_scov.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH           = s_scov.CHAR_OCTET_LENGTH_28,
ORDINAL_POSITION            = s_scov.ORDINAL_POSITION,
IS_NULLABLE                 = s_scov.IS_NULLABLE,
SS_DATA_TYPE                = s_scov.SS_DATA_TYPE
from
sys.spt_sproc_columns_odbc_view s_scov
where
s_scov.object_id = @procedure_id and
s_scov.odbcver = @ODBCVer and
(@column_name is null or s_scov.COLUMN_NAME = @column_name) and
(s_scov.procedure_number between @group_num_lower and @group_num_upper)
UNION ALL
select         -- procedure return value & table valued functions
PROCEDURE_QUALIFIER         = s_scrvov.PROCEDURE_QUALIFIER,
PROCEDURE_OWNER             = s_scrvov.PROCEDURE_OWNER,
PROCEDURE_NAME              = convert(nvarchar(134),
s_scrvov.PROCEDURE_NAME +'';''+ ltrim(str(s_scrvov.procedure_number,5))),
COLUMN_NAME                 = s_scrvov.COLUMN_NAME,
COLUMN_TYPE                 = s_scrvov.COLUMN_TYPE,
DATA_TYPE                   = s_scrvov.DATA_TYPE, -- SNAC == MDAC, return value can only be int or table
TYPE_NAME                   = s_scrvov.TYPE_NAME, -- SNAC == MDAC, return value can only be int or table
"PRECISION"                 = s_scrvov.PRECISION,
"LENGTH"                    = s_scrvov.LENGTH,
SCALE                       = s_scrvov.SCALE,
RADIX                       = s_scrvov.RADIX,
NULLABLE                    = s_scrvov.NULLABLE,
REMARKS                     = s_scrvov.REMARKS,
COLUMN_DEF                  = s_scrvov.COLUMN_DEF,
SQL_DATA_TYPE               = s_scrvov.SQL_DATA_TYPE,
SQL_DATETIME_SUB            = s_scrvov.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH           = s_scrvov.CHAR_OCTET_LENGTH,
ORDINAL_POSITION            = s_scrvov.ORDINAL_POSITION,
IS_NULLABLE                 = s_scrvov.IS_NULLABLE,
SS_DATA_TYPE                = s_scrvov.SS_DATA_TYPE
from
sys.spt_sproc_columns_return_values_odbc_view s_scrvov
where
s_scrvov.object_id = @procedure_id and
(
@column_name is null or
@column_name = ''@RETURN_VALUE'' or
@column_name = ''@TABLE_RETURN_VALUE''
) and
(s_scrvov.procedure_number between @group_num_lower and @group_num_upper)
order by 1, 2, 3, 18
end
else
begin
/* -- Debug output, do not remove it.
print ''*************''
print ''THERE IS pattern matching!''
print isnull(convert(sysname, @procedure_id),   ''@procedure_id = null'')
print isnull(@full_procedure_name,  ''@full_procedure_name = null'')
print isnull(@procedure_name,                   ''@procedure_name = null'')
print isnull(@procedure_owner,                  ''@procedure_owner = null'')
print isnull(@procedure_qualifier,              ''@procedure_qualifier = null'')
print isnull(@column_name,                      ''@column_name = null'')
print isnull(@ODBCVer,                          ''@ODBCVer = null'')
print ''*************''
*/
--
-- SLOOOOOW!
--
if @procedure_owner is null
select @procedure_owner = ''%''
select
PROCEDURE_QUALIFIER         = s_scov.PROCEDURE_QUALIFIER,
PROCEDURE_OWNER             = s_scov.PROCEDURE_OWNER,
PROCEDURE_NAME              = convert(nvarchar(134),
s_scov.PROCEDURE_NAME +'';''+ ltrim(str(s_scov.procedure_number,5))),
COLUMN_NAME                 = s_scov.COLUMN_NAME,
COLUMN_TYPE                 = s_scov.COLUMN_TYPE,
DATA_TYPE                   = s_scov.DATA_TYPE_28,
TYPE_NAME                   = s_scov.TYPE_NAME_28,
"PRECISION"                 = s_scov.PRECISION_28,
"LENGTH"                    = s_scov.LENGTH_28,
SCALE                       = s_scov.SCALE,
RADIX                       = s_scov.RADIX,
NULLABLE                    = s_scov.NULLABLE,
REMARKS                     = s_scov.REMARKS,
COLUMN_DEF                  = s_scov.COLUMN_DEF,
SQL_DATA_TYPE               = s_scov.SQL_DATA_TYPE_28,
SQL_DATETIME_SUB            = s_scov.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH           = s_scov.CHAR_OCTET_LENGTH_28,
ORDINAL_POSITION            = s_scov.ORDINAL_POSITION,
IS_NULLABLE                 = s_scov.IS_NULLABLE,
SS_DATA_TYPE                = s_scov.SS_DATA_TYPE
from
sys.spt_sproc_columns_odbc_view s_scov
where
s_scov.PROCEDURE_NAME like @procedure_name and
(@column_name is null or s_scov.COLUMN_NAME like @column_name) and
s_scov.odbcver = @ODBCVer and
(s_scov.procedure_number between @group_num_lower and @group_num_upper) and
schema_name(s_scov.schema_id) like @procedure_owner
UNION ALL
select         -- procedure return value & table valued functions
PROCEDURE_QUALIFIER         = s_scrvov.PROCEDURE_QUALIFIER,
PROCEDURE_OWNER             = s_scrvov.PROCEDURE_OWNER,
PROCEDURE_NAME              = convert(nvarchar(134),
s_scrvov.PROCEDURE_NAME +'';''+ ltrim(str(s_scrvov.procedure_number,5))),
COLUMN_NAME                 = s_scrvov.COLUMN_NAME,
COLUMN_TYPE                 = s_scrvov.COLUMN_TYPE,
DATA_TYPE                   = s_scrvov.DATA_TYPE, -- SNAC == MDAC, return value can only be int or table
TYPE_NAME                   = s_scrvov.TYPE_NAME, -- SNAC == MDAC, return value can only be int or table
"PRECISION"                 = s_scrvov.PRECISION,
"LENGTH"                    = s_scrvov.LENGTH,
SCALE                       = s_scrvov.SCALE,
RADIX                       = s_scrvov.RADIX,
NULLABLE                    = s_scrvov.NULLABLE,
REMARKS                     = s_scrvov.REMARKS,
COLUMN_DEF                  = s_scrvov.COLUMN_DEF,
SQL_DATA_TYPE               = s_scrvov.SQL_DATA_TYPE,
SQL_DATETIME_SUB            = s_scrvov.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH           = s_scrvov.CHAR_OCTET_LENGTH,
ORDINAL_POSITION            = s_scrvov.ORDINAL_POSITION,
IS_NULLABLE                 = s_scrvov.IS_NULLABLE,
SS_DATA_TYPE                = s_scrvov.SS_DATA_TYPE
from
sys.spt_sproc_columns_return_values_odbc_view s_scrvov
where
s_scrvov.PROCEDURE_NAME like @procedure_name and
schema_name(s_scrvov.schema_id) like @procedure_owner and
(
@column_name is null or
@column_name = ''@RETURN_VALUE'' or
@column_name = ''@TABLE_RETURN_VALUE''
) and
(s_scrvov.procedure_number between @group_num_lower and @group_num_upper)
order by 1, 2, 3, 18
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Create_Login]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Create_Login]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- To create login
Create PROCEDURE [dbo].[Create_Login]
	@username sysname
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQL NVARCHAR(4000);
	
	SET @SQL = ''CREATE LOGIN '' + @username + '' WITH PASSWORD = ''''fiesadmin003'''', DEFAULT_DATABASE=[adminv2], DEFAULT_LANGUAGE=[British], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON'';
	
	IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N''admin'')
	begin
	EXECUTE(@SQL);
	end
	
	EXEC sys.sp_addsrvrolemember @loginame = @username, @rolename = N''sysadmin'';
	
	SET @SQL = ''ALTER LOGIN '' + @username + '' ENABLE'';
	EXECUTE(@SQL);
	
END;' 
END
GO
/****** Object:  StoredProcedure [dbo].[CryptPwd]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CryptPwd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.CryptPwd    Script Date: 18/01/2003 9:45:42 PM ******/
/****** Object:  Stored Procedure dbo.CryptPwd    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.CryptPwd    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.CryptPwd    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.CryptPwd    Script Date: 17/11/2001 9:22:12 PM ******/
CREATE proc [dbo].[CryptPwd](@pwd as varchar(250),@key as varchar(1000)) as
declare @posS as int,@posC as int,
	@tempString as varchar(1000),@intcnt as int
begin
set @tempstring=space(len(@pwd))
set @posS=len(@pwd)
set @posC=1
set @intcnt=1
while  @intcnt<=@posS
begin
	if @posC>len(@key) set @posC=1
--	set substring(@tempstring,@posS,1)=cast(ascii(substring(@pwd,@posS,1)) ^ ascii(substring(@key,@posC,1)) as varchar)
--	print convert(char,ascii(substring(@pwd,@posS,1)) & ascii(substring(@key,@posC,1)) )
	set @tempstring = stuff(@tempstring,@intcnt,1,char(ascii(substring(@pwd,@intcnt,1))^
	ascii(substring(@key,@posC,1))))
--	print @tempstring
	If Ascii(substring(@tempstring,@intcnt, 1)) = 0
--		set substring(@tempstring,@PosS, 1) = substring(@pwd,@PosS, 1)
	set @tempstring =stuff(@tempstring,@intcnt,1,substring(@pwd,@intcnt, 1))
	set @intcnt=@intcnt+1
	set @posC=@posC+1
	
end
	print ''''''''+ @tempstring+''''''''
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStock]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.SpUpdateShopStock    Script Date: 18/01/2003 9:45:43 PM ******/
--Verified by Hariharan on 04/01/2003
--Not used
CREATE proc [dbo].[SpUpdateShopStock](@fromDate as varchar(10),@shopid as int,
@itemid as int,@shipmentid as int) as
return 0
/*declare
@tmpOpeningGoodStock as numeric(18,3),
@tmpClosingGoodStock as numeric(18,3),
@tmpOpeningBadStock  as numeric(18,3),
@tmpClosingBadStock  as numeric(18,3),
@tmpDate	     as datetime,
@opGoodStock 	     as numeric(18,3),	
@opBadStock          as numeric(18,3),
@diffGoodStock       as numeric(18,3),		
@diffBadStock        as numeric(18,3),
@GoodStockDiff       as numeric(18,3),
@BadStockDiff	     as numeric(18,3),
@dtfromDate as datetime
set nocount on
set @dtfromdate = @fromdate
if @dtfromdate = (select packagedate from apackagesettings)
begin
	return 0
end
declare cursor_Shop scroll cursor for
select OpeningStock,Stock,OpeningBadStock,
BadStock,stockdate from MosshopStock
where shopid = @shopid and
itemid = @Itemid and shipmentid = @shipmentid and
stockdate >= @dtFromDate order by stockdate
open cursor_Shop
fetch next from cursor_Shop into
@tmpOpeningGoodStock,@tmpClosingGoodStock,
@tmpOpeningBadStock,@tmpClosingBadStock,@tmpdate
/* For storing the Opening stock of Good and Bad quantity */
/*	select @opGoodStock = @tmpClosingGoodStock
	select @opBadStock = @tmpClosingBadStock
while @@fetch_status = 0
begin
	fetch next from cursor_Shop into
	@tmpOpeningGoodStock,@tmpClosingGoodStock,
	@tmpOpeningBadStock,@tmpClosingBadStock,@tmpdate*/
/* For storing the Stock difference between the Opening and closing of Good and Bad Quantity */
/*	select @diffGoodStock = @tmpOpeningGoodStock - @tmpClosingGoodStock
	select @diffBadStock = 	@tmpOpeningBadStock -  @tmpClosingBadStock
	
	select @GoodStockDiff = @opGoodStock - @diffGoodStock
	select @BadStockDiff = @opBadStock - @diffBadStock
	if (@GoodStockDiff < 0  or @BadStockDiff < 0 )
	begin
	close cursor_Shop
	deallocate cursor_Shop	
	return 1
	end
	update MosshopStock set OpeningStock = @opGoodStock,
	OpeningBadStock = @opBadStock,stock = @GoodStockDiff,
	badstock = @BadStockDiff where
	shopid = @shopid and
	itemid = @itemid and shipmentid = @shipmentid and
	stockdate = @tmpdate
	
	select @opGoodStock = @GoodStockDiff
	select @opBadStock = @BadStockDiff
end
close cursor_Shop
deallocate cursor_Shop	
return 0*/
*/' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReturnExrate]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnExrate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------
--Created on 	: 30/11/2002
--Created by	: leo
--Comments	: to find the currency match and return the exchangerate from the string
--------------------------------------------------------------------------------------------
--Modified on	: 24/09/2003
--Modified by	: R Harikrishnan
--Comments	: Changed the precision of the output paramenter to 8 from 7
--------------------------------------------------------------------------------------------
CREATE proc [dbo].[spReturnExrate]
	@intCurid 	as int,
	@strExrates 	as varchar(250),
	@numexrate 	as numeric(18,8) output as
begin
	set nocount on
	declare @intposition as int,
		@strcurrenciesonly as varchar(200),
		@strexratesonly as varchar(200),
		@intcoloncount as int,
		@intcounter as int,
		@intcolonposition as int
	
	--finding the postion of seperator hypen in the string
	set @intposition = patindex(''%-%'',@strexrates)
	--extracting only the currency string part from main string
	set @strcurrenciesonly = ltrim(rtrim(substring(@strexrates,1,@intposition-1)))
	--extracting only the exrates string part from main string
	set @strexratesonly = ltrim(rtrim(substring(@strexrates,@intposition+1,
				len(@strexrates)-@intposition)))
	
	--to find the postion of the currencyid in the currency string
	set @intposition = patindex(''%''+ ltrim(rtrim(str(@intcurid))) + '':%'',@strcurrenciesonly)
	set @intcounter =1
	set @intcoloncount =0
	while @intcounter < @intposition
	begin	
		--to find how many colon it has to skip in the exrate string
		if substring(@strcurrenciesonly,@intcounter, 1) = '':''
			set @intcoloncount = @intcoloncount +1
		set @intcounter = @intcounter +1
	end
	set @intposition =1
	set @intcounter = @intcoloncount
	while @intcounter <>  0
	begin	
		--to find how many colon it has to skip in the exrate string
		if substring(@strexratesonly,@intposition, 1) = '':''
			set @intcounter = @intcounter - 1
		set @intposition = @intposition +1
	end	
	-- in @intposition the start of the respective ex rate will be there
	set @numexrate = substring(@strexratesonly,@intposition,
				charindex('':'',@strexratesonly,@intposition) - @intposition)
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGodownPriceList]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownPriceList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spGodownPriceList 0,'''',0,''arrow''
------------------------------------------------------------------------------------------------------------------------
--Created by    :  Shinu
--Created On    :  30/04/2008
--Comments      :  Godown Price List
------------------------------------------------------------------------------------------------------------------------
--Modified By   :  Yogesh Joe
--Modified On   :  12/07/2010
--Purpose  :  To fix the string truncation errors. Increased the size of @strCategoryID,@strBrand,@strCategoryCond
------------------------------------------------------------------------------------------------------------------------
CREATE Procedure [dbo].[spGodownPriceList] (@intGodownID as int,@strCategoryID as varchar(2500),@ItemID as int,@strBrand as Varchar(2500))
As
Begin
Set Ansi_Warnings Off
Set Nocount On
Declare @strSql as nvarchar(4000)
Declare @strBrandCond as varchar(100)
Declare @strCategoryCond as varchar(2500)
Declare @strItemCond1 as varchar(100)
Declare @strItemCond2 as varchar(100)
set @strsql=''''
set @strCategoryCond=''''
set @strItemCond1=''''
set @strItemCond2=''''
set @strBrandCond=''''
if @strCategoryID<>''''
Begin
set @strCategoryCond='' and vw.ItemCategoryID in ('' + @strCategoryID + '')''
End
If @ItemID<>0
Begin
set @strItemCond1='' and agd.ItemID = '' + cast(@ItemID as varchar(10))
set @strItemCond2='' Where agd.ItemID = '' + cast(@ItemID as varchar(10))
End
If @strBrand<>''''
Begin
set @strBrandCond='' and vw.Brand in ('''''' + @strBrand + '''''')''
End
if @intGodownID<>0
Begin
set @strsql=''select ai.ItemID,agd.GodownId,GodownName,ItemCode,ItemDescription,ItemRate,
ItemCategoryID,CategoryNameDescription,Brand,
SellingPrice,WholesalePrice,DiscountPrice,
CreditSp,CreditDP,CreditWP,PackingTypeName
From aGodownDetail agd
Right Outer Join (Select vw.*,CategoryNameDescription From vwShopItemStockitemsItemDtls vw
Left Outer Join aItemCategory aic On vw.ItemCategoryID=aic.ItemCategoryID where Active=1 ''
+ @strBrandCond  + @strCategoryCond + '') ai
ON ai.ItemID=agd.ItemID and quantity=1
Left Outer Join (select Distinct ItemID,SellingPrice,WholesalePrice,DiscountPrice,
CreditSp,CreditDP,CreditWP From  losshopItemShipmentDetail) ship ON ship.ItemID=agd.ItemID
Left Outer Join aGodown ag ON ag.GodownID=agd.GodownId
Where agd.GodownID='' + cast(@intGodownID as varchar(10))+ @strItemCond1 + '' Order By ItemDescription ''
End
Else
Begin
set @strsql=''Select distinct(ai.ItemID)ItemID,0 GodownId, '''''''' GodownName,ItemCode,ItemDescription,
ItemRate,ItemCategoryID,CategoryNameDescription,Brand,
SellingPrice,WholesalePrice,DiscountPrice,
CreditSp,CreditDP,CreditWP,PackingTypeName
From aGodownDetail agd
Right Outer Join (Select vw.*,CategoryNameDescription From vwShopItemStockitemsItemDtls vw
Left Outer Join aItemCategory aic On vw.ItemCategoryID=aic.ItemCategoryID Where Active=1''
+ @strBrandCond  +  @strCategoryCond +'') ai
ON ai.ItemID=agd.ItemID and quantity=1
Left Outer Join (select Distinct ItemID,SellingPrice,WholesalePrice,DiscountPrice,
CreditSp,CreditDP,CreditWP From  losshopItemShipmentDetail) ship ON ship.ItemID=ai.ItemID
'' + @strItemCond2 + ''Order By ItemDescription ''
End
--print @strsql
Exec sp_ExecuteSql @strSql
Set NoCount Off
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spgodownitemnotinshop]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgodownitemnotinshop]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
----------------------------------------------------------
--Last Modified on : 08/02/2010
--Modified By      : VinothMurugan V
--Purpose     : The Else Part is Added for Quich Item Fetch
----------------------------------------------------------
--Last Modified on : 22/03/2010
--Modified By      : Regin T
--Purpose          : Filtered out all those items that are not in the item list of the shop.
--  [inner join aShopItemDetail si] was added.
----------------------------------------------------------
--Last Modified on : 07/04/2010
--Modified By      : Regin T
--Purpose          : To view only active and forsale items,
--	[and a.active=1 and a.forsales=1] condition was added
----------------------------------------------------------
create proc [dbo].[spgodownitemnotinshop] (@intshopid as int ,@strcolname varchar(250),@QuickFetch int=0) as
begin
declare @strSql as nvarchar(3000)
if  @QuickFetch = 0
begin
set @strsql=''select  a.itemid,a.itemcode, v.itemdescription,a.brand,a.modelno,
ac.itemcategoryid, ac.CategoryNameDescription,gs.stock ,a.part_code
from vwgodownstockitem gs
inner join aShopItemDetail si on gs.ItemId=si.ItemId and si.ShopId='' + convert(varchar(2),@intshopid)
+'' left outer join vwshopstockitem ss on gs.itemcategoryid = ss.itemcategoryid and
gs.itemid = ss.itemid and ss.shopid = ''+ convert(varchar(2),@intshopid)+'' ,
vwitemdescription v,aitem a left outer join aitemcategory ac on
a.itemcategoryid=ac.ItemCategoryID
where (ss.stock is null or ss.stock = 0) and a.itemid=v.itemid
and gs.itemid = v.itemid and a.active=1 and a.forsales=1 ''
+ @strcolname
execute sp_executesql @strsql
end
else
begin
set @strsql=''select  a.itemid,a.itemcode, v.itemdescription,a.brand,a.modelno,
a.part_code from vwgodownstockitem gs
inner join aShopItemDetail si on gs.ItemId=si.ItemId and si.ShopId='' + convert(varchar(2),@intshopid)
+'' left outer join vwshopstockitem ss on gs.itemcategoryid = ss.itemcategoryid and
gs.itemid = ss.itemid and ss.shopid = ''+ convert(varchar(2),@intshopid)+'' ,
vwitemdescription v,aitem a left outer join aitemcategory ac on
a.itemcategoryid=ac.ItemCategoryID
where (ss.stock is null or ss.stock = 0) and a.itemid=v.itemid
and gs.itemid = v.itemid and a.active=1 and a.forsales=1 ''
+ @strcolname
execute sp_executesql @strsql
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReturnValue]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnValue]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 17/11/2001 9:22:14 PM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 09/03/2001 02:32:28 ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 12/05/00 1:40:15 PM ******/
/****** Object:  Stored Procedure dbo.spReturnValue    Script Date: 11/13/00 3:01:57 PM ******/
CREATE proc [dbo].[spReturnValue] @strTableName varchar(500) ,@strFieldName varchar(250),@strWherecondition varchar(1000)='''' as
begin
	set nocount on
	declare @sqlString as nvarchar(1000)
	if @strWhereCondition <> ''''
	begin
		set @sqlstring = N''Select ''+ @strFieldName + '' from ''+ @strTableName + '' where '' + @strwherecondition
	end
	else
	begin
		set @sqlstring = N''Select ''+ @strFieldName + '' from ''+ @strTableName
	end
	exec sp_executesql @sqlString
	/*if @@rowcount > 0
		return 1
	else
		return 0*/
	set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwItemSearching]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSearching]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[vwItemSearching] As
Select ShopId,aItem.ItemID,aItem.UnitsID,aItem.SizeID,BrandID,ItemCode,aItem.ItemRate,IsNull(Stock,0) As CurStock,Brand,SizeName,UnitName,
----If Brand and Size is Not Null
Case
When Coalesce(Brand,'''')<>'''' And  Coalesce(aItem.SizeId,'''')<>'''' Then
Convert(Varchar(250),ItemCode + '' - '' + ItemDescription + '' - '' + Brand + '' - '' + SizeName)
----If Brand is Null and Size is Not Null
When Coalesce(Brand,'''')='''' And  Coalesce(aItem.SizeId,'''')<>'''' Then
Convert(Varchar(250),ItemCode + '' - '' + ItemDescription +  '' - '' + SizeName )
----If Brand is Not Null and Size is Null
When Coalesce(Brand,'''')<>'''' And  Coalesce(aItem.SizeId,'''')='''' Then
Convert(Varchar(250),ItemCode + '' - '' + ItemDescription + '' - '' + Brand)
----If Brand and Size is Null
When Coalesce(Brand,'''')='''' And  Coalesce(aItem.SizeId,'''')='''' Then
Convert(Varchar(250),ItemCode + '' - '' + ItemDescription) End
As SearchDescription,ItemDescription,ItemType,Active,Brand
ItemCategoryid ,ColorName From aItem Left Outer Join vwinquiryshopstock
On aItem.ItemId=vwinquiryshopstock.ItemId Left Outer Join aSize
On aItem.SizeId = aSize.SizeId Left Outer Join aBrandMaster
On aItem.Brand = aBrandMaster.BrandName
Left Outer join aColor  On aItem.ColorID=aColor.ColorID ,
aUnit au Where aItem.UnitsId = au.UnitId'
GO
/****** Object:  StoredProcedure [dbo].[spGetUser]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[spGetUser]  AS
select UserID,UserName from aUsers' 
END
GO
/****** Object:  View [dbo].[vwFixedCost]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwFixedCost]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY 	: Hariharan
--Modified Date	: 10/09/2004
CREATE View [dbo].[vwFixedCost]
as
Select fixedcostid,FixedCostNo,FixedCostDate,FixedCostEnteredby,FixedCostRemarks,
FixedCostDepartmentid,fixedcostCompanyid, isnull(dFixedCostItemId,0)Itemid,
dFixedCostCategoryId,dFixedCostValue,
isnull(itemdescription,'''')itemdesc,CategoryNameDescription,
Case dFixedCostItemId when 0 then ''Category wise'' else ''Item wise'' end type  from
loafixedcostheader a, loafixedcostdetail b
left outer join aitem
on b.dfixedcostitemid=aitem.itemid
left outer join aitemcategory
on b.dFixedCostCategoryId=aitemcategory.ItemCategoryID
where a.fixedcostid=b.dfixedcostid and
a.fixedcostcompanyid =b.dfixedcompanyid'
GO
/****** Object:  View [dbo].[vwShopCloseDate]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCloseDate]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopCloseDate    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwShopCloseDate] as
select max(stockdate) as closedate,shopid from mosshopstockbackup group by shopid'
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_AITEMCATEGORY]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_AITEMCATEGORY]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATE BY : VINOTHMURUGAN v
--DATE		: 11/08/2010
--PURPOSE	: FETCH ITEM CATEGORY
--CLIENT	: KOODDOOO	
CREATE PROCEDURE [dbo].[SP_FETCH_AITEMCATEGORY]
AS
BEGIN
SELECT ITEMCATEGORYID,CATEGORYNAMEDESCRIPTION FROM AITEMCATEGORY ORDER BY CATEGORYNAMEDESCRIPTION
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_AITEM]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_AITEM]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATE BY : VINOTHMURUGAN V
--DATE  : 11/08/2010
--PURPOSE : FETCH ITEM ITEM
--CLIENT : KOODDOOO
CREATE PROCEDURE [dbo].[SP_FETCH_AITEM](@CATEGORYID as int)
AS
BEGIN
SELECT ITEMID,ITEMDESCRIPTION from AITEM where ACTIVE=1
and ITEMCATEGORYID=@CATEGORYID
ORDER BY ITEMDESCRIPTION
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_SELLINGPRICE]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_SELLINGPRICE]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATE BY : VINOTHMURUGAN V
--DATE  : 11/08/2010
--PURPOSE : FETCH ITEM SELLING PRICE
--CLIENT : KOODDOOO
--EXEC SP_FETCH_SELLINGPRICE ''5857'',0
CREATE PROCEDURE [dbo].[SP_FETCH_SELLINGPRICE](@itemid as int,@SHOPID AS INT)
AS
BEGIN
IF @SHOPID =''0''
BEGIN
SELECT A.ITEMDESCRIPTION,FIXDATE,IPH.SELLINGPRICE,DISCOUNTPRICE,WHOLESALEPRICE,USERNAME
FROM ITEMPRICEHISTORY IPH INNER JOIN AITEM A on IPH.ITEMID = A.ITEMID
LEFT OUTER  JOIN AUSERS U  ON  U.USERID = IPH.USERID
where  IPH.ITEMID=@itemid AND IPH.SHOPID IS NULL
END
IF @SHOPID <>''0''
BEGIN
SELECT A.ITEMDESCRIPTION,FIXDATE,IPH.SELLINGPRICE,DISCOUNTPRICE,WHOLESALEPRICE,USERNAME
FROM ITEMPRICEHISTORY IPH INNER JOIN AITEM A on IPH.ITEMID = A.ITEMID
LEFT OUTER  JOIN AUSERS U  ON  U.USERID = IPH.USERID
where  IPH.ITEMID= @itemid AND IPH.SHOPID = @SHOPID
END
END
--SELECT * FROM ITEMPRICEHISTORY' 
END
GO
/****** Object:  StoredProcedure [dbo].[Sp_param_SellingPrice]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_param_SellingPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--create  by : VinothMurugan V.
--Date   : 17/08/2010
--Purpose    : To show Currently modified selling price
--Client  : Kooddoo
CREATE PROC [dbo].[Sp_param_SellingPrice]
AS
BEGIN
select I.itemdescription,T.costprice,T.sellingprice,T.discountprice,T.wholesaleprice,u.username
from TempItemPriceList T inner join aitem I on T.itemid = I.itemid
inner join ausers u on T.userid = u.userid
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[SP_MIS_GetCompanyImage]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MIS_GetCompanyImage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SP_MIS_GetCompanyImage]
as
begin
select CompImage from acompanyimagemaster
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spFixedCost]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedCost]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spFixedCost  1,1,0
-- Last Modified : 10/06/2004
-- Modified by   : venkitesh
--		 : For Fixed Cost Processing
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spFixedCost 1,1,0
CREATE PROC [dbo].[spFixedCost] (@intdepartmentid as int = 0 ,@intcompanyid as int,
@onlyLastvalue as int = 0, @strFromDate as varchar(10), @strToDate as varchar(10),
@intCategoryid as int = 0 )
as
begin
set nocount on
set ansi_warnings off
declare
	@strcondition as varchar(1000),
	@strsql as nvarchar(4000)
	Create table #TempFixedCost
	(companyid int,
	departmentid	int,
	Fixedcostid 	int,
	FixedCostNo	varchar(25),
	fixedcostDate	datetime,
	FixedCostEnteredby varchar(250),
	Remarks varchar(250),
	ItemID int,
	categoryid int,
	Costvalue numeric(18,2),
	Type char(1))
if @intdepartmentid >0
set  @strCondition = '' and fixedcostdepartmentid= ''+ convert(varchar(2), @intdepartmentid) 		
set @strCondition = @strCondition + ''  and fixedcostDate >='''''' + @strFromDate +
		    '''''' and fixedcostDate <= '''''' + @strToDate + ''''''''
if @intCategoryid >0
	Set @strCondition = @strCondition + '' and dFixedCostCategoryId = '' +
	Convert(varchar(2), @intCategoryId)
set @strsql =''Insert into #TempFixedCost
	Select fixedcostCompanyid,FixedCostDepartmentid,
	FixedCostId,FixedCostno,FixedCostdate,FixedCostEnteredby,
	FixedCostRemarks, dFixedCostItemId,dFixedCostCategoryId,
	dFixedCostValue, '''''' + ''I'' + ''''''
	from loafixedcostheader ch,loafixedcostdetail cd where
	ch.fixedcostid=cd.dFixedCostId and ch.fixedcostcompanyid = cd.dfixedcompanyid and
	cd.dFixedCostItemId>0 and dFixedCostValue<>0 '' + @strCondition
	exec sp_executesql @strsql
	set @strsql = ''Insert into #TempFixedCost
	select fixedcostCompanyid,FixedCostDepartmentid,
	FixedCostId,FixedCostno,FixedCostdate,FixedCostEnteredby,
	FixedCostRemarks,  aItem.ItemId, dFixedCostCategoryId,
	dFixedCostValue, '''''' + ''C''+ ''''''
	from loafixedcostheader ch, loafixedcostdetail cd, aitem where
	ch.fixedcostid=cd.dFixedCostId and ch.fixedcostcompanyid=cd.dfixedcompanyid and
	cd.dFixedCostItemId=0 and dFixedCostValue<>0 and cd.dFixedCostCategoryId =
	aitem.ItemCategoryID '' + @strCondition
	exec sp_executesql @strsql
	
	Delete from #TempFixedCost where #TempFixedCost.ItemId =
	(Select a.ItemId from #TempFixedCost a where #TempFixedCost.ItemId =
	a.ItemId and #TempFixedCost.FixedCostId = a.FixedCostId and 	
	a.Type =''I'' Group By a.ItemId) and #TempFixedCost.Type =''C''
	
if @OnlyLastValue =0
	--To show the history of fixed costs item wise
	Select companyid, departmentid, Fixedcostid, FixedCostNo, fixedcostDate,
	FixedCostEnteredby, Remarks, b.ItemID, categoryid, Costvalue, Type,
	b.itemcategoryid, itemdescription, CategoryNameDescription
	from #TempFixedCost a left outer join (select itemid, a.itemcategoryid,
	itemdescription,CategoryNameDescription from aitem a, aitemcategory b where
	a.itemcategoryid=b.itemcategoryid) b on a.itemid=b.itemid
	order by b.ItemID, Fixedcostid
else
	Select companyid, departmentid, Fixedcostid, FixedCostNo, fixedcostDate,
	FixedCostEnteredby, Remarks, b.ItemID, categoryid, Costvalue, Type,
	b.itemcategoryid, itemdescription, CategoryNameDescription  from
	#TempFixedCost a left outer join
	(select itemid,a.itemcategoryid,itemdescription,CategoryNameDescription from
	 aitem a ,aitemcategory b where  a.itemcategoryid=b.itemcategoryid)b
	on a.itemid=b.itemid where a.fixedCostId = (Select max(FixedCostId) from
	#TempFixedCost b where a.ItemId = b.ItemID)
	order by b.ItemID, Fixedcostid	
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc1]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.proc1    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 17/11/2001 9:22:15 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 09/03/2001 02:32:28 ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 12/05/00 1:40:15 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 10/17/00 2:19:50 PM ******/
/****** Object:  Stored Procedure dbo.proc1    Script Date: 10/7/00 11:07:57 AM ******/
CREATE procedure [dbo].[proc1] as
begin
	declare @n as int
	select @n=5
select max(costingvalue) from aitem where costingvalue in(select distinct top 5 costingvalue from aitem order by costingvalue)
end
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveSettings]    Script Date: 10/06/2012 14:17: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].[SpEmail_SaveSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_SaveSettings]
	@SMTP  varchar(50),
	@Password varchar(50),
	@Port int,
	@Fromaddress varchar(50),
	@OdbcName varchar(50),
	@OdbcUser varchar(50),
	@OdbcPassword varchar(50),
	@DatabaseName varchar(50),
	@CompanyId  int
as
begin
	select * from [dbo].[PIS_EmailSettings] where companyid=@CompanyId
	if @@rowcount>0
		begin
			UPDATE [dbo].[PIS_EmailSettings]
				SET [SMTP] = @SMTP
				,[Password] = @Password
				,[Port]=@Port
				,[Fromaddress]=@Fromaddress
				,[OdbcName]=@OdbcName
				,[OdbcUser]=@OdbcUser
				,[OdbcPassword]=@OdbcPassword
				,[DatabaseName]=@DatabaseName
			WHERE [CompanyId] = @CompanyId
		end
	else
		begin
			INSERT INTO [dbo].[PIS_EmailSettings]
				([SMTP]
				,[Password]
				,[Port]
				,[Fromaddress]
				,[OdbcName]
				,[OdbcUser]
				,[OdbcPassword]
				,[DatabaseName]
				,[CompanyId])
			VALUES
				(@SMTP
				,@Password
				,@Port
				,@Fromaddress
				,@OdbcName
				,@OdbcUser
				,@OdbcPassword
				,@DatabaseName
				,@CompanyId)
		end
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReportParameter]    Script Date: 10/06/2012 14:17: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].[SpEmail_SaveReportParameter]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_SaveReportParameter]
	@ReportId  int,
	@ParameterOrder int,
	@ParameterValue varchar(50),
	@CompanyId  int
as
begin
	INSERT INTO [dbo].[PIS_EmailSchedulerReportParameter]
	   ([ReportId]
	   ,[ParameterOrder]
	   ,[ParameterValue]
	   ,[CompanyId])
	VALUES
	   (@ReportId
	   ,@ParameterOrder
	   ,@ParameterValue
	   ,@CompanyId)
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReport]    Script Date: 10/06/2012 14:17: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].[SpEmail_SaveReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_SaveReport]
	@ReportId  int,
	@SendTime datetime,
	@Interval char(10),
	@MonthInterval  char(10),
	@WeekInterval  int,
	@Subject nvarchar(500),
	@Message nvarchar(1000),
	@CompanyId  int
as
begin
	UPDATE [dbo].[PIS_EmailScheduler]
		SET [SendTime] = @SendTime
		  ,[Interval] = @Interval
		  ,[MonthInterval] = @MonthInterval
		  ,[WeekInterval] = @WeekInterval
		  ,[Subject]=@Subject
		  ,[Message]=@Message
	WHERE [ReportId] = @ReportId and [CompanyId] = @CompanyId
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveRecepients]    Script Date: 10/06/2012 14:17: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].[SpEmail_SaveRecepients]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_SaveRecepients]
	@ReportId  int,
	@UserId int,
	@CompanyId  int
as
begin
	INSERT INTO [dbo].[PIS_EmailSchedulerRecepients]
	   ([ReportId]
	   ,[UserId]
	   ,[CompanyId])
	VALUES
	   (@ReportId
	   ,@UserId
	   ,@CompanyId)
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetUsers]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetUsers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create Procedure [dbo].[SpEmail_GetUsers]
@CompanyId int
as
begin	
	select us.userid,us.UserName,us.FullName,ug.description,us.emailid as ''Recepients''
	from dbo.aUsers us
		inner join ausergroups ug on ug.usergroupid=us.usergroupid and ug.companyid=us.companyid
	where us.companyid=@CompanyId and us.userid<>1
		order by us.userid
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetSettings]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_GetSettings]
	@CompanyId int
as
begin
	SELECT [SMTP]
	  ,[Password]
	  ,[Port]
	  ,[Fromaddress]
	  ,[OdbcName]
	  ,[OdbcUser]
	  ,[OdbcPassword]
	  ,[DatabaseName]
	FROM [dbo].[PIS_EmailSettings]
	where [CompanyId]=@CompanyId
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRepost]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetRepost]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_GetRepost]
	@CompanyId int
as
begin
	select * from dbo.PIS_EmailScheduler where companyid=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRecepients]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetRecepients]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_GetRecepients]
	@ReportId int,
	@CompanyId int
as
begin
	select Us.UserID,us.emailid as email,us.FullName from dbo.PIS_EmailSchedulerRecepients Resp
	inner join dbo.aUsers Us on Us.UserID= Resp.UserId  and us.companyid=Resp.CompanyId and us.userid<>1
	where Resp.ReportId=@ReportId and Resp.CompanyId=@CompanyId
end
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepostParameter]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetByIdRepostParameter]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_GetByIdRepostParameter]
	@ReportId int,
	@CompanyId int
as
begin
	SELECT [ParameterOrder]
		  ,[ParameterValue]
	  FROM [dbo].[PIS_EmailSchedulerReportParameter]
	where [ReportId]=@ReportId and [CompanyId]=@CompanyId
	order by [ParameterOrder]
end
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepost]    Script Date: 10/06/2012 14:17: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].[SpEmail_GetByIdRepost]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_GetByIdRepost]
	@ReportId int,
	@CompanyId int
as
begin
	SELECT [Discription]
	  ,[ReportPath]
	  ,[SendTime]
	  ,[Interval]
	  ,[MonthInterval]
	  ,[WeekInterval]
	  ,[Subject]
	  ,[Message]
	FROM [dbo].[PIS_EmailScheduler]
	where [ReportId]=@ReportId and [CompanyId]=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteReportParameter]    Script Date: 10/06/2012 14:17: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].[SpEmail_DeleteReportParameter]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_DeleteReportParameter]
	@ReportId  int,
	@CompanyId  int
as
begin
	DELETE FROM [dbo].[PIS_EmailSchedulerReportParameter]
WHERE ReportId=@ReportId and CompanyId=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteRecepients]    Script Date: 10/06/2012 14:17: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].[SpEmail_DeleteRecepients]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpEmail_DeleteRecepients]
	@ReportId  int,
	@CompanyId  int
as
begin
	DELETE FROM [dbo].[PIS_EmailSchedulerRecepients]
WHERE ReportId=@ReportId and CompanyId=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwGodownCloseDate]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownCloseDate]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 20/11/2001 9:58:55 AM ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 17/11/2001 9:21:11 PM ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 09/03/2001 02:32:25 ******/
/****** Object:  View dbo.vwGodownCloseDate    Script Date: 12/05/00 1:40:14 PM ******/
CREATE view [dbo].[vwGodownCloseDate] as
select max(gsstockdate) as closedate,gsgodownid as godownid from moigodownstockbackup group by gsgodownid'
GO
/****** Object:  View [dbo].[tempItems]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[tempItems]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[tempItems]
as
select  case when v.itemid is not null then vendoritemcode  else itemcode end as itemcode,
case when v.itemid is not null then vendoritemdesc else itemdescription end as itemdesc,i.itemid,v.vendorid
from aitem i  left join
avendoritem v on i.itemid=v.itemid'
GO
/****** Object:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationHeader]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_SaveDeliveryVerificationHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:  Regin T.
-- Create date: 15-07-2010
-- Description:
--   To save Delivery Verification Header
-- =============================================================================
CREATE PROC [dbo].[spMag_SaveDeliveryVerificationHeader]
-- Add the parameters of the stored procedure here
@CompanyId int,
@ShopId int,
@DeliveryDate datetime,
@AddUserId int,
@FinancialYearId int,
@DeliveryVerificationId int = null output
AS
BEGIN
--declare @StoreRequestNo as varchar(50)
--set @StoreRequestNo=dbo.GenereateNextTransactionnumber(@interfaceid,@FinancialYearId,@CompanyId,''D'',@DepartmentId)
-- Generate next delivery verification ID
SELECT @DeliveryVerificationId = case ISNULL(MAX(DeliveryVerificationId),0)
WHEN 0 THEN 1 ELSE MAX(DeliveryVerificationId)+1 END
FROM dbo.[losDeliveryVerificationHeader]
INSERT INTO [dbo].[losDeliveryVerificationHeader]
([CompanyId]
,[ShopId]
,[DeliveryVerificationId]
,[DeliveryDate]
,[AddUserId]
,[UpdateTime]
,[FinancialYearId]
)
VALUES
(@CompanyId
,@ShopId
,@DeliveryVerificationId
,@DeliveryDate
,@AddUserId
,getdate()
,@FinancialYearId
)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLogin]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckLogin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : Rajesh Kamalakshan
-- Create date : 18/03/2010
-- Description : To check the user name and password
-- =============================================
CREATE PROCEDURE [dbo].[spMagnolia_CheckLogin]--  ''fies'','''',1
-- Add the parameters for the stored procedure here
@UserName varchar(50),
@Password varchar(50),
@CompanyId int,
@Outs int =null output
AS
BEGIN
SELECT @Outs=UserId
FROM [dbo].ausers
WHERE
UserName=@UserName and
UserPwd=@Password and
CompanyID=@CompanyId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLlmsGetCard]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLlmsGetCard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[spLlmsGetCard]
as
select CardRegistrationID,CardNumber from LMSCardRegistration' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteCardRegistation]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeleteCardRegistation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[SpLmsDeleteCardRegistation]
@CardRegistrationID as int
as
Delete from      LMSCardRegistration where CardRegistrationID=@CardRegistrationID' 
END
GO
/****** Object:  View [dbo].[vwEligibleForDiscount]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwEligibleForDiscount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 20/11/2001 9:58:55 AM ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 17/11/2001 9:21:12 PM ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwEligibleForDiscount    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[vwEligibleForDiscount] as
select ItemDescription, max(DPQty) DPQty, max(WPQty) WPQty from aitem group by ItemDescription'
GO
/****** Object:  View [dbo].[vwcustomerGroupcategory]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerGroupcategory]'))
EXEC dbo.sp_executesql @statement = N'
-- Created  on  : 27/02/2007
-- Created by   : Shinu
-- Comments     :For taking Customer Group from table aCustomerGroup
--               Returns only Group having no Childs
--		:
-- Modified on  :
-- Modified by  :
-- Comments     :
CREATE view [dbo].[vwcustomerGroupcategory] as
select CompanyID,CusGroupId, CusGroupName from aCustomerGroup where CusGroupId not in (Select ParentGroupid from
aCustomerGroup)'
GO
/****** Object:  StoredProcedure [dbo].[spCompSalesValueWise]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompSalesValueWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on 	: 06/09/2002
-- Created by 	: hariharan
------------------------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 12/06/2003, 19/06/2003
-- Comments     : Added @strCategory parameter, Corrected bugs
------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spCompSalesValueWise] (@intyear as int, @strbrand as varchar(2000),
				  @strCategory as Varchar(2000)
				  ) AS
begin
	-- Assumption: reportid 2 is assumed for this report
	declare @intcount as int,
	@strwherecondition as varchar(3000),
	@strsql as nvarchar(4000),
	@intavgmonth as int
	set nocount on
	set @intavgmonth = 0.0
	set @strbrand = replace(@strbrand,''/'','''')
	truncate table tempvaluewise
	-- the in operator to be replaced
	set @strsql = ''select year(poshbilldate) soldyear,
	month(poshbilldate) soldmonth, sum(quantity) qty, sum(costofsales) cog,
	sum(salesvalue) sales, 0.0  from vwsalesanalysisbyitem vws, aitem i '' +
	'' where vws.posditemid = i.itemid''
	
	If @strBrand <> ''''
	Begin
		Set @strSql = @strSql + '' and i.brand in ('' + @strbrand + '')''
	End
	
	If @strCategory <> ''''
	Begin
		Set @strSql = @strSql + '' And i.ItemCategoryId In ('' + @strCategory + '')''
	End
	Set @strSql = @strSql + '' group by year(poshbilldate), month(poshbilldate) ''
	insert into tempvaluewise
	exec sp_executesql @strsql
	select @intavgmonth = count(distinct(soldmonth)) from tempvaluewise
	where soldyear = @intyear
	update tempvaluewise set avgnoofmonth = @intavgmonth
	set nocount off
End -- procedure' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCompSalesQuantityWise]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCompSalesQuantityWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on  : 30/08/2002
-- Created by  : leo
----------------------------------------------------------------
-- Modified on  : 12/06/2003
-- Modified by  : Kishore
-- Comments     : Added strCategory in parameters and query
--                (On comparison with v2)
----------------------------------------------------------------
-- Modified on  : 29/08/2009
-- Modified by  : Benzigar S D
-- Comments     : changed @strWhereConditionGdn part
----------------------------------------------------------------
--RefNo : 01
--Modified On  : 20/09/2010
--Modified by  : VinothMurugan V.
--Purpose    : didn''t Mention column Name properly So error will arise.
--Some times passing null values so that dynamic quiry not execute.
--Client   : Alia
----------------------------------------------------------
--spCompSalesQuantityWise 2010, ''''''YAMAHA'''', ''''STANLEY'''''',''11''
CREATE  PROCEDURE [dbo].[spCompSalesQuantityWise] (@intYear as int,
@strBrand as varchar(2000),
@strCategory as Varchar(3500)) AS
begin
-- Assumption: reportid 1 is assumed for this report
declare @intrangecount as int,
@intcount as int,
@strCaseStmt as varchar(750),
@numstartprice as numeric(18,2),
@numendprice as numeric(18,2),
@strWhereCondition as varchar(3000),
@strsql as nvarchar(4000),
@intavgmonth as int,
@strCaseStmtgdn as varchar(3000),
@strCaseStmtpos as varchar(3000),
@strWhereConditionGdn as varchar(3000),
@strWhereConditionPos as varchar(3000)
CREATE TABLE #tempqtywise (
[soldyear] [int] NULL ,
[soldmonth] [int] NULL ,
[range1qty] [numeric](18, 2) NULL ,
[range2qty] [numeric](18, 2) NULL ,
[range3qty] [numeric](18, 2) NULL ,
[range4qty] [numeric](18, 2) NULL ,
[range5qty] [numeric](18, 2) NULL ,
[range6qty] [numeric](18, 2) NULL
)
CREATE TABLE #tempgdnstock (
[range1gdnqty] [numeric](18, 2) NULL ,
[range2gdnqty] [numeric](18, 2) NULL ,
[range3gdnqty] [numeric](18, 2) NULL ,
[range4gdnqty] [numeric](18, 2) NULL ,
[range5gdnqty] [numeric](18, 2) NULL ,
[range6gdnqty] [numeric](18, 2) NULL ,
[range1gdnvalue] [numeric](18, 2) NULL ,
[range2gdnvalue] [numeric](18, 2) NULL ,
[range3gdnvalue] [numeric](18, 2) NULL ,
[range4gdnvalue] [numeric](18, 2) NULL ,
[range5gdnvalue] [numeric](18, 2) NULL ,
[range6gdnvalue] [numeric](18, 2) NULL ,
summary char(1) null
)
CREATE TABLE #tempposstock (
[range1posqty] [numeric](18, 2) NULL ,
[range2posqty] [numeric](18, 2) NULL ,
[range3posqty] [numeric](18, 2) NULL ,
[range4posqty] [numeric](18, 2) NULL ,
[range5posqty] [numeric](18, 2) NULL ,
[range6posqty] [numeric](18, 2) NULL ,
[range1posvalue] [numeric](18, 2) NULL ,
[range2posvalue] [numeric](18, 2) NULL ,
[range3posvalue] [numeric](18, 2) NULL ,
[range4posvalue] [numeric](18, 2) NULL ,
[range5posvalue] [numeric](18, 2) NULL ,
[range6posvalue] [numeric](18, 2) NULL ,
summary char(1) null
)
set nocount on
set @intrangecount =0
set @intcount =0
set @strCaseStmt = ''''
set @numstartprice =0.0
set @numendprice =0.0
set @intavgmonth = 0.0
set @strbrand  = replace(@strbrand,''/'','''')  -- hari 020906
-- seleting the minmum and max price to be considered in the report
select @numstartprice = isnull(fromrange,0) from reportrangevalues where reportid =1 and
rangedetailid = 1
select @numendprice = isnull(torange,0) from reportrangevalues where reportid =1 and
rangedetailid = 6
-- arriving on the where condition to fetch data on price
if @numendprice =0.0
set @strWhereCondition = '' where avgcost >= '' + lTrim(rTrim(convert(varchar(20),
@numstartprice)))
else
set @strWhereCondition = '' where avgcost between '' + lTrim(rTrim(convert(varchar(20),
@numstartprice))) +
'' and '' + lTrim(rTrim(convert(varchar(20),@numendprice)))
-- to form the select case based on the no of entries in range table
select @intrangecount = count(*) from reportrangevalues where reportid = 1
-- forming the case statment for using in select
set @strCaseStmt = ''''
while @intcount < @intrangecount
begin
set @intcount = @intcount + 1
if @intcount <> 6
Begin
select @strCaseStmt = @strCaseStmt + ''case when avgcost between '' + lTrim(rTrim(convert(varchar(20),fromrange)))
+ '' and '' + lTrim(rTrim(convert(varchar(20),torange))) + '' then Quantity end ['' + lTrim(rTrim(rangecode)) + ''], '' from reportrangevalues
where reportid = 1 and  rangedetailid =  @intcount
End
else
begin -- last condition
if @numendprice =0.0
Begin
select @strCaseStmt = @strCaseStmt + ''case when avgcost >= '' + lTrim(rTrim(convert(varchar(20), fromrange))) +
'' then Quantity end ['' + lTrim(rTrim(rangecode)) + '']''  from
reportrangevalues where reportid = 1 and rangedetailid =  @intcount
end
else
Begin
select @strCaseStmt = @strCaseStmt + ''case when avgcost between '' + lTrim(rTrim(convert(varchar(20),fromrange)))
+ '' and '' + lTrim(rTrim(convert(varchar(20),torange))) + '' then Quantity end ['' + lTrim(rTrim(rangecode)) +'']''
from reportrangevalues where reportid = 1 and rangedetailid =  @intcount
End
end -- for else
end
--formaing the wherecondition for gdn stock
set @strWhereConditionGdn =''''
set @strWhereConditionGdn = replace(@strWhereCondition, ''avgcost'', ''itemrate'')
set @strWhereConditionGdn = @strWhereConditionGdn + '' and i.itemid = gs.gsitemid''
If @strBrand <> ''''
Begin
-- Benzigar 29/08/2009 commented and added below condition
--set @strWhereConditionGdn = @strWhereConditionGdn + '' and replace(brand,"/"," ") in ('' + @strbrand + '')''
set @strWhereConditionGdn = @strWhereConditionGdn + '' and i.brand in ('' + @strbrand + '')''
End
If @strCategory <> ''''
Begin
set @strWhereConditionGdn = @strWhereConditionGdn + '' and i.ItemCategoryId in ('' + @strCategory + '')''
End
Set @strWhereConditionGdn = @strWhereConditionGdn + '' group by itemrate''
--formaing the wherecondition for pos stock
set @strWhereConditionPos =''''
set @strWhereConditionPos = replace(@strWhereCondition, ''avgcost'', ''itemrate'')
set @strWhereConditionPos = @strWhereConditionPos + '' and i.itemid = ss.itemid ''
If @strBrand <> ''''
Begin
set @strWhereConditionPos = @strWhereConditionPos + '' and i.brand in ('' + @strbrand + '')''
End
If @strCategory <> ''''
Begin
set @strWhereConditionPos = @strWhereConditionPos + '' and i.ItemCategoryId in ('' + @strCategory + '')''
End
Set @strWhereConditionPos = @strWhereConditionPos + '' group by itemrate''
set @strWhereCondition = @strWhereCondition + '' and (year(poshbilldate) = '' + convert(varchar(4),@intyear) +
'' or year(poshbilldate) = '' + convert(varchar(4),@intyear-1) + '')''
If @strBrand <> ''''
Begin
Set @strWhereCondition = @strWhereCondition + '' and i.brand in ('' + @strbrand + '')''
End
-- the in operator to be replaced
If @strCaseStmt <> ''''
Begin
set @strsql = ''select year(poshbilldate) soldyear, month(poshbilldate) soldmonth, '' + @strCaseStmt + ''  from ''
+ ''vwsalesanalysisbyitem vws, aitem i '' + @strWhereCondition + '' and '' + '' vws.posditemid = i.itemid ''
End
Else
Begin
set @strsql = ''select year(poshbilldate) soldyear, month(poshbilldate) soldmonth  from ''
+ ''vwsalesanalysisbyitem vws, aitem i '' + @strWhereCondition + '' and '' + '' vws.posditemid = i.itemid ''
End
----------------------------------------RefNo : 01
--
-- insert into #tempqtywise
-- exec sp_executesql @strsql
If @strCaseStmt <> ''''
Begin
insert into #tempqtywise
exec sp_executesql @strsql
end
else
begin
insert into #tempqtywise(soldyear,soldmonth)
exec sp_executesql @strsql
end
----------------------------------------
update #tempqtywise set range1qty =0.0 where range1qty is null
update #tempqtywise set range2qty =0.0 where range2qty is null
update #tempqtywise set range3qty =0.0 where range3qty is null
update #tempqtywise set range4qty =0.0 where range4qty is null
update #tempqtywise set range5qty =0.0 where range5qty is null
update #tempqtywise set range6qty =0.0 where range6qty is null
truncate table tempqtywisegrouped
insert into tempqtywisegrouped
select soldyear, soldmonth, 1, sum(range1qty), 0, 0.0, 0.0      from #tempqtywise group by soldyear, soldmonth
insert into tempqtywisegrouped
select soldyear, soldmonth, 2, sum(range2qty), 0, 0.0, 0.0 from #tempqtywise group by soldyear, soldmonth
insert into tempqtywisegrouped
select soldyear, soldmonth, 3, sum(range3qty), 0, 0.0, 0.0 from #tempqtywise group by soldyear, soldmonth
insert into tempqtywisegrouped
select soldyear, soldmonth, 4, sum(range4qty), 0, 0.0, 0.0 from #tempqtywise group by soldyear, soldmonth
insert into tempqtywisegrouped
select soldyear, soldmonth, 5, sum(range5qty), 0, 0.0, 0.0 from #tempqtywise group by soldyear, soldmonth
insert into tempqtywisegrouped
select soldyear, soldmonth, 6, sum(range6qty), 0, 0.0, 0.0 from #tempqtywise group by soldyear, soldmonth
select @intavgmonth = count(distinct(soldmonthgrp)) from tempqtywisegrouped where soldyeargrp = @intyear
update tempqtywisegrouped set avgmonth = @intavgmonth
-- for the stock calcuation
set @strCaseStmtgdn =''''
-- forming the case statment based on range for godown stock
set @strCaseStmtgdn = replace(@strCaseStmt, ''avgcost'', ''itemrate'')
set @strCaseStmtgdn = replace(@strCaseStmtgdn, ''Quantity'', ''sum(gsstock)'')
if (@strCaseStmtgdn <>'''')----RefNo : 01
begin
set @strCaseStmtgdn = @strCaseStmtgdn + '','' + replace(@strCaseStmtgdn, ''sum(gsstock)'', ''sum(gsstock * itemrate)'')
set @strsql =''''
set @strsql = ''select '' + @strCaseStmtgdn + '',''''d'''' from moigodownstock gs, aitem i '' + @strWhereConditionGdn
insert into #tempgdnstock
exec sp_executesql @strsql
update #tempgdnstock set range1gdnqty =0.0 where range1gdnqty is null
update #tempgdnstock set range2gdnqty =0.0 where range2gdnqty is null
update #tempgdnstock set range3gdnqty =0.0 where range3gdnqty is null
update #tempgdnstock set range4gdnqty =0.0 where range4gdnqty is null
update #tempgdnstock set range5gdnqty =0.0 where range5gdnqty is null
update #tempgdnstock set range6gdnqty =0.0 where range6gdnqty is null
update #tempgdnstock set range1gdnvalue =0.0 where range1gdnvalue is null
update #tempgdnstock set range2gdnvalue =0.0 where range2gdnvalue is null
update #tempgdnstock set range3gdnvalue =0.0 where range3gdnvalue is null
update #tempgdnstock set range4gdnvalue =0.0 where range4gdnvalue is null
update #tempgdnstock set range5gdnvalue =0.0 where range5gdnvalue is null
update #tempgdnstock set range6gdnvalue =0.0 where range6gdnvalue is null
end
insert into #tempgdnstock
select sum(range1gdnqty), sum(range2gdnqty), sum(range3gdnqty),
sum(range4gdnqty), sum(range5gdnqty), sum(range6gdnqty),
sum(range1gdnvalue), sum(range2gdnvalue), sum(range3gdnvalue),
sum(range4gdnvalue), sum(range5gdnvalue), sum(range6gdnvalue), ''s'' from #tempgdnstock
update tempqtywisegrouped set currentstock = range1gdnqty,
stockvalue = range1gdnvalue
from #tempgdnstock
where soldyeargrp = @intyear and rangedetail =1 and summary =''s''
update tempqtywisegrouped set currentstock = range2gdnqty, stockvalue = range2gdnvalue from #tempgdnstock
where soldyeargrp = @intyear and rangedetail =2 and summary =''s''
update tempqtywisegrouped set currentstock = range3gdnqty, stockvalue = range3gdnvalue from #tempgdnstock
where soldyeargrp = @intyear and rangedetail =3 and summary =''s''
update tempqtywisegrouped set currentstock = range4gdnqty, stockvalue = range4gdnvalue from #tempgdnstock
where soldyeargrp = @intyear and rangedetail = 4 and summary =''s''
update tempqtywisegrouped set currentstock = range5gdnqty, stockvalue = range5gdnvalue from #tempgdnstock
where soldyeargrp = @intyear and rangedetail = 5 and summary =''s''
update tempqtywisegrouped set currentstock = range6gdnqty, stockvalue = range6gdnvalue from #tempgdnstock
where soldyeargrp = @intyear and rangedetail = 6 and summary =''s''
-- for the pos stock calcuation
set @strCaseStmtpos =''''
-- forming the case statment based on range for godown stock
set @strCaseStmtpos = replace(@strCaseStmt, ''avgcost'', ''itemrate'')
set @strCaseStmtpos = replace(@strCaseStmtpos, ''Quantity'', ''sum(stock)'')
if (@strCaseStmtpos <>'''')--RefNo : 01
begin
set @strCaseStmtpos = @strCaseStmtpos + '','' + replace(@strCaseStmtpos, ''sum(stock)'', ''sum(stock * itemrate)'')
set @strsql =''''
set @strsql = ''select '' + @strCaseStmtpos + '',''''d'''' from mosshopstock ss, aitem i '' + @strWhereConditionPos
insert into #tempposstock
exec sp_executesql @strsql
update #tempposstock set range1posqty = 0.0 where range1posqty is null
update #tempposstock set range2posqty = 0.0 where range2posqty is null
update #tempposstock set range3posqty = 0.0 where range3posqty is null
update #tempposstock set range4posqty = 0.0 where range4posqty is null
update #tempposstock set range5posqty = 0.0 where range5posqty is null
update #tempposstock set range6posqty = 0.0 where range6posqty is null
update #tempposstock set range1posvalue = 0.0 where range1posvalue is null
update #tempposstock set range2posvalue = 0.0 where range2posvalue is null
update #tempposstock set range3posvalue = 0.0 where range3posvalue is null
update #tempposstock set range4posvalue = 0.0 where range4posvalue is null
update #tempposstock set range5posvalue = 0.0 where range5posvalue is null
update #tempposstock set range6posvalue = 0.0 where range6posvalue is null
end
insert into #tempposstock
select sum(range1posqty), sum(range2posqty), sum(range3posqty),
sum(range4posqty), sum(range5posqty), sum(range6posqty), sum(range1posvalue), sum(range2posvalue), sum(range3posvalue),
sum(range4posvalue), sum(range5posvalue), sum(range6posvalue), ''s'' from #tempposstock
update tempqtywisegrouped set currentstock = currentstock + range1posqty, stockvalue = stockvalue + range1posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail =1 and summary =''s''
update tempqtywisegrouped set currentstock = currentstock + range2posqty, stockvalue = stockvalue + range2posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail =2 and summary =''s''
update tempqtywisegrouped set currentstock = currentstock + range3posqty, stockvalue = stockvalue + range3posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail =3 and summary =''s''
update tempqtywisegrouped set currentstock = currentstock + range4posqty, stockvalue = stockvalue + range4posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail = 4 and summary =''s''
update tempqtywisegrouped set currentstock = currentstock + range5posqty, stockvalue = stockvalue + range5posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail = 5 and summary =''s''
update tempqtywisegrouped set currentstock = currentstock + range6posqty, stockvalue = stockvalue + range6posvalue
from #tempposstock where soldyeargrp = @intyear and rangedetail = 6 and summary =''s''
drop table #tempqtywise
drop table #tempgdnstock
drop table #tempposstock
set nocount off
end -- procedure' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDateWiseSalesReport]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDateWiseSalesReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--exec spDateWiseSalesReport  1,''R'',''20030101'',''20030105'',0,0,0
-------------------------------------------------------------------------
--Created  on	: 16/05/2003
--Created  by	: R Harikrishnan
--Verified By 	: Hariharan
--Verified Date	: 30/04/2004(updated from Devl Db)
--Comments	: For Reports
-------------------------------------------------------------------------
CREATE procedure [dbo].[spDateWiseSalesReport]
	@intCompanyID		as int,
	@strDateRangeType 	as char(1),
	@strFromDate 		as varchar(8),
	@strToDate 		as varchar(8),
	@intShopID 		as int,
	@intDeptID		as int,
	@intChkDeptID		as int
--set @intCompanyID = 1
--set @strDateRangeType =''R''
--set @strFromDate =''20030301''
--set @strToDate =''20030312''
--set @intShopID =0
--set @intDeptID =0
--set @intChkDeptID=0
as
set nocount on	
CREATE table #tempSales
	(
		companyid 	int,
		departmentid 	int,
		shopid 		int,
		billdate 	datetime,
		cashsales 	numeric(18,2),
		dcashsales 	numeric(18,2),
		ccashsales 	numeric(18,2),
		creditcard 	numeric(18,2),
		dcreditcard 	numeric(18,2),
		ccreditcard 	numeric(18,2),
		debitcard 	numeric(18,2),
		ddebitcard 	numeric(18,2),
		cdebitcard 	numeric(18,2),
		receipts 	numeric(18,2),
		dreceipts 	numeric(18,2),
		creceipts 	numeric(18,2),
		payments 	numeric(18,2),
		dpayments 	numeric(18,2),
		cpayments 	numeric(18,2),
		creditsales 	numeric(18,2),
		dcreditsales 	numeric(18,2),
		ccreditsales 	numeric(18,2),
		localpurchase 	numeric(18,2),
		dlocalpurchase 	numeric(18,2),
		clocalpurchase 	numeric(18,2),
		RowOrder 	tinyint,
		Type		varchar(100),
		ShopName	Varchar(250),
		colOrder	tinyint
	)
declare @strSQL as nvarchar(2000),@intDateDiff as smallint
if @strDateRangeType=''R''
	set @intDateDiff=datediff(dd,convert(datetime,@strFromDate),convert(datetime,@strtoDate))+1
-- cashsales
set @strSQl = N''
insert into #tempSales
select cs.companyid ,cs.departmentid, cs.shopid, billdate, sum(actamount) cashsales,
sum(damount) dcashsales, sum(camount) 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, 0.0 as localpurchase,
0.0 as dlocalpurchase, 0.0 as clocalpurchase,1 RowOrder, ''''Cash Sales'''' Type,s.ShopName, 1 ColOrder
from vwcashsalestruncated cs Left outer Join aShops s on cs.companyID=s.companyID and
cs.shopid=s.shopID, aAccountmaster am where
am.misc=''''CA'''' and cs.accountid = am.accountid and cs.companyid = am.companyid
and cash = 1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
if @intdeptid>0
	set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
exec sp_Executesql @strSQl
--Credit Card
set @strSQl = N''
insert into #tempSales
select cs.companyid ,cs.departmentid, cs.shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2),sum(actamount)) as creditcard, convert(numeric(18,2),sum(damount)) as dcreditcard,
convert(numeric(18,2),sum(camount)) 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, 0.0 as localpurchase, 0.0 as dlocalpurchase,
0.0 as clocalpurchase,1 RowOrder, ''''Cash Sales'''' Type ,s.ShopName, 1 ColOrder
from vwcashsalestruncated cs Left outer Join aShops s on cs.companyID=s.companyID and
cs.shopid=s.shopID, aaccountmaster am
where am.misc = ''''CC'''' and cs.accountid = am.accountid and cs.companyid = am.companyid
and cash=1''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
exec sp_Executesql @strSQl
--debit card sales
set @strSQl = N''
insert into #tempSales
select cs.companyid,cs.departmentid, cs.shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, convert(numeric(18,2),sum(actamount))
as debitcard, convert(numeric(18,2),sum(damount)) as ddebitcard, convert(numeric(18,2),sum(camount))
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, 1 RowOrder, ''''Cash Sales'''' Type ,s.ShopName, 1 ColOrder
from vwcashsalestruncated cs Left outer Join aShops s on cs.companyID=s.companyID and
cs.shopid=s.shopID, aaccountmaster am where
am.misc =''''DC'''' and cs.accountid = am.accountid and cs.companyid = am.companyid
and cash=1 ''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and billdate between '''''' + @strFromDate + ''''''and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
exec sp_Executesql @strSQl
--credit sales
Set @strSQl = N''
insert into #tempSales
select cs.companyid ,cs.departmentid, cs.shopid, billdate, 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, convert(numeric(18,2),sum(actamount)) as creditsales,
convert(numeric(18,2),sum(damount)) as dcreditsales, convert(numeric(18,2),sum(camount))
as ccreditsales, 0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase
,2 RowOrder, ''''Credit Sales'''',s.ShopName, 1 ColOrder from vwcashsalestruncated cs Left outer Join
aShops s on cs.companyID=s.companyID and cs.shopid=s.shopID where cs.cash=0 ''
set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and cs.billdate between '''''' + @strFromDate + N'''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by cs.companyid ,cs.departmentid, cs.shopid, cs.billdate, s.ShopName''
exec sp_Executesql @strSQl
--Receipts
set @strSQl = N''
insert into #tempSales
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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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,5 RowOrder, ''''Reciepts'''' Type,s.ShopName, 1 ColOrder
from losDummyReceiptHeader rh LEFT OUTER JOIN aShops s ON rh.drCompanyid=s.CompanyID and rh.drShopID=s.ShopID, acustomermaster cm
where rh.drcustomerid=cm.customerid and rh.drcompanyid=cm.companyid
and drcancelled=0''
set @strSQL=@strSQL + N'' and drcompanyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and drshopID='' + convert(varchar(10),@intShopID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and drdepartmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and drdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQl=@strSQl + '' group by drcompanyid, drdepartmentid, drshopid, drdate, s.ShopName''
exec sp_Executesql @strSQl
--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
set @strSQl = N''
insert into #tempSales
select rh.companyid,rh.departmentid, s.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,2),sum(customeramount)) receipts,
convert(numeric(18,2),sum(amount * depexrate)) dreceipts,
convert(numeric(18,2),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,5 RowOrder, ''''Reciepts'''',s.ShopName, 1 ColOrder
from receiptvoucherheader rh,receiptvoucherdetails rd, ashops s
where rh.receiptid=rd.receiptid and rh.companyid = rd.companyid
and rh.departmentid=s.departmentid and rh.cancelled=0 and s.companyid=rh.companyid and
((rh.dummyreceiptid is null and rh.recshopid is null) or
(rh.dummyreceiptid=0 and rh.recshopid=0)) ''
set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
if @intShopID>0
	set @strSQL=@strSQL + N'' and s.shopid='' + convert(varchar(10),@intShopID)
if @intDeptID>0
	set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
if @strDateRangeType=''R''
	set @strSQL=@strSQL + N'' and rh.receiptdate between '''''' + @strFromDate + '''''' and '''''' + @strTodate + ''''''''
set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, s.shopid, rh.receiptdate, s.ShopName''
exec sp_Executesql @strSQl
if @intDateDiff<=0
	set @intDateDiff=1
insert into #tempSales
select
	companyid ,departmentid ,shopid , billdate ,sum(cashsales) ,sum(dcashsales) ,
	sum(ccashsales) ,sum(creditcard) ,sum(dcreditcard) ,sum(ccreditcard) ,sum(debitcard) ,
	sum(ddebitcard) ,sum(cdebitcard) ,sum(receipts) ,sum(dreceipts) ,sum(creceipts) ,
	sum(payments) ,sum(dpayments) ,sum(cpayments) ,sum(creditsales) ,sum(dcreditsales) ,
	sum(ccreditsales) ,sum(localpurchase) ,sum(dlocalpurchase) ,sum(clocalpurchase) ,
	3 RowOrder ,''Revenue'' Type ,ShopName , 1 ColOrder
from 	
	#tempSales
where
	roworder<3 and shopID is not null
group by
	companyid ,departmentid ,shopid , billdate ,ShopName
insert into #tempSales
select
	companyid ,departmentid ,shopid , billdate ,sum(cashsales)/@intDateDiff ,
	sum(dcashsales)/@intDateDiff ,sum(ccashsales)/@intDateDiff ,
	sum(creditcard)/@intDateDiff ,sum(dcreditcard)/@intDateDiff ,
	sum(ccreditcard)/@intDateDiff ,sum(debitcard)/@intDateDiff ,
	sum(ddebitcard)/@intDateDiff ,sum(cdebitcard)/@intDateDiff ,
	sum(receipts)/@intDateDiff ,sum(dreceipts)/@intDateDiff ,
	sum(creceipts)/@intDateDiff ,sum(payments)/@intDateDiff ,
	sum(dpayments)/@intDateDiff ,sum(cpayments)/@intDateDiff ,
	sum(creditsales)/@intDateDiff ,sum(dcreditsales)/@intDateDiff ,
	sum(ccreditsales)/@intDateDiff ,sum(localpurchase)/@intDateDiff ,
	sum(dlocalpurchase)/@intDateDiff ,sum(clocalpurchase)/@intDateDiff ,
	4 RowOrder ,''Daily Average'' Type ,ShopName , 1 ColOrder
from 	
	#tempSales
where
	roworder<3 and shopID is not null
group by
	companyid ,departmentid ,shopid , billdate ,ShopName
insert into #tempSales
select
	companyid ,departmentid ,shopid , billdate ,sum(cashsales)/@intDateDiff ,
	sum(dcashsales)/@intDateDiff ,sum(ccashsales)/@intDateDiff ,
	sum(creditcard)/@intDateDiff ,sum(dcreditcard)/@intDateDiff ,
	sum(ccreditcard)/@intDateDiff ,sum(debitcard)/@intDateDiff ,
	sum(ddebitcard)/@intDateDiff ,sum(cdebitcard)/@intDateDiff ,
	sum(receipts)/@intDateDiff ,sum(dreceipts)/@intDateDiff ,
	sum(creceipts)/@intDateDiff ,sum(payments)/@intDateDiff ,
	sum(dpayments)/@intDateDiff ,sum(cpayments)/@intDateDiff ,
	sum(creditsales)/@intDateDiff ,sum(dcreditsales)/@intDateDiff ,
	sum(ccreditsales)/@intDateDiff ,sum(localpurchase)/@intDateDiff ,
	sum(dlocalpurchase)/@intDateDiff ,sum(clocalpurchase)/@intDateDiff ,
	6 RowOrder ,''Daily Average'' Type ,ShopName, 1 ColOrder
from 	
	#tempSales
where
	roworder=5 and shopID is not null
group by
	companyid ,departmentid ,shopid , billdate ,ShopName
select
	companyid,departmentid, shopid, billdate,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
		else convert(numeric(18,2),sum(dcashsales)) end cashsales,
	convert(numeric(18,2),sum(dcashsales)) dcashsales,
	convert(numeric(18,2),sum(ccashsales)) ccashsales,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
		else convert(numeric(18,2),sum(dreceipts)) end receipts,
	convert(numeric(18,2),sum(dreceipts)) dreceipts,
	convert(numeric(18,2),sum(creceipts)) creceipts,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
		else convert(numeric(18,2),sum(dpayments)) end payments,
	convert(numeric(18,2),sum(dpayments)) dpayments ,
	convert(numeric(18,2),sum(cpayments)) cpayments ,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
		else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
	convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
	convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
		else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
	convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
	convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
		else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
	convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
	convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
		else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
	convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
	convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
	RowOrder, Type, ShopName,@intDateDiff TotalDays, 1 ColOrder
from
	#tempsales
where
	shopID is not null
group by
	companyID,departmentID,shopID,Billdate,RowOrder, Type, ShopName, colOrder
union all
--declare @intChkDeptID		as int
--declare @intDateDiff		as int
--set @intChkDeptID=0
select
	a.companyid,0, 0, '''',
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
		else convert(numeric(18,2),sum(dcashsales)) end cashsales,
	convert(numeric(18,2),sum(dcashsales)) dcashsales,
	convert(numeric(18,2),sum(ccashsales)) ccashsales,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
		else convert(numeric(18,2),sum(dreceipts)) end receipts,
	convert(numeric(18,2),sum(dreceipts)) dreceipts,
	convert(numeric(18,2),sum(creceipts)) creceipts,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
		else convert(numeric(18,2),sum(dpayments)) end payments,
	convert(numeric(18,2),sum(dpayments)) dpayments ,
	convert(numeric(18,2),sum(cpayments)) cpayments ,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
		else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
	convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
	convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
		else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
	convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
	convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
		else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
	convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
	convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
	case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
		else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
	convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
	convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
	RowOrder, Type,b.Name shopname,@intDateDiff TotalDays, 2 ColOrder
from
	#tempsales a, aCompanyMaster b
where
	a.companyID=b.CompanyID and shopID is not null
group by
	a.companyID,RowOrder, Type,b.Name
order by RowOrder,Type
drop table #tempsales
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDeletePOSdummyDetail]    Script Date: 10/06/2012 14:17: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].[spDeletePOSdummyDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Created By : Aneesh
--Created On : 14-09-2006
--Purpose    : To delete details in the POS Detail Table [losPosDetail]
--Modified BY	: Rajesh Kamalskshan
--Modifies On	: 1-05-2007
--Purpose	: for using in dummy pos bill
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spDeletePOSdummyDetail]
@intBillId As Int,
@intShopId As Int
As
	Begin
		Delete From losPosdummyDetail Where posdShopId=@intShopId
	And posdbillID=@intBillId
	End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetExpiryEmailSettings]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[spGetExpiryEmailSettings]
AS
BEGIN
	SET NOCOUNT ON
		SELECT
			SMTPhost,
			Port,
			DisplayName,
			UserName,
			EmailID,
			Password,
			GracePeriod
	
		FROM [dbo].ExpiryEmailSettings
		
	SET NOCOUNT OFF
END
------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwHPAdvaneShopReceipt]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAdvaneShopReceipt]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by :  Prasanth
Created on : 30/05/2008
Modified by :
Modified on :
Purpose      : To Get the Hire Purchase Processing Details (Invocie,Quotation,ItemRegistration,Processing)
*/
CREATE view [dbo].[vwHPAdvaneShopReceipt] as
select hprhCompanyID,hprhShopiD,hprhReceiptID,HprhReceiptNo,HprhReceiptDate,hprhReceiptType,
hprhReceiptAmount,c.hpCustName,c.HpCustPermanentAdd,Q.hpQhQuotationNo,hprhBankName,hprhChequeNo, hprhCancel from losHpCustomerDetails c,
losHpReceiptHeader inner join losHpInvoiceheader Q on hprhHPQuotationID=Q.hpqhQuotationID
where c.hpCustid=hprhCustomerID and hprhReceiptType=''A'''
GO
/****** Object:  View [dbo].[vwhpAdvanceReceived]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpAdvanceReceived]'))
EXEC dbo.sp_executesql @statement = N'
---Created by         : Prasanth Joseph
---Created on         : 14-12-2007
---Created For        : Get report for Advance paid Customer Details
---Modified by        :
---Modified On        :
Create view [dbo].[vwhpAdvanceReceived] as
select h.hprhCompanyId,c.hpcustName,q.hpqhQuotationNo,h.hprhReceiptNo,h.hprhReceiptDate,h.hprhReceiptAmount,h.hprhCustomerID
from loshpreceiptHeader h left outer join loshpInvoiceHeader q on h.hprhhpQuotationID=q.hpqhQuotationID
left outer join loshpCustomerdetails c on h.hprhCustomerID=c.hpCustID
where h.hprhCancel=0 and hprhReceiptType=''A'''
GO
/****** Object:  View [dbo].[vwHpShopReceipt]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpShopReceipt]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHpShopReceipt] as
select h.hprhCompanyID,h.hprhShopid,h.hprhReceiptNO,h.hprhReceiptId,h.hprhReceiptDate,
h.hprhReceipttype,h.hprhReceiptAmount,h.hprhinvBal,c.hpCustName,
hprhBankName,h.HprhChequeNo,
inv.hpqhQuotationNo,d.hprdSettelmentAmount, h.hprhCancel
from loshPreceiptHeader h,losHpReceiptDetail d,losHpinvoiceheader inv,losHpCustomerDetails c
where h.hprhCompanyID=d.hprdCompanyID and h.hprhShopid=d.hprdShopid
and h.hprhReceiptId=d.hprdReceiptId and d.hprdInvoiceid=inv.hpqhQuotationId
and c.hpCustID=h.hprhCustomeriD
and h.hprhReceiptType=''S'''
GO
/****** Object:  View [dbo].[vwHPSettiementReceipts]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPSettiementReceipts]'))
EXEC dbo.sp_executesql @statement = N'
---Created By       : Prasanth Joseph
---Created on       : 06-12-2007
---Created For      : To get the Hire Purchase SettlementAmount
---Modified By      :
---Modified on      :
create view [dbo].[vwHPSettiementReceipts] as
-----Accounts Receipts
select companyid, customerid, shopid, max(Tdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) SettledAmt  from(
select rh.hprhCompanyID as CompanyID,rh.hprhCustomerId as CustomerID,rh.hprhReceiptDate as Tdate,
rh.hprhreceiptno as refno,rd.hprdPaymentID invoiceID,null Shopid,rh.hprhAmount settledamt
from ahpReceiptHeader rh,ahpReceiptDetail rd
where rh.hprhCompanyID=rd.hprdCompanyID and rh.hprhReceiptId=rd.hprdreceiptID
and rh.hprhCancel=0
and rh.hprhCustomerid is not null
and rd.hprdPaymentID is not null
union all
----Shopreceipts
select rh.hprhCompanyID as CompanyID,rh.hprhCustomerId as CustomerID,rh.hprhReceiptDate as Tdate,
rh.hprhreceiptno as refno,rd.hprdInvoiceiD invoiceID,rh.hprhShopID Shopid,rd.hprdSettelmentAmount settledamt
from losHpreceiptHeader rh,losHPReceiptDetail rd
where rh.hprhCompanyID=rd.hprdCompanyID and rh.hprhReceiptId=rd.hprdreceiptID
and rh.hprhCancel=0
and rh.hprhCustomerid is not null
and rd.hprdInvoiceID is not null)settledaccinvoices
group by companyid, customerid, shopid, invoiceid'
GO
/****** Object:  View [dbo].[vwhpunsettledProcessing]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpunsettledProcessing]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwhpunsettledProcessing] as
select rd.hprdProcessingId ProcessingID,rd.hprdShopid shopid from loshpreceiptheader rh inner join loshpreceiptdetail rd on
hprhReceiptID=hprdReceiptID and hprhShopID=hprdShopId and hprhCancel=0
where hprhReceiptID in (
select hpdReceiptID from (ahppaymentheader inner join loshpCustomerdetails on hphCustomerID=hpCustID)
inner join ahppaymentdetail on hphPaymentID=hpdPaymentID and hphCompanyID=hpdCompanyID
and hphDepartmentID=hpdDepartmentID
where hphCancel=0 and hphPAymentID not in (
select hprdPaymentID from  ahpReceiptdetail
inner join ahpReceiptHEader on hprdReceiptID=hprhReceiptID and hprdDepartmentID=hprhDepartmentID
and hprhCancel=0))'
GO
/****** Object:  View [dbo].[vwshopexpirystock]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopexpirystock]'))
EXEC dbo.sp_executesql @statement = N'
--Created on 	: 22/02/03
--Created by 	: leo
CREATE view [dbo].[vwshopexpirystock] as
select eadshopid, eadexpirydate, eaditemid, sum(quantity) stock from
(select eadshopid, eadexpirydate, eaditemid, sum(eaditemqty) quantity from losexpiryarrivaldetails where
eadcancel = 0 group by eadshopid, eadexpirydate, eaditemid
union all
select eidshopid, eidexpirydate, eiditemid, - sum(eiditemqty) quantity  from losexpiryissuedetails where
eidcancel = 0 group by eidshopid, eidexpirydate, eiditemid) s group by eadshopid, eadexpirydate, eaditemid'
GO
/****** Object:  View [dbo].[vwShopHPInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopHPInvoiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on          : 26/11/2003
-- Created by  : Kishore
-- Comments  :  For Getting HirePurchase SettlementDetails
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopHPInvoiceSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
accinvoiceid, sum(settledamt) SettledAmt
from
(
select hprhcompanyid companyid, hprhcustomerid customerid, hprhreceiptdate setdate, hprhreceiptno refno,
hprdinvoiceid accinvoiceid, hprdshopid shopid, hprdsettelmentAmount settledamt
from loshpreceiptheader,loshpreceiptDetail
where hprhcompanyid = hprdcompanyid
and hprhreceiptid =hprdreceiptid
and hprhcancel = 0
and hprhcustomerid is not null
and hprdinvoiceid is not null) settledaccinvoices
group by companyid, customerid, shopid, accinvoiceid'
GO
/****** Object:  View [dbo].[vwserialnoshopstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoshopstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnoshopstock] as
SELECT SerialNo, ShopId, ItemId, SUM(qty) qty
FROM (SELECT sadSerialNo SerialNo, sadShopId ShopId,  sadItemId ItemId , SUM(sadItemQty) Qty
FROM losSerialArrivalDetails WHERE  sadCancel = 0
GROUP BY sadSerialNo, sadShopId, sadItemId UNION ALL
SELECT sidSerialNo, sidShopId, sidItemId, - SUM(sidItemQty)
FROM losSerialIssueDetails WHERE sidCancel = 0
GROUP BY sidSerialNo, sidShopId, sidItemId) a GROUP BY SerialNo, ShopId, ItemId HAVING Sum(qty) > 0'
GO
/****** Object:  View [dbo].[vwserialnoissueshopstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoissueshopstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnoissueshopstock] as
select  sidSerialNo SerialNo, sidShopId ShopId,  sidItemId ItemId,sum(sidItemQty) Qty,sidinterfaceid interfaceid
FROM losSerialissueDetails WHERE  sidCancel = 0 group by sidSerialNo, sidinterfaceid,sidShopId,sidItemId'
GO
/****** Object:  View [dbo].[vwserialnoissuegodownstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoissuegodownstock]'))
EXEC dbo.sp_executesql @statement = N'
Create view [dbo].[vwserialnoissuegodownstock]   as
SELECT sidSerialNo SerialNo, sidgodownId GodownId,  sidItemId ItemId , sum(sidItemQty) Qty, sidinterfaceid interfaceid
FROM loiSerialissueDetails WHERE  sidCancel = 0 group by sidSerialNo, sidinterfaceid,sidgodownId,sidItemId'
GO
/****** Object:  View [dbo].[vwserialnogodownstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnogodownstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnogodownstock] as
SELECT SerialNo, GodownId, ItemId, SUM(qty) qty
FROM (SELECT sadSerialNo SerialNo, sadgodownId GodownId,  sadItemId ItemId , SUM(sadItemQty) Qty
FROM loiSerialArrivalDetails WHERE  sadCancel = 0
GROUP BY sadSerialNo, sadgodownId, sadItemId UNION ALL
SELECT sidSerialNo, sidgodownId, sidItemId, - SUM(sidItemQty)
FROM loiSerialIssueDetails WHERE sidCancel = 0
GROUP BY sidSerialNo, sidgodownId, sidItemId) a GROUP BY SerialNo, GodownId, ItemId HAVING Sum(qty) > 0'
GO
/****** Object:  View [dbo].[vwpurchaseorderothcharge]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchaseorderothcharge]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwpurchaseorderothcharge] as
select POorderID,SUM(POAmount)POAmount from lopurchaseorderothcharge group by POorderID'
GO
/****** Object:  View [dbo].[vwAllMergeDetails]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllMergeDetails]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by  : Kishore
-- Created on  : 23/08/2003
-- Comments    : This view unions loiMergeDetails and losMergeDetails
--               and returns the sum of qunatity (taken from v2)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwAllMergeDetails] AS
--
SELECT ItemId, HeaderId, CompanyId, SUM(Quantity) Quantity FROM
(SELECT lgdId, lgdCompanyId CompanyId, lgdGodownId LocationId,
lgdItemId ItemId, lgsdQty Quantity, lghRefMergeId HeaderId
FROM loiMergeDetails Details, loiMergeHeader Header
WHERE Details.lgdId = Header.lghId
AND Details.lgdGodownId = Header.lghGodownId
AND Details.lgdCompanyId = Header.lghCompanyId
AND Header.lghTransFinished = 1
AND Header.lghCancelled = 0
--
UNION ALL
--
SELECT lsdId MergeId, lsdCompanyId CompanyId, lsdShopId LocationId,
lsdItemId ItemId, lsdQty Quantity, lshRefMergeId HeaderId
FROM losMergeDetails Details, losMergeHeader Header
WHERE Details.lsdId = Header.lshId
AND Header.lshTransFinished = 1
AND Header.lshCancelled = 0
AND Details.lsdShopId = Header.lshShopId
AND Details.lsdCompanyId = Header.lshCompanyId) a
GROUP BY ItemId, HeaderId, CompanyId'
GO
/****** Object:  View [dbo].[vwvendorItemDescription]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwvendorItemDescription]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwvendorItemDescription] AS
/*select aitem.ItemID,avendoritem.vendorid,case when avendoritem.itemid is not null then aitem.itemdescription
when avendoritem.itemid is null then
case when aitem.colorid is not null and aitem.sizeid is not null and aitem.did is not null then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is not null and aitem.did is null) then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename )
when (aitem.colorid is null and aitem.sizeid is not null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + colorname + '' - '' + dname)
when aitem.did is not null then convert(varchar(250), ItemDescription + '' - '' + dname)
when aitem.colorid is not null then convert(varchar(250), ItemDescription + '' - '' + colorname )
when aitem.sizeid is not null then convert(varchar(250), ItemDescription + '' - '' + sizename )
when aitem.colorid is null and aitem.sizeid is null and aitem.did is null  then
convert(varchar(250), ItemDescription ) end end as itemdescription,
case when avendoritem.vendoritemcode is not null then aitem.itemcode
when avendoritem.vendoritemcode is null then itemcode end code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid
from aitem left outer join acolor on aitem.colorid = acolor.colorid
left outer join asize on aitem.sizeid = asize.sizeid
left outer join avendoritem on aitem.itemid=avendoritem.itemid
left outer join adistributormaster dist on aitem.did = dist.did, aunit au
where aitem.unitsid = au.unitid
UNION ALL*/
select ItemID,Null VendorID,
case when aitem.colorid is not null and aitem.sizeid is not null and aitem.did is not null then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is not null and aitem.did is null) then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename )
when (aitem.colorid is null and aitem.sizeid is not null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + colorname + '' - '' + dname)
when aitem.did is not null then convert(varchar(250), ItemDescription + '' - '' + dname)
when aitem.colorid is not null then convert(varchar(250), ItemDescription + '' - '' + colorname )
when aitem.sizeid is not null then convert(varchar(250), ItemDescription + '' - '' + sizename )
when aitem.colorid is null and aitem.sizeid is null and aitem.did is null  then
convert(varchar(250), ItemDescription ) end as itemdescription, itemcode code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid
from aitem left outer join acolor on aitem.colorid = acolor.colorid
left outer join asize on aitem.sizeid = asize.sizeid
left outer join adistributormaster dist on aitem.did = dist.did, aunit au
where aitem.unitsid = au.unitid'
GO
/****** Object:  View [dbo].[vwVendorGroupcategory]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorGroupcategory]'))
EXEC dbo.sp_executesql @statement = N'
-- Created  on  : 27/02/2007
-- Created by   : Shinu
-- Comments     :For taking Vendor Group from table aVendorGroup
--               Returns only Group having no Childs
--		:
-- Modified on  :
-- Modified by  :
-- Comments     :
CREATE view [dbo].[vwVendorGroupcategory] as
select CompanyID,VenGroupId, VenGroupName from aVendorGroup where VenGroupId not in (Select ParentGroupid from
aVendorGroup)'
GO
/****** Object:  View [dbo].[vwitemDescriptionprint]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemDescriptionprint]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwitemDescriptionprint    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwitemDescriptionprint    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwitemDescriptionprint    Script Date: 31/07/2002 2:00:26 PM ******/
CREATE view [dbo].[vwitemDescriptionprint] as
select ItemID ,
case when aitem.colorid is not null and aitem.sizeid is not null then
ItemDescription + '' - '' + colorname + '' - '' + sizename
when aitem.colorid is not null  then ItemDescription + '' - '' + colorname
when aitem.sizeid is not null then ItemDescription + '' - '' + sizename
when aitem.colorid is null and aitem.sizeid is null then ItemDescription
end as itemdescription  from aitem
left outer join acolor on aitem.colorid = acolor.colorid
left outer join asize on aitem.sizeid = asize.sizeid'
GO
/****** Object:  View [dbo].[vwItemDescription1]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription1]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwItemDescription1] AS
select ItemID,
case when aitem.colorid is not null and aitem.sizeid is not null and aitem.did is not null then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is not null and aitem.did is null) then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename )
when (aitem.colorid is null and aitem.sizeid is not null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + colorname + '' - '' + dname)
when aitem.did is not null then convert(varchar(250), ItemDescription + '' - '' + dname)
when aitem.colorid is not null then convert(varchar(250), ItemDescription + '' - '' + colorname )
when aitem.sizeid is not null then convert(varchar(250), ItemDescription + '' - '' + sizename )
when aitem.colorid is null and aitem.sizeid is null and aitem.did is null  then
convert(varchar(250), ItemDescription ) end as itemdescription, itemcode code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid
from aitem left outer join acolor on aitem.colorid = acolor.colorid
left outer join asize on aitem.sizeid = asize.sizeid
left outer join adistributormaster dist on aitem.did = dist.did, aunit au
where aitem.unitsid = au.unitid'
GO
/****** Object:  View [dbo].[vwItemDescription_ASKholdings]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDescription_ASKholdings]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on  : 14/11/2003, 11/03/2004
-- Modified by  : Hariharan R
-- Comments             : Renamed the field Active to vwActive
--                        in order to avoice conflicting with aItem.Active
--                        whereever this view and aitem are joined
--   : Unitcode, brand, Itemcategoryid added
--   : modified to take first 250 characters of itemdescription
--   : Modified By      : Benzigar S D
--   : Modified On      : 17/09/2009
--   : Comment          : For ask added Brand and Modelno
-----------------------------------------------------
Create VIEW [dbo].[vwItemDescription_ASKholdings] AS
select  ItemID,case when (vBrand is not null or vBrand<>'''') and (ModelNo is not null or ModelNo<>'''') then
convert(varchar(250),itemdescription + '' - '' + vBrand + '' - '' + ModelNo)
when (vBrand is not null or vBrand<>'''') then
convert(varchar(250),itemdescription + '' - '' + vBrand)
when (ModelNo is not null or ModelNo<>'''') then
convert(varchar(250),itemdescription + '' - '' + ModelNo)
when (vBrand is null or vBrand='''') and (ModelNo is  null or ModelNo='''') then
convert(varchar(250), ItemDescription)
end as itemdescription,code, vwActive,  vunitcode,
vUnitName,  vBrand, vItemCategoryid,ModelNo
from
(select ItemID,
case when aitem.colorid is not null and aitem.sizeid is not null and aitem.did is not null then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is not null and aitem.did is null) then
convert(varchar(250),ItemDescription + '' - '' + colorname + '' - '' + sizename )
when (aitem.colorid is null and aitem.sizeid is not null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + sizename + '' - '' + dname)
when (aitem.colorid is not null and aitem.sizeid is null and aitem.did is not null) then
convert(varchar(250), ItemDescription + '' - '' + colorname + '' - '' + dname)
when aitem.did is not null then convert(varchar(250), ItemDescription + '' - '' + dname)
when aitem.colorid is not null then convert(varchar(250), ItemDescription + '' - '' + colorname )
when aitem.sizeid is not null then convert(varchar(250), ItemDescription + '' - '' + sizename )
when aitem.colorid is null and aitem.sizeid is null and aitem.did is null  then
convert(varchar(250), ItemDescription ) end as itemdescription,
itemcode code, aItem.Active vwActive, unitcode vunitcode,
UnitName vUnitName, Brand vBrand, ItemCategoryid vItemCategoryid,ModelNo
from aitem left outer join acolor on aitem.colorid = acolor.colorid
left outer join asize on aitem.sizeid = asize.sizeid
left outer join adistributormaster dist on aitem.did = dist.did, aunit au
where aitem.unitsid = au.unitid) Itemdetails'
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesForBudget]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpShopItemSalesForBudget]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified on                  : 22/07/2004
--Modified by                  : venkitesh
--Comments                     : Created for Budgeting item sales value taking
--
CREATE Proc [dbo].[SpShopItemSalesForBudget] (@intitemid as int,
	@intdepartmentid as int, @intmonthid as int,@intyearid as int,
@intcategoryid as int=0)
as
set nocount on
-- 1
begin
declare
@strCondition as varchar(200),
@strquery nvarchar(4000)
Create table #ShopItemSalesForBudget
(
itemid integer,
ItemCategoryid integer,
costprice numeric(18,2),
dcostprice numeric(18,2),
ccostprice numeric(18,2),
amount numeric(18,2),
damount numeric(18,2),
camount numeric(18,2)
)
if @intcategoryid =0
set @strCondition = '' = ''+ CONVERT(VARCHAR(25),@intitemid)	
else
set @strCondition = '' in ( select itemid from aitem where itemcategoryid = ''+
convert(varchar(10), @intcategoryid )+'')''
set @strquery =''insert into #ShopItemSalesForBudget
select
	posditemid,0,
	sum(posdcostprice * posdQuantity ) costprice,
	sum(posdcostprice * poshDepExRate * posdQuantity) dcostprice,
	sum(posdcostprice * poshExchangeRate * posdQuantity) ccostprice,
	sum(convert(numeric(18, 2),posdUnitPrice)) Amount,
	sum(convert(numeric(18, 2),posdUnitPrice * poshExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),posdUnitPrice * poshDepExRate)) dAmount
from
		losposdetail, losposheader
where
	poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0
	and month(poshBilldate)=''+convert(varchar(5),convert(varchar(4),@intmonthid)) +	
	''and year(poshBilldate)=''+convert(varchar(5),convert(varchar(5),@intyearid))  +
	''and posditemid ''+ @strcondition +'' and poshDepartmentid=''+
	convert(varchar(3),@intdepartmentid)+
''group by
	posditemid, month(poshBilldate) ''
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	iditemid,0, sum(idcostprice * idQuantity)costprice,
	sum(idcostprice * ihDepExRate * idQuantity)dcostprice,
	sum(idcostprice * ihExchangeRate * idQuantity) ccostprice,
	sum(convert(numeric(18, 2),idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),idUnitPrice * ihExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),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''''
	and month(ihInvoicedate)=''+ convert(varchar(4),@intmonthid) +
	'' and year(ihInvoicedate)=''+ convert(varchar(5),@intyearid) +
	''and iditemid ''+@strcondition  + ''and ihDepartmentID=''+
	convert(varchar(3),@intdepartmentid) + '' group by iditemid ''
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select  seditemid, 0, sum(sedcostprice * sedQuantity) costprice,
	sum(sedcostprice *  sehDepExRate * sedQuantity ) dcostprice,
	sum(sedcostprice * sehExchangeRate * sedQuantity) ccostprice,
	sum(convert(numeric(18, 2),sedUnitPrice))  Amount,
	sum(convert(numeric(18, 2),sedUnitPrice * sehExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),sedUnitPrice * sehDepExRate)) dAmount
from
	losposexchangeheader, losposexchangedetail
where
	sedExchangeid = sehExchangeID and sedShopID = sehShopid and
	SEHCANCELLED = 0 and sedbillorexchange  = ''''E''''
	and month(sehExchangeDate)=''+ convert(varchar(4),@intmonthid) +''and year(sehExchangeDate)='' + convert(varchar(5),@intyearid) +
	'' and seditemid ''+ @strcondition +'' and sehDepartmentID= ''+ convert(varchar(3),@intdepartmentid) +
''group by
	seditemid''
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	iditemid,0,sum(idcostprice * reqQty)costprice,
	sum(idcostprice * ihDepExRate * reqQty) dcostprice,
	sum(idcostprice * ihExchangeRate * reqQty) ccostprice,
	sum(convert(numeric(18, 2),idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),idUnitPrice * ihExchangeRate))  cAmount,
	sum(convert(numeric(18, 2),idUnitPrice * ihDepExRate))  Amount
from
	 losspecialinvoicedetail, losspecialinvoiceheader ,ashops a,adepartmentmaster b
where
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND
	IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0
	and IhTransFinished = 1 and a.departmentid=b.departmentid
	and month(ihInvoicedate)='' + convert(varchar(4),@intmonthid) +''and year(ihInvoicedate)='' + convert(varchar(5),@intyearid) +
	''and iditemid ''+ @strcondition +'' and b.departmentid= ''+ convert(varchar(3),@intdepartmentid) +
''group by
	iditemid ''
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	seditemid, 0,
	-sum(sedcostprice*sedExchangeQty) costprice,
	-sum(sedcostprice * sehDepExRate * sedExchangeQty)Dcostprice ,
	-sum(sedcostprice * sehExchangeRate* sedExchangeQty) Ccostprice,
	sum(convert(numeric(18, 2),- sedUnitPrice)) Amount,
	sum(convert(numeric(18, 2),- sedUnitPrice * sehexchangerate))  cAmount,
	sum(convert(numeric(18, 2),- sedUnitPrice * sehDepExRate))  dAmount
from
	losposexchangeheader, losposexchangedetail
where
	sedExchangeid = sehExchangeID and sedShopID = sehShopid and
	SEHCANCELLED = 0 and sedbillorexchange  =  ''''B'''' and sedexchangeqty>0
	and month(sehExchangeDate)=''+ convert(varchar(4),@intmonthid) + ''and year(sehExchangeDate)='' + convert(varchar(5),@intyearid) +
	''and seditemid ''+  @strcondition + ''and sehDepartmentID='' + convert(varchar(3),@intdepartmentid) +
''group by
	seditemid ''
-- 6
-- Special invoice return
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	iditemid,0,sum(idcostprice * Reqqty) costprice,
	sum(idcostprice * ihDepExRate* Reqqty) Dcostprice,
	sum(idcostprice * ihExchangeRate* Reqqty) Ccostprice,
	sum(convert(numeric(18, 2),-idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),-idUnitPrice * ihExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),-idUnitPrice * ihDepExRate)) dAmount
from
	 losspecialinvoicedetail,losspecialinvoiceheader
where
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
	idratetype = 1 and ihproforma = 0 and ihTransFinished = 1
	and month(ihInvoicedate)='' + convert(varchar(4),@intmonthid) +
	''and year(ihInvoicedate)='' + convert(varchar(5),@intyearid) +
	'' and iditemid '' + @strCondition + ''and IhDepartmentID='' +
	convert(varchar(3),@intdepartmentid) + ''group by iditemid ''
-- 7
-- (- Qty has to be minus so when multiplying - * - =+ so i am removing the - on values )
--venkitesh 150403
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
Select 	grnditemid,0,sum(grncostprice * GRNDQuantity) costprice,
	sum(grncostprice * grnhDepExRate * GRNDQuantity) dcostprice,
	sum(grncostprice * grnhExchangeRate * GRNDQuantity) Ccostprice,
	sum(convert(numeric(18, 2),-grndUnitPrice)) Amount,
	sum(convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),-grndUnitPrice * grnhDepExRate)) dAmount
from
	losgoodsreturnnoteheader, losgoodsreturnnotedetail
where 	
	GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and
	grnhShopid =  GRNDShopid AND GrnhCancel = 0
	and month(GrnhGoodsreturnnoteDate)=''+ convert(varchar(4),@intmonthid) +
	'' and year(GrnhGoodsreturnnoteDate)= ''+ convert(varchar(5),@intyearid) +
	'' and grnditemid ''+ @strCondition + '' and grnhDepartmentid=''
	+ convert(varchar(3),@intdepartmentid) + ''group by grnditemid ''
-- 8
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	repinvdpartsid,0,
	sum(repinvdcostprice * repinvdqty) costprice,
	sum( repinvdcostprice *  seinvhDepExRate * repinvdqty) Dcostprice,
	sum(repinvdcostprice * serinvhcmpexrate * repinvdqty) Ccostprice,
	sum(convert(numeric(18, 2),RepInvDRate * repinvpackqty)) Amount,
	sum(convert(numeric(18, 2),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty)) cAmount,
	sum(convert(numeric(18, 2),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty)) dAmount
from
	losinvoicedpartsreplacedetails,  losserviceinvheader
where
	serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND
	serinvhcancelled = 0
	and month(serinvhdate)=''+ convert(varchar(4),@intmonthid) + ''and year(serinvhdate)=''+ convert(varchar(5),@intyearid) +
	''and repinvdpartsid ''+  @strcondition + ''and serinvhdepartmentid=''+ convert(varchar(3),@intdepartmentid) +
'' group by
	repinvdpartsid ''
-- 9
exec sp_Executesql @strquery
set @strquery =''insert into #ShopItemSalesForBudget
select
	reditemid,0, sum(redcostprice * redQuantity) costprice,
	sum(redcostprice * rehDepExRate * redQuantity) dcostprice,
	sum(redcostprice * rehExchangeRate * redQuantity) ccostprice,
	sum(convert(numeric(18, 2),redUnitPrice)) Amount,
	sum(convert(numeric(18, 2),redUnitPrice * rehExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),redUnitPrice * rehDepExRate)) Amount
from
	losExportDetail,  losExportHeader
where
	rehExportID = redExportID and rehShopID = redShopID AND
	rehCancelled = 0 and rehproforma = 0 and rehtype = ''''i''''
	and month(rehExportDate)=''+ convert(varchar(4),@intmonthid) +'' and year(rehExportDate)=''+ convert(varchar(5),@intyearid) +
	'' and reditemid ''+  @strcondition +'' and rehDepartmentID='' + convert(varchar(3),@intdepartmentid) +
''group by
	reditemid ''
exec sp_Executesql @strquery
	if @intcategoryid =0
		select * from #ShopItemSalesForBudget
	else
	begin
		update #ShopItemSalesForBudget
		set #ShopItemSalesForBudget.ItemCategoryid = a.itemcategoryid
		from aitem  a
		where #ShopItemSalesForBudget.itemid = a.itemid
		
		select ItemCategoryid ,sum(costprice)costprice,
		sum(dcostprice)dcostprice,sum(ccostprice)ccostprice,
		sum(amount)amount,sum(damount)damount,
		sum(camount)cmaount  from #ShopItemSalesForBudget
		group by ItemCategoryid
	end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spreportInformation]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spreportInformation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spreportInformation](@reportId as int,
				@mdulecode as varchar(10),
				@modcode as varchar(10))
as
declare @intcatid as int
declare @intdetid as int
create table #reptemp(ReportcatName  varchar(50),
		      ReportDetName  varchar(50),
		      ReportName    varchar(50),
		      ReportConst   varchar(20))				
begin
set nocount on
	if @reportId>0 and  @mdulecode=''''
		begin
		insert into #reptemp
			select h.repCatName,d.RepDetailName,r.ReportName,r.Reportconst
			from reportcategoryheader h,reportcategorydetail d,areports r
			where  r.ReportCatId=d.RepCatId and r.ReportDetailId=d.RepDetailId
			and d.RepCatId=h.repCatId and ReportID=@reportId
		select ReportcatName,ReportDetName,ReportName,ReportConst from #reptemp
		delete from #reptemp
			drop table #reptemp
	end
else
if @reportId>0 and  @mdulecode<>'''' and @modcode<>''''
begin
		select r.ReportName,d.RepDetailName,h.repCatName,r.Reportconst
			from reportcategoryheader h,reportcategorydetail d,areports r
			where  r.ReportCatId=d.RepCatId and r.ReportDetailId=d.RepDetailId
			and d.RepCatId=h.repCatId and h.repCatModCode=@mdulecode
	union all
		select r.ReportName,d.RepDetailName,h.repCatName,r.Reportconst
			from reportcategoryheader h,reportcategorydetail d,areports r
			where  r.ReportCatId=d.RepCatId and r.ReportDetailId=d.RepDetailId
			and d.RepCatId=h.repCatId and h.repCatModCode=@modcode
		
end
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spQuotereplaceSelPrice]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuotereplaceSelPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 17/11/2001 9:22:18 PM ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spQuotereplaceSelPrice    Script Date: 09/03/2001 02:32:28 ******/
CREATE PROCEDURE [dbo].[spQuotereplaceSelPrice] (@strin  varchar(250) ) AS
Select itemid from aitem a where replace(a.ItemDescription,"''","?") =@strin' 
END
GO
/****** Object:  View [dbo].[vwAllMergeHeader]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllMergeHeader]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by  : Kishore
-- Created on  : 23/08/2003
-- Comments    : This view unions loiMergeHeader and losMergeHeader
--               and returns mainly the sum of qunatity (Taken from v2)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwAllMergeHeader] AS
--
SELECT ItemId, HeaderId, CompanyId, SUM(Quantity) Quantity FROM
(SELECT lghId, lghCompanyId CompanyId, lghGodownId LocationId,
lghItemId ItemId, lghQty Quantity, lghRefMergeId HeaderId
FROM loiMergeHeader  Header
WHERE Header.lghTransFinished = 1
AND Header.lghCancelled = 0
--
UNION ALL
--
SELECT lshId MergeId, lshCompanyId CompanyId, lshShopId LocationId,
lshItemId ItemId, lshQty Quantity, lshRefMergeId HeaderId
FROM losMergeHeader Header
WHERE Header.lshTransFinished = 1
AND Header.lshCancelled = 0) a
GROUP BY ItemId, HeaderId, CompanyId'
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyDetail]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSdummyDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : Aneesh
--Created On : 14-09-2006
--Purpose    : To insert/update details to the POS Detail Table [losPosDetail]
--Modified BY : Rajesh Kamalskshan
--Modifies On : 1-05-2007
--Purpose : for using in dummy pos bill
-----------------------------------------------------------------------------------------------------------------------------
--Modified by   : Bijesh.B
--Date Modified : 21/09/2011
--Description   : GST feature added jyothish added colums field
-----------------------------------------------------------------------------------------------------------------------------
--Modified by   : Bijesh.B
--Date Modified : 12/10/2011
--Description   : changed @intUnitPrice As Numeric(18,2) to  @intUnitPrice As Numeric(18,8)
--                and  @NumItemTaxAmount as  Numeric(18,8)
-----------------------------------------------------------------------------------------------------------------------------
--Modified by   : Shine Das
--Date Modified : 22/11/2011
--Description   : BillDetailId added
-- Ref No 01
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spInsertPOSdummyDetail]
@intBillId As Int,
@intShopId As Int,
@intItemId As int,
@intPackId As Int,
@intUnitId As Int,
@intPQty As Numeric(18,3),
@intBillQty As Numeric(18,3),
@intUnitPrice As Numeric(18,8),
@intRateType As Int,
@intActUP As Numeric(18,2),
@intCostPrice As Numeric(18,2),
@strNotes As Varchar(250),
@intBlockPrice As Numeric(18,2),
@intGuarantee As Varchar(250),
@intFreeQty As Numeric(18,3),
@intSerialNo As Varchar(250),
@intItemSlno As Int,
-- @intItemVarFlag As Int,
-- @intCmpVarFlag As Int
@NumItemTaxPercentage as Numeric(18,2),
@NumItemTaxAmount as  Numeric(18,8),
@intItemTaxCatId as int,
@intBillDetailID as int     -- Ref No 01
As
Begin
Insert InTo losPosdummyDetail
(posdShopID,
posdBillID,
posdItemID,
posdPackingTypeID,
posdPUnitID,
posdPQuantity,
posdQuantity,
posdUnitPrice,
posdRateType,
posdActualUnitPrice,
posdcostprice,
posddescription,
posdblockprice,
posdguarantee,
rowguid,
posdSerialNo,
posdFreeQuantity,
posdItemSerialNo,
posdItemTaxAmount,
posdItemTaxCategory,
posdItemTaxPercentage,
posdbilldetailid) -- Ref No 01
Values(@intShopId,@intBillId,@intItemId,@intPackId,@intUnitId,@intPQty,@intBillQty,
@intUnitPrice,@intRateType,@intActUP,@intCostPrice,@strNotes,@intBlockPrice,@intGuarantee,NewId(),@intSerialNo,
@intFreeQty,@intItemSlno,@NumItemTaxAmount,@intItemTaxCatId,@NumItemTaxPercentage,@intBillDetailID)--,@intItemVarFlag,@intCmpVarFlag) -- Ref No 01
End' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[GetIndexColumns]    Script Date: 10/06/2012 14:17: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].[GetIndexColumns]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- Returns the list of columns in the index
CREATE FUNCTION [dbo].[GetIndexColumns]
(
@table_name SYSNAME,
@object_id INT,
@index_id TINYINT
)
RETURNS NVARCHAR(4000)
AS
BEGIN
DECLARE
@colnames NVARCHAR(4000),
@thisColID INT,
@thisColName SYSNAME
SET @colnames = INDEX_COL(@table_name, @index_id, 1)
+ dbo.GetIndexColumnOrder(@object_id, @index_id, 1)
SET @thisColID = 2
SET @thisColName = INDEX_COL(@table_name, @index_id, @thisColID)
+ dbo.GetIndexColumnOrder(@object_id, @index_id, @thisColID)
WHILE (@thisColName IS NOT NULL)
BEGIN
SET @thisColID = @thisColID + 1
SET @colnames = @colnames + '', '' + @thisColName
SET @thisColName = INDEX_COL(@table_name, @index_id, @thisColID)
+ dbo.GetIndexColumnOrder(@object_id, @index_id, @thisColID)
END
RETURN @colNames
END' 
END
GO
/****** Object:  View [dbo].[vwHPOutstandingAmount]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOutstandingAmount]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by  : Regin
Created on  : 01/10/2008
Modified by :
Modified on :
Purpose     : To Get outstanding amount of all hire purchase customers
*/
CREATE view [dbo].[vwHPOutstandingAmount] as
select InvoiceID, sum(Amount) OutstandingAmount
from
(
-- Invoice Amount (+)
select hpqhQuotationID InvoiceID, hpqhInstPrice Amount
from losHpInvoiceHeader where hpqhType=''I''  and hpqhCancel = 0
union all
-- Down Payment (-)
select hpqhQuotationID InvoiceID, -hpqhFirstInstAmt Amount
from losHpInvoiceHeader where hpqhType=''I''  and hpqhCancel = 0
union all
-- Settled Amount (-)
select hprdInvoiceID InvoiceID, -sum(hprdSettelmentAmount) Amount
from loshpreceiptdetail, loshpreceiptheader
where hprdReceiptID = hprhReceiptID and  hprhcancel = 0
group by hprdInvoiceID
union all
-- HP Paments (+)
select lrd.hprdInvoiceID InvoiceID, sum(lrd.hprdSettelmentAmount) Amount
from ahppaymentDetail pd inner join ahppaymentHeader ph on hpdPaymentID=hphPaymentID and ph.hphCancel = 0
left outer join loshpreceiptdetail lrd on pd.hpdReceiptID=lrd.hprdReceiptID
and pd.hpdProcessingDetailID=lrd.hprdProcessingDetailId
group by lrd.hprdInvoiceID
union all
-- HP Receipts (-)
select lrd.hprdInvoiceID InvoiceID, -sum(lrd.hprdSettelmentAmount) Amount
from ahpReceiptDetail rd
left outer join ahppaymentDetail pd on rd.hprdPaymentID=pd.hpdPaymentID
left outer join loshpReceiptDetail lrd on pd.hpdReceiptID=lrd.hprdReceiptID
and pd.hpdProcessingDetailID=lrd.hprdProcessingDetailId, ahpReceiptHeader
where rd.hprdReceiptID=hprhReceiptID and hprhCancel = 0
group by hprdInvoiceID
) a
--where InvoiceID=629
group by InvoiceID'
GO
/****** Object:  StoredProcedure [dbo].[spSaveExpiryEmailSettings]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSaveExpiryEmailSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
-----------------------------------------------------------------------------------------------------------------------------------
--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
-------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwbookingservinvoices]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingservinvoices]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY  : Hariharan R
--Modified Date : 14/03/2004
----------------------------------------------------------------------------------------
--Modified on :02-12-2011
--Modified by :MANUNADH. U
--comments    :Add Tax Amount with Service invoice Amount
--Ref.No      :<<Ref.No1>>
----------------------------------------------------------------------------------------
--Ref.No:2
--Modified on :12-12-2011
--Modified by :AADYAKUMAR D V
--comments    :Rollback Ref.No.1 ,serinvhamount already include tax
--Reason      : FIR-232619
----------------------------------------------------------------------------------------
--Ref.No:3
--Modified on :29-02-2012
--Modified by :AADYAKUMAR D V
--comments    :Adding new column serinvhTaxamount
--Reason      : FGY-413407
----------------------------------------------------------------------------------------
CREATE view [dbo].[vwbookingservinvoices] as
select
li.serinvhcompanyid companyid, li.serinvhdepartmentid, li.serinvhshopid shopid,
li.serinvhrefno refno,li.serinvhid invoiceid, li.serinvno invoiceno,
li.serinvhdate invoicedate, li.serinvhduedate, serinvhCustomerId customerid,
--isnull(li.serinvhamount,0)+ISNULL(li.serinvhTaxamount,0)serinvhamount ,--<<Ref.No1>>  --Ref.No:2
isnull(li.serinvhamount,0)serinvhamount ,
0 as settled, ''SBI'' as type, isnull(li.serinvhrefno,'''') referenceno,
isnull(li.serinvhremarks,'''') remarks,li.serinvhupdatetime, serinvhcmpexrate,
li.serinvfinancialid, seinvhdepexrate,li.serinvhexchangerates, serinvhpreparedby,
ISNULL(serinvhTaxamount,0) serinvhTaxamount --Ref.No:3
from
losserviceinvheader li
where
li.serinvhcancelled=0 and (serinvhcashacc is null or serinvhcashacc=0)
and serinvhCustomerId is not null and li.serinvhamount>0'
GO
/****** Object:  View [dbo].[vwbrandcategory]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbrandcategory]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwbrandcategory    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwbrandcategory] as
--created the brand category view to have the brand name with respect to category
select itemcategoryid,brand  from aitem group by itemcategoryid,brand'
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysismax]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetActualAnalysismax]'))
EXEC dbo.sp_executesql @statement = N'
--Created By  : Reji Abraham
--Created  Date : 25/09/2003
CREATE view [dbo].[vwBudgetActualAnalysismax] as
select max(bchCheckID) maxid,bchcompanyid from budgetCheckDetail bd,budgetCheckheader bh where
bd.bcdCheckID=bh.bchcheckid and bd.bcdCompanyID=bh.bchCompanyID and bchCancelled=0 group by bcdBudgetAllocID,bchCompanyID'
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchItem]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchItem]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===========================================================
-- Author:		SREEJITH GA
-- Create date: 30/04/2010
-- Description:	TO FETCH ALL ITEMS TO THE MASTER GRID IN ITEMFETCH PAGE
-- ===========================================================
CREATE PROC [dbo].[SpMag_FetchItem]
@Shopid INT
AS
SELECT DISTINCT(a.itemid), a.itemcode, v.itemdescription,  p.packingtypename, a.brand,
a.modelno,p.PackingTypeID,a.Part_code
FROM aitem a , vwinquiryshopstock ss,apackingtype p , aitempackingdetail ap , vwitemdescription v
WHERE a.itemID = v.itemID
	AND a.itemID = ap.itemID
	AND a.active=1
	AND ap.packingtypeid = P.packingtypeid
	AND a.itemid=v.itemid
	AND a.itemid=ss.itemid
	AND ss.shopid=@Shopid
	AND ap.active = 1
	AND a.active=1' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnIssueSerialNosForSpINV]    Script Date: 10/06/2012 14:17: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].[fnIssueSerialNosForSpINV]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This function returns the comma separated serial numbers
-- This function is used in vwCreditInvoice.
-- Coded by: Regin T.
-- Coded on: 27-01-2010
--------------------------------------------------------------------------------
CREATE function [dbo].[fnIssueSerialNosForSpINV](
@intInterfaceId int,
@intGodown int,
@intTransId int,
@intItemId int)
-- Crystal report cannot include a field having more than 254 char in formula.
-- Since the return value is used in the formula field of credit invoice reports,
-- the type of return value is set as varchar(254).
-- Caution: DO NOT INCREASE THE SIZE OF RETURN VALUE
returns varchar(8000)
as
begin
declare @strSerialNo as varchar(50)
declare @strSerialNoSet as varchar(500)
declare cur cursor for
select sidSerialNo
from loiSerialIssueDetails
where sidInterfaceId=@intInterfaceId
and sidGodownid=@intGodown
and sidTransactionID=@intTransId
and sidItemId=@intItemId
ORDER BY sidSerialNo
open cur
set @strSerialNoSet = ''''
fetch next from cur into @strSerialNo
while @@FETCH_STATUS = 0
begin
if len(@strSerialNoSet) = 0
set @strSerialNoSet = @strSerialNo
else
set @strSerialNoSet = @strSerialNoSet + '','' + @strSerialNo
fetch next from cur into @strSerialNo
end -- end of while
close cur
deallocate cur
return @strSerialNoSet
end -- end of function
---------------------------------------------------------------' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnIssueSerialNos]    Script Date: 10/06/2012 14:17: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].[fnIssueSerialNos]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
/*
--------------------------------------------------------------------------------
-- This function returns the comma separated serial numbers
-- This function is used in vwCreditInvoice.
-- Coded by: Regin T.
-- Coded on: 27-01-2010
/*
Ref No : 01
Update Date : 21.12.2011
Updated By  : Shine Das
Commented   : "varchar(500)" changed to varchar(MAX) for showing more lengthier string
*/
--------------------------------------------------------------------------------
*/
CREATE function [dbo].[fnIssueSerialNos](
@intInterfaceId int,
@intShopId int,
@intTransId int,
@intItemId int)
-- Crystal report cannot include a field having more than 254 char in formula.
-- Since the return value is used in the formula field of credit invoice reports,
-- the type of return value is set as varchar(254).
-- Caution: DO NOT INCREASE THE SIZE OF RETURN VALUE
returns varchar(8000)
as
begin
declare @strSerialNo as varchar(50)
--declare @strSerialNoSet as varchar(500)
declare @strSerialNoSet as varchar(MAX) ---   Ref No : 01
declare cur cursor for
select sidSerialNo
from losSerialIssueDetails
where sidInterfaceId=@intInterfaceId
and sidShopID=@intShopId
and sidTransactionID=@intTransId
and sidItemId=@intItemId
ORDER BY sidSerialNo
open cur
set @strSerialNoSet = ''''
fetch next from cur into @strSerialNo
while @@FETCH_STATUS = 0
begin
if len(@strSerialNoSet) = 0
set @strSerialNoSet = @strSerialNo
else
set @strSerialNoSet = @strSerialNoSet + '','' + @strSerialNo
fetch next from cur into @strSerialNo
end -- end of while
close cur
deallocate cur
return @strSerialNoSet
end -- end of function' 
END
GO
/****** Object:  View [dbo].[vwitemcustomcode]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemcustomcode]'))
EXEC dbo.sp_executesql @statement = N'
Create view [dbo].[vwitemcustomcode] as select distinct isnull(customcode,'''') Customcode ,1 customid from aitem'
GO
/****** Object:  View [dbo].[vwHPFeePaymentFrameWise]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentFrameWise]'))
EXEC dbo.sp_executesql @statement = N'
-- View
----------------------------------------------------------
-- View
--View Name : vwHPFeePaymentFrameWise
--Developed by : Regin T.
--Description : To view the details of fee payments against given item frame number
--Stated on : 12-08-2008
--Completed on : 12-08-2008
--Modified by :
CREATE view [dbo].[vwHPFeePaymentFrameWise] as
select hpHCompanyID, hpHDepartmentID, HpHPaymentID, hpHPaymentNo, hpHPaymentDate, hpHPayee,
hpHAmount, hpDAmount, feeName, hasExpiry, hpDExpiry, hpDRegID, IRFrameNo,
itemDescription, hpDDebitAccountID, hpHAccountID, hpHCancel
from ahpFeePaymentHeader
left outer join ahpFeePaymentDetail on hpDPaymentID=hpHPaymentID
left outer join losHpitemRegistrationdetails on hpDRegID=irregistrationid
left outer join aFeeMaster on hpFeeID=feeID
left outer join aItem on hpDItemID=itemID  where hphcancel=0'
GO
/****** Object:  View [dbo].[vwhpReceipt]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpReceipt]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwhpReceipt] as
select hprhCompanyID,hprhDepartmentId,HprhReceiptID,HprhReceiptNo,hprhReceiptDate,
hprhRefNo,hprhFinancialID,c.HPcustName,hprhAmount,hprhRemarks,hprhCancel
from aHPReceiptHeader,losHPCustomerDetails c
where hprhCustomerID=c.HPCustID'
GO
/****** Object:  View [dbo].[VwTemplocation]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwTemplocation]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[VwTemplocation] as
Select ai.itemcode,ai.itemdescription,dis.dname,ai.itemID from aitem ai left outer  join
adistributormaster dis on ai.did = dis.did'
GO
/****** Object:  View [dbo].[vwTargetAllocationdetails]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetAllocationdetails]'))
EXEC dbo.sp_executesql @statement = N'
--Modifeid(added target id)-santhosh M
--Date:29/09/2003
CREATE view [dbo].[vwTargetAllocationdetails] as
select tfhCompanyID, tfhFixationID, TargetCode, TargetHead, tfhFixationNo, tfhFixationDate,
tfhFromDate, tfhToDate, tfhFixationPanel, tfhReviewPanel, tfhReviewDate, tfhSanctionedBy,
tfhSanctionedDate, tfhRemarks, tfdFromDate Targetfromdate, tfdToDate Targettodate, tfdAmount,
tfdDetailID,TargetId from TargetMaster tm, TargetFixationHeader tfh, TargetFixationDetail tfd where
tfh.tfhcompanyid = tfd.tfdCompanyID and tfh.tfhFixationID = tfd.tfdFixationID and
tfd.tfdTargetID = tm.TargetId and tfd.tfdcompanyid = tm.companyid and tfh.tfhcancelled=0'
GO
/****** Object:  View [dbo].[vwTargetActualAnalysismax]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetActualAnalysismax]'))
EXEC dbo.sp_executesql @statement = N'
--Created By  : Reji Abraham
--Created  Date : 25/09/2003
CREATE view [dbo].[vwTargetActualAnalysismax]
as
select max(tcdCheckID) maxid,tcdcompanyid from TargetCheckDetail td,TargetCheckheader th where
td.tcdCheckID=th.tchcheckid and td.tcdCompanyID=th.tchCompanyID and tchCancelled=0 group by tcdFixationID,tcdCompanyID'
GO
/****** Object:  View [dbo].[vwSerialNofetch]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSerialNofetch]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------
/*
CREATED BY : PRASANTH JOSEPH
CREATEDFOR : FETCH SERIAL NO FROM MAGNOLIA SALES
CREATED ON :12-02-2010
*/
-------------------------------------
CREATE VIEW [dbo].[vwSerialNofetch] as
SELECT InterfaceID,ShopID,GodownID,TransactionID,ItemID,SerialNO from
(
SELECT sidInterfaceID InterfaceID,Null ShopID,sidGodownID GodownID,sidTransactionID TransactionID,sidItemID ItemID,sidSerialNo SerialNO FROM loiSerialIssueDetails
UNION ALL
SELECT sidInterfaceID InterfaceID,sidShopID ShopID,Null GodownID,sidTransactionID TransactionID,sidItemID ItemID,sidSerialNo SerialNO FROM losSerialIssueDetails
) Ser'
GO
/****** Object:  View [dbo].[vwSerialNoArrival]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSerialNoArrival]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------
/*
CREATED BY : jYOTHISH SR
CREATEDFOR : Arrivla SERIAL NO FROM MAGNOLIA SALES
CREATED ON :16-02-2010
*/
-------------------------------------
CREATE VIEW [dbo].[vwSerialNoArrival] as
SELECT InterfaceID,ShopID,GodownID,TransactionID,ItemID,SerialNO from
(
SELECT sadInterfaceID InterfaceID,Null ShopID,sadGodownID GodownID,sadTransactionID TransactionID,sadItemID ItemID,sadSerialNo SerialNO FROM loiSerialArrivalDetails
UNION ALL
SELECT  sadInterfaceID,sadShopID ShopID,Null GodownID,sadTransactionID TransactionID,sadItemID ItemID,sadSerialNo SerialNO FROM losSerialArrivalDetails
) Se'
GO
/****** Object:  View [dbo].[vwcompsalesquantitywise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcompsalesquantitywise]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
/****** Object:  View dbo.vwcompsalesquantitywise    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
CREATE view [dbo].[vwcompsalesquantitywise]  as
select qwise.rangedetail, r.rangename, qwise.soldyeargrp, qwise.soldmonthgrp,
datename(month,qwise.soldmonthgrp) soldmonth,
qwise.rangeqtygrp, avgmonth, currentstock, stockvalue
from tempqtywisegrouped qwise, reportrangevalues r where qwise.rangedetail =
r.rangedetailid and r.reportid =1'
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteReward]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeleteReward]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SpLmsDeleteReward]
@RewardId as int
as
delete from LMSReward where  RewardId=@RewardId' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeletePoint]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDeletePoint]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CrEATE PROCEDURE [dbo].[SpLmsDeletePoint]
@Point as int
as
delete from LmsPoint where PointsID=@Point' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRewards]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRewards]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SpLmsGetRewards]
@RewardId as int
as
select * from LMSReward where RewardId=@RewardId' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetReward]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetReward]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created by Jyothish S R
CREATE PROCEDURE  [dbo].[SpLmsGetReward] AS
SELECT    LMSReward.RewardId, LMSCardRegistration.CardNumber, LMSReward.Type,  LMSReward.Points ,  convert(varchar(10),LMSReward.PointDate,101) as PointDate  ,
CASE WHEN dbo.LMSReward.Dr = 1 THEN ''Dr''
	         WHEN dbo.LMSReward.Dr = 0 THEN ''Cr'' ELSE '''' END AS DRCR
FROM         LMSReward INNER JOIN
LMSCardRegistration ON LMSReward.CardId = LMSCardRegistration.CardRegistrationID
GROUP BY LMSReward.Dr, LMSReward.Type, .LMSCardRegistration.CardNumber, LMSReward.RewardId, LMSReward.Points,   LMSReward.PointDate
ORDER BY LMSReward.PointDate DESC' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistatioDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRegistatioDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SpLmsGetRegistatioDetails]
@CardRegistrationID as int
As
select * from LMSCardRegistration  where CardRegistrationID=@CardRegistrationID' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistaion]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetRegistaion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[SpLmsGetRegistaion]  AS
SELECT     dbo.LMSCardRegistration.CardRegistrationID AS CardRegistrationID, dbo.LMSCardRegistration.CardNumber AS CardNumber, CONVERT(varchar(10),
dbo.LMSCardRegistration.RegistrationDate, 101) AS RegistrationDate, CONVERT(varchar(10), dbo.LMSCardRegistration.ExpairyDate, 101)
AS ExpairyDate, dbo.CrmContact.FirstName AS CustomerName
FROM         dbo.LMSCardRegistration INNER JOIN
dbo.CrmContact ON dbo.LMSCardRegistration.CustmerId = dbo.CrmContact.ContactID' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetPoints]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetPoints]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SpLmsGetPoints]
as
select PointsID,PointDesc from LmsPoint' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetpoint]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetpoint]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[SpLmsGetpoint]
@PointsID as int
as
select  * from LmsPoint where PointsID=@PointsID' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsUpdateCardRegistation]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsUpdateCardRegistation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[SpLmsUpdateCardRegistation]
		@CompanyID as int,
@CardRegistrationID as int,
		@CardNumber as varchar(50),
		@RegistrationDate as datetime,
		@CustmerId as int,
@UserName as varchar(50),
		@TypeID as int,
		@ExpairyDate as datetime
		
AS
begin
		
		update  LMSCardRegistration  set CompanyID=@CompanyID ,CardNumber=@CardNumber ,RegistrationDate=@RegistrationDate,CustmerId=@CustmerId  ,UserName= @UserName ,TypeID=@TypeID ,ExpairyDate=@ExpairyDate where CardRegistrationID=@CardRegistrationID
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLMsUpateRewardPoint]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLMsUpateRewardPoint]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[SpLMsUpateRewardPoint]
@CompanyID as int,
@RewardId as int ,
@dr as int ,
@CardId as int,
@Type as Varchar(50),
@Points  as int,
@PointDate as datetime,
@Description   as varchar(50)
AS
begin
		
		update  LMSReward  set  CompanyID=@CompanyID ,CardId=@CardId,Dr=@dr  ,Type=@Type ,Points= @Points , PointDate=@PointDate ,[Description] =@Description     where RewardId = @RewardId
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsRewardsearch]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsRewardsearch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---Created by Jyothish
CREATE PROCEDURE  [dbo].[SpLmsRewardsearch]
@cardno as  varchar(50),
@Type as Varchar(50)
AS
if @Type=''ALL''
begin
SELECT    LMSReward.RewardId, LMSCardRegistration.CardNumber, LMSReward.Type,  LMSReward.Points ,  convert(varchar(10),LMSReward.PointDate,101) as PointDate ,
CASE WHEN dbo.LMSReward.Dr = 1 THEN ''Dr''
	         WHEN dbo.LMSReward.Dr = 0 THEN ''Cr'' ELSE '''' END AS DRCR
FROM         LMSReward INNER JOIN
LMSCardRegistration ON LMSReward.CardId = LMSCardRegistration.CardRegistrationID
where  LMSCardRegistration.CardNumber=@cardno
GROUP BY LMSReward.Dr, LMSReward.Type, .LMSCardRegistration.CardNumber, LMSReward.RewardId, LMSReward.Points,   LMSReward.PointDate
ORDER BY LMSReward.PointDate DESC
end
else
begin
SELECT    LMSReward.RewardId, LMSCardRegistration.CardNumber, LMSReward.Type,  LMSReward.Points ,  convert(varchar(10),LMSReward.PointDate,101)  as PointDate,
CASE WHEN dbo.LMSReward.Dr = 1 THEN ''Dr''
	         WHEN dbo.LMSReward.Dr = 0 THEN ''Cr'' ELSE '''' END AS DRCR
FROM         LMSReward INNER JOIN
LMSCardRegistration ON LMSReward.CardId = LMSCardRegistration.CardRegistrationID
where  LMSCardRegistration.CardNumber=@cardno and  LMSReward.Type=@Type
GROUP BY LMSReward.Dr, LMSReward.Type, .LMSCardRegistration.CardNumber, LMSReward.RewardId, LMSReward.Points,   LMSReward.PointDate
ORDER BY LMSReward.PointDate DESC
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsInsertCardRegistation]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsInsertCardRegistation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[SpLmsInsertCardRegistation]
		@CompanyID as int,
		@CardNumber as varchar(50),
		@RegistrationDate as varchar(50),
		@CustmerId as int,
@UserName as varchar(50),
		@TypeID as int,
		@ExpairyDate as varchar(50)
		
AS
begin
		DECLARE @MaxValue as int
		select @MaxValue  = max(CardRegistrationID) from LMSCardRegistration
		if @MaxValue is not Null
			Set  @MaxValue  =  @MaxValue +1
		else
			Set @MaxValue=1
		Insert into LMSCardRegistration values(@CompanyID ,@MaxValue,@CardNumber ,@RegistrationDate,@CustmerId  , @UserName ,@TypeID ,@ExpairyDate )
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCRM_SendMail]    Script Date: 10/06/2012 14:17: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].[spCRM_SendMail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author		:	MANUNADH. U
-- Create Date	:	
-- Description	:	To send mail
-- =============================================
CREATE PROCEDURE [dbo].[spCRM_SendMail]
(
	@email_recipients VARCHAR(MAX)  = NULL,
	@cc_recipients VARCHAR(MAX)  = NULL,
	@subject NVARCHAR(255) = NULL,
	@body NVARCHAR(MAX) = NULL
	--@profile NVARCHAR(255)= NULL
	--@mail_item_id INT = NULL OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
EXEC msdb.dbo.sp_send_dbmail
	@recipients=@email_recipients,
	@copy_recipients=@cc_recipients,
	@subject = @subject,
	@body = @body,
	@body_format = ''HTML'',
	@profile_name=''Fies Automated Mail Service'' ,
	@importance =''High''
--@mailitem_id = @mail_item_id Output
SET NOCOUNT OFF;
END' 
END
GO
/****** Object:  View [dbo].[vwItemAttributes2]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemAttributes2]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwItemAttributes2] as  select distinct isnull(Attribute2,'''') Attribute2 ,1 Aid from aitem'
GO
/****** Object:  View [dbo].[vwItemAttributes1]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemAttributes1]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwItemAttributes1] as  select distinct isnull(Attribute1,'''') Attribute1 ,1 Aid from aitem'
GO
/****** Object:  View [dbo].[vwShopItemStockitemsItemDtls]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemStockitemsItemDtls]'))
EXEC dbo.sp_executesql @statement = N'
--created by  : dheena
--created date  : 14052004
--Comments : purpose rptshopitemstockdtls
-----------------------------------------------------
--Modified By : Nidheesh P V
--Modified on : 02/08/2011
--Commentes : Commented ''a.active=1'' to get both active & in active items
--Modified Area : shop item price list report
--Reference : RefNo-1
-----------------------------------------------------
CREATE view [dbo].[vwShopItemStockitemsItemDtls] as
select
a.*,b.PackingTypeName ,c.packingtypeid,d.Quantity,
c.active packactive, vwd.itemdescription itemdescri
from
aitem a ,aPackingType b,vwitemdescription vwd,
aItemPackingDetail c, aPackingTypeCapacityDetail d
where   a.itemid=c.itemid and d.UnitsID=a.UnitsID and c.active=1 --and a.active=1 --RefNo-1
and c.PackingTypeID=d.PackingTypeID and c.PackingTypeID=b.PackingTypeID and a.itemid=vwd.itemid'
GO
/****** Object:  View [dbo].[vwItemsHavingStock]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsHavingStock]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view gives all items with stock more than 0.
-- This view is going to be used in rptItemPriceListHavingStock.rpt to show the selling price
-- of ONLY those items having stock.
-- This report was requested by Seenco.
--------------------------------------------------------------------------------
-- Coded By: Regin T.
-- Coded On: 24-09-2009
--------------------------------------------------------------------------------
CREATE view [dbo].[vwItemsHavingStock]
as
select v1.* from
vwShopItemStockitemsItemDtls v1, vwsellingtotalstockwithnegative v2
where v1.ItemID = v2.ItemID and v2.Stock > 0'
GO
/****** Object:  View [dbo].[vwShopPurchaseReturn]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPurchaseReturn]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopPurchaseReturn   Script Date: 19/06/2008  ******/
-- Created by - Benzigar S D
-- Modified on -
--
CREATE VIEW [dbo].[vwShopPurchaseReturn]
AS
SELECT     dbo.LOsPurchaseReturnHeader.whShopID, dbo.LOsPurchaseReturnHeader.WhID,
dbo.LOsPurchaseReturnHeader.WhNo, dbo.LOsPurchaseReturnHeader.WhDate,
dbo.LOsPurchaseReturnHeader.WhUserName, dbo.LOsPurchaseReturnHeader.WhRemarks,
dbo.vwitemDescription.itemdescription, dbo.LOsPurchaseReturnDetail.WdItemID, dbo.LOsPurchaseReturnHeader.whtype,
dbo.LOsPurchaseReturnDetail.WdAvailableQty AS BeforeVerify, dbo.LOsPurchaseReturnDetail.WdPurchaseReturnQty AS ReturnQty,
dbo.LOsPurchaseReturnDetail.WdAvailableQty - dbo.LOsPurchaseReturnDetail.WdPurchaseReturnQty AS AfterVerify
FROM         dbo.LOsPurchaseReturnHeader INNER JOIN
dbo.LOsPurchaseReturnDetail ON dbo.LOsPurchaseReturnHeader.whShopID = dbo.LOsPurchaseReturnDetail.wdShopID AND
dbo.LOsPurchaseReturnHeader.WhID = dbo.LOsPurchaseReturnDetail.WdID INNER JOIN
dbo.vwitemDescription ON dbo.LOsPurchaseReturnDetail.WdItemID = dbo.vwitemDescription.ItemID'
GO
/****** Object:  View [dbo].[vwMEDifferenceinStock]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMEDifferenceinStock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view  [dbo].[vwMEDifferenceinStock]  as
--this view is used for rptitemstoberecovered report
select dstransid,dstranscode,dsItemid,dsToAdd,dsToDeduct,
dsFromGodownID,dsToGodownID,dsFromShopID,dsToShopID,dsFutureint,
dsFutureVC,dsCostPrice,dsTransDate,dsDate
from MEDifferenceinStock where dsToDeduct<>0 or dsToAdd<>0'
GO
/****** Object:  View [dbo].[vwLoyaltyCardContactDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLoyaltyCardContactDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By   :Shinu	
-- Created On   :24/06/2007
-- Purpose      :For Loyality Card And Contacts Details
-- Modified by  :
-- Modified on  :
-- Comments     :
--------------------------------------------------------------------------------
Create View [dbo].[vwLoyaltyCardContactDetails] as
SELECT lmd.CompanyID,lmd.ID,cn.ContactID,cn.FirstName +'' ''+cn.LastName as ContactName,lm.CardID,
		lm.CardDesc,Lm.Amount,Lm.Points,lmd.ExpiryDate,lmd.UserName
FROM   aLoyaltyCardMaster lm
INNER JOIN aLoyaltyCardContactDetails lmd ON lm.CompanyID = lmd.CompanyID AND lm.CardID = lmd.CardID
INNER JOIN CrmContact cn ON lmd.CompanyID = cn.Companyid AND  lmd.ContactID = cn.ContactID'
GO
/****** Object:  View [dbo].[vwTargetActualAnalysis]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTargetActualAnalysis]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By 	: Santhosh M (added target id)
--Modified Date	: 29/09/2003
CREATE view [dbo].[vwTargetActualAnalysis] as select v.TargetHead,v.tfdAmount TargetAmount,
d.tcdActualAmount UtilizedAmount,isnull((v.tfdAmount-d.tcdActualAmount),0) Variance,
h.tchCheckDate CheckDate,h.tchActualAsonDate CheckPeriod,h.tchCheckedBy,
h.tchRemarks,h.tchCheckID,v.tfhFromDate,v.tfhToDate,v.Targetfromdate,
v.Targettodate,v.tfhFixationNo,v.tfhFixationID,h.tchCheckNo,h.tchCompanyID, d.tcdcheckid,
tchActualAsonDate,TargetId from
vwTargetAllocationDetails v, TargetCheckHeader h,TargetCheckDetail d where
v.tfhCompanyID=h.tchCompanyID
and v.tfhFixationID=h.tchFixationID and h.tchCompanyID=d.tcdCompanyID and
h.tchCheckID=d.tcdCheckID and v.tfdDetailID=d.tcdFixationDetailID and h.tchCancelled=0'
GO
/****** Object:  View [dbo].[vwHPQuotationReport]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPQuotationReport]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHPQuotationReport] as
select h.hpqhShopID,h.hpqhQuotationid,h.hpqhQuotationNo,h.hpqhQuotationDate,h.hpqhAmount,h.hpqhScheme,
h.hpqhCustName,h.hpqhcustAddress,h.hpQhFirstInstamt,h.HpqhBalAmt,h.hpqhInstPeriod,
h.hpqhCashAllowance,h.hpqhInstPerc,h.hpqhInstcharge,h.hpqhSurcharge,h.hpqhTotAdditional,
h.hpqhInstPrice,h.hpqhMonthilyPay,h.hpqhUserName,d.hpqdItemId,vw.itemdescription,
vw.code,d.hpqdSellingPrice, h.hpqhCancel from loshpinvoiceheader h,loshpinvoicedetail d,vwitemdescription vw
where h.hpqhQuotationid=d.hpqdQuotationId and d.hpqdItemId=vw.itemid'
GO
/****** Object:  StoredProcedure [dbo].[spTillEndStockVerificationRpt]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndStockVerificationRpt]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ==========================================================================================
-- Author: LAWRENCE M.
-- Created date: 08 April 2011
-- Description: To show the F&B Bill details in the Till End Stock Verification Report-
--     : as per the client requested format.This report is showing based on the item category.
--    : If the Dish is selling in the F&B shop then this report showing the purticular
--    : dish ingrdients based on the category
--     : This stored procedure is used to show the Till End Stock Verification Report
-- Client     : Wings Service
-- ==========================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 03 May 2011
-- Description: To show the values based on the packing type
-- Client     : Wings Service
-- ==========================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 09 May 2011
-- Description: As per the team guidance I have changed some flow in this stored procedure.
--    This stored procedure is taking the values from opening till table and closing
--    till table,here no need to show the sold quantity only we need to show the
--    used Quantity also
-- Client     : Wings Service
-- ==========================================================================================
CREATE PROCEDURE [dbo].[spTillEndStockVerificationRpt] @TillNo AS INT,@OutletID AS INT
AS
BEGIN
-- CREATE TABLE #TempStockVerification
-- (
--  ItemCategoryID INT,
--  ItemID INT,
--  ItemCode VARCHAR(50),
--  ItemName VARCHAR(250),
--  ItemCategoryName VARCHAR(250),
--  PackingTypeName VARCHAR(250),
--  OpeningStock INT,
--  ClosingStock INT,
--  PhysicalStock INT,
--  ShortageStock INT,
--  SoldQty DECIMAL(18,3),
--  PackingID INT
-- )
-- CREATE TABLE #TempDish
-- (
--  DishID INT,
--  ItemID INT,
--  Qty DECIMAL(18,3)
-- )
-- CREATE TABLE #TempInsideDish--If the ingredients inside another one dish
-- (
--  InsideDishID INT,
--  InsideItemID INT,
--  InsideQty DECIMAL(18,3)
-- )
-- CREATE TABLE #Tempshopbincardaudit
-- (
--  intItemID INT,
--  decReceivedQty DECIMAL(18,3),
--  intPackingID INT
-- )
-- --Dish with Ingredients items
-- INSERT INTO #TempStockVerification(ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,
-- OpeningStock,ClosingStock,PhysicalStock,ShortageStock,SoldQty,PackingID)
-- SELECT  a.ItemCategoryID,a.itemid,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock/p.Quantity openstock,availablestock/p.Quantity availablestock,
-- physicalstock/p.Quantity physicalstock,(physicalstock-availablestock)/p.Quantity Shortage,
-- SUM((fb_rd_packingqty*fb_pd_reusedqty)/p.Quantity) ,aipd.PackingTypeID
-- FROM TillClosingstock tcs INNER JOIN TillOpeningstock tos ON tos.companyid=tcs.companyid
-- AND tcs.tillHistId=tos.tillHistId AND tcs.tillId=tos.tillId AND tcs.tillNo=tos.tillno AND
-- tcs.shopid=tos.shopid AND tcs.itemid=tos.itemid INNER JOIN aitem a on  a.itemid=tos.itemid
-- INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
-- INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p on p.UnitsID = a.UnitsID
-- and  p.PackingtypeID=aipd.PackingtypeID
-- INNER JOIN Tillhistory ON till_hist_id=tos.tillHistId AND
-- till_id=tos.tillId AND till_outletid=tos.shopid AND till_companyid=tos.companyid INNER JOIN
-- losposfandbheader ON poshtillhistId=till_hist_id and poshTillID=till_id and poshShopID=till_outletid
-- AND poshCompanyID=till_companyid INNER JOIN fb_processdetail ON fb_pd_processid=poshbillid AND
-- fb_pd_companyid=poshCompanyID AND fb_pd_outletid=poshShopID INNER JOIN fb_recipedetails ON
-- Fb_rd_dishid=fb_pd_dishid AND Fb_rd_itemid=a.itemid and Fb_rd_Futurebit=0 AND fb_pd_AddedItemtype=0
-- WHERE tos.shopid=@OutletID AND tos.tillno=@TillNo
-- GROUP BY p.Quantity,a.itemid,a.ItemCategoryID,CategoryNameDescription,ItemCode,ItemDescription,PackingTypeName,
-- openstock,availablestock,physicalstock ,aipd.PackingTypeID
--
-- --For Added Item[Extras]
-- INSERT INTO #TempStockVerification(ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,
-- OpeningStock,ClosingStock,PhysicalStock,ShortageStock,SoldQty,PackingID)
-- SELECT  a.ItemCategoryID,fb_pd_dishid,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock/p.Quantity openstock,availablestock/p.Quantity availablestock,
-- physicalstock/p.Quantity physicalstock,(physicalstock-availablestock)/p.Quantity Shortage,
--SUM((fb_da_packingqty*fb_pd_reusedqty)/p.Quantity),aipd.PackingTypeID
-- FROM TillClosingstock tcs INNER JOIN TillOpeningstock tos ON tos.companyid=tcs.companyid
-- AND tcs.tillHistId=tos.tillHistId AND tcs.tillId=tos.tillId AND tcs.tillNo=tos.tillno AND
-- tcs.shopid=tos.shopid AND tcs.itemid=tos.itemid INNER JOIN aitem a ON  a.itemid=tos.itemid
-- INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
-- INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p on p.UnitsID = a.UnitsID
-- and  p.PackingtypeID=aipd.PackingtypeID
-- INNER JOIN Tillhistory ON till_hist_id=tos.tillHistId AND
-- till_id=tos.tillId AND till_outletid=tos.shopid AND till_companyid=tos.companyid INNER JOIN
-- losposfandbheader ON poshtillhistId=till_hist_id and poshTillID=till_id and poshShopID=till_outletid
-- AND poshCompanyID=till_companyid INNER JOIN fb_processdetail ON fb_pd_processid=poshbillid AND
-- fb_pd_companyid=poshCompanyID AND fb_pd_outletid=poshShopID and fb_pd_AddedItemtype=2
-- and fb_pd_dishid=a.itemid INNER JOIN fb_dishadds ON Fb_da_itemid=a.itemid and Fb_da_Futurebit=0
-- WHERE tos.shopid=@OutletID AND tos.tillno=@TillNo --and Fb_da_dishid=2
-- GROUP BY  p.Quantity,a.ItemCategoryID,fb_pd_dishid,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock,availablestock,physicalstock,aipd.PackingTypeID
--
-- --Insert the ItemID and DishID to Temp table[if the dish ingredients has one dish]
-- INSERT INTO #TempDish(DishID,ItemID,Qty)
-- SELECT Fb_rd_dishid,Fb_rd_itemid,Sum(fb_rd_packingqty*fb_pd_reusedqty)
-- FROM TillClosingstock tcs INNER JOIN TillOpeningstock tos ON tos.companyid=tcs.companyid
-- AND tcs.tillHistId=tos.tillHistId AND tcs.tillId=tos.tillId AND tcs.tillNo=tos.tillno AND
-- tcs.shopid=tos.shopid AND tcs.itemid=tos.itemid INNER JOIN aitem a ON  a.itemid=tos.itemid
-- INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
-- INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN Tillhistory ON till_hist_id=tos.tillHistId AND
-- till_id=tos.tillId AND till_outletid=tos.shopid AND till_companyid=tos.companyid INNER JOIN
-- losposfandbheader ON poshtillhistId=till_hist_id and poshTillID=till_id and poshShopID=till_outletid
-- AND poshCompanyID=till_companyid INNER JOIN fb_processdetail ON fb_pd_processid=poshbillid AND
-- fb_pd_companyid=poshCompanyID AND fb_pd_outletid=poshShopID INNER JOIN fb_recipedetails ON
-- Fb_rd_dishid=fb_pd_dishid AND Fb_rd_itemid=a.itemid  AND fb_pd_AddedItemtype=0 AND Fb_rd_Futurebit=1
-- WHERE tos.shopid=@OutletID AND tos.tillno=@TillNo
-- GROUP BY Fb_rd_itemid,Fb_rd_dishid
--
-- --[Based on the temp table DishId and ItemID to insert the
-- --Item details in to the master temptable[#TempStockVerification]
-- INSERT INTO #TempStockVerification(ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,
-- OpeningStock,ClosingStock,PhysicalStock,ShortageStock,SoldQty,PackingID)
-- SELECT a.ItemCategoryID,tmp.ItemID,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock/p.Quantity openstock,availablestock/p.Quantity availablestock,physicalstock/p.Quantity physicalstock,(physicalstock-availablestock)/p.Quantity Shortage,
--SUM((fb_rd_packingqty*Qty)/p.Quantity),aipd.PackingTypeID
-- FROM TillClosingstock tcs INNER JOIN TillOpeningstock tos ON tos.companyid=tcs.companyid
-- AND tcs.tillHistId=tos.tillHistId AND tcs.tillId=tos.tillId AND tcs.tillNo=tos.tillno AND
-- tcs.shopid=tos.shopid AND tcs.itemid=tos.itemid INNER JOIN aitem a ON  a.itemid=tos.itemid
-- INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
-- INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p on p.UnitsID = a.UnitsID
-- and  p.PackingtypeID=aipd.PackingtypeID
-- INNER JOIN Tillhistory ON till_hist_id=tos.tillHistId AND
-- till_id=tos.tillId AND till_outletid=tos.shopid AND till_companyid=tos.companyid INNER JOIN
-- #TempDish tmp ON tmp.ItemID=a.itemid INNER JOIN
-- fb_recipedetails ON Fb_rd_dishid=tmp.ItemID and Fb_rd_Futurebit=0
-- where tos.shopid=@OutletID AND tos.tillno=@TillNo
-- GROUP BY p.Quantity,a.ItemCategoryID,tmp.ItemID,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock,availablestock,physicalstock,aipd.PackingTypeID
--
-- --[If the ingredients has one dish that has handle above,but that dish has another
-- --dish then that DishID and ItemID to insert another temptable[#TempInsideDish]
-- INSERT INTO #TempInsideDish(InsideDishID,InsideItemID,InsideQty)
-- select Fb_rd_dishid,ItemID,SUM(Qty*fb_rd_packingqty) FROM #TempDish INNER JOIN
-- fb_recipedetails ON Fb_rd_dishid=ItemID and Fb_rd_Futurebit=1
-- GROUP BY  Fb_rd_dishid,ItemID
--
-- --Besed on the temp table[#TempInsideDish] DishID and ItemID to Insert the
-- --Item details in to the master temptable[#TempStockVerification]
-- INSERT INTO #TempStockVerification(ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,
-- OpeningStock,ClosingStock,PhysicalStock,ShortageStock,SoldQty,PackingID)
-- SELECT a.ItemCategoryID,InsideItemID,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock/p.Quantity openstock,availablestock/p.Quantity availablestock,physicalstock/p.Quantity physicalstock,
-- (physicalstock-availablestock)/p.Quantity Shortage,
--SUM((fb_rd_packingqty*InsideQty)/p.Quantity),aipd.PackingTypeID
-- FROM TillClosingstock tcs INNER JOIN TillOpeningstock tos ON tos.companyid=tcs.companyid
-- AND tcs.tillHistId=tos.tillHistId AND tcs.tillId=tos.tillId AND tcs.tillNo=tos.tillno AND
-- tcs.shopid=tos.shopid AND tcs.itemid=tos.itemid INNER JOIN aitem a ON  a.itemid=tos.itemid
-- INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
-- INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p on p.UnitsID = a.UnitsID
-- and  p.PackingtypeID=aipd.PackingtypeID
-- INNER JOIN Tillhistory ON till_hist_id=tos.tillHistId AND
-- till_id=tos.tillId AND till_outletid=tos.shopid AND till_companyid=tos.companyid INNER JOIN
-- #TempInsideDish tmp ON tmp.InsideItemID=a.itemid INNER JOIN
-- fb_recipedetails ON Fb_rd_dishid=tmp.InsideItemID and Fb_rd_Futurebit=0
-- WHERE tos.shopid=@OutletID AND tos.tillno=@TillNo
-- GROUP BY p.Quantity,a.ItemCategoryID,InsideItemID,ItemCode,ItemDescription,CategoryNameDescription,PackingTypeName,
-- openstock,availablestock,physicalstock,aipd.PackingTypeID
--
-- --Received Quantity based on the ItemID
-- INSERT INTO #Tempshopbincardaudit(intItemID,decReceivedQty,intPackingID)
-- SELECT vw.ItemId,sum(TransQty/p.Quantity),aipd.PackingTypeID
-- FROM vwshopbincardaudit vw inner join aItemPackingDetail aipd ON aipd.ItemID=vw.ItemID
-- INNER JOIN aPackingType apt ON
-- aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p on
-- p.PackingtypeID=aipd.PackingtypeID INNER JOIN aitem a on p.UnitsID = a.UnitsID
-- AND a.ItemID=vw.ItemID
-- WHERE shopid=@OutletID AND mode=1
-- GROUP BY vw.ItemId,ShopId,aipd.PackingtypeID
--
-- SELECT ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,OpeningStock,ClosingStock,
-- PhysicalStock,ShortageStock,SUM(SoldQty) SoldQty,decReceivedQty
-- FROM #TempStockVerification LEFT OUTER JOIN #Tempshopbincardaudit ON  intItemID=ItemID and PackingID=intPackingID
-- GROUP BY ItemCategoryID,ItemID,ItemCode,ItemName,ItemCategoryName,PackingTypeName,OpeningStock,
-- ClosingStock,PhysicalStock,ShortageStock,decReceivedQty
-- ORDER BY ItemCategoryID,ItemID
--
--
-- DROP TABLE #TempStockVerification
-- DROP TABLE #TempDish
-- DROP TABLE #TempInsideDish
-- DROP TABLE #Tempshopbincardaudit
SELECT a.ItemCategoryID,a.itemid,ItemCode,ItemDescription ItemName,CategoryNameDescription ItemCategoryName,PackingTypeName,
ISNULL(openstock/p.Quantity,0) OpeningStock,ISNULL(availablestock/p.Quantity,0) ClosingStock,
ISNULL(physicalstock/p.Quantity,0) PhysicalStock,ISNULL((physicalstock-availablestock)/p.Quantity,0) ShortageStock,
SUM(ISNULL(tcs.allReceivedStock/p.Quantity,0))-SUM(ISNULL(tos.allReceivedStock/p.Quantity,0)) decReceivedQty,
SUM(ISNULL(tcs.allUsedStock/p.Quantity,0))-SUM(ISNULL(tos.allUsedStock/p.Quantity,0)) SoldQty
from TillClosingstock tcs LEFT OUTER JOIN TillOpeningstock tos ON tcs.itemid=tos.itemid
AND tcs.companyid=tos.companyid AND tcs.tillHistId=tos.tillHistId AND tcs.tillid=tos.tillid
AND tcs.shopid=tos.shopid INNER JOIN aitem a ON a.itemid=tcs.itemid INNER JOIN aItemCategory ic ON ic.ItemCategoryID=a.ItemCategoryID
INNER JOIN aItemPackingDetail aipd ON aipd.ItemID=a.ItemID INNER JOIN aPackingType apt ON
aipd.PackingTypeID=apt.PackingTypeID INNER JOIN apackingtypecapacitydetail p ON p.UnitsID = a.UnitsID
and  p.PackingtypeID=aipd.PackingtypeID
WHERE tcs.shopid=@OutletID AND tcs.tillno=@TillNo
GROUP BY p.Quantity,a.itemid,a.ItemCategoryID,CategoryNameDescription,ItemCode,ItemDescription,PackingTypeName,
openstock,availablestock,physicalstock ,aipd.PackingTypeID
HAVING  SUM(ISNULL(tcs.allReceivedStock,0))-SUM(ISNULL(tos.allReceivedStock,0)) <> 0 OR
SUM(ISNULL(tcs.allUsedStock,0))-SUM(ISNULL(tos.allUsedStock,0))<>0
ORDER BY a.ItemCategoryID,a.itemid
END' 
END
GO
/****** Object:  View [dbo].[vwHPDummyQuotationReport]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPDummyQuotationReport]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHPDummyQuotationReport] as
select h.hpqhShopID,h.hpqhQuotationid,h.hpqhQuotationNo,h.hpqhQuotationDate,h.hpqhAmount,h.hpqhScheme,
h.hpqhCustName,h.hpqhcustAddress,h.hpQhFirstInstamt,h.HpqhBalAmt,h.hpqhInstPeriod,
h.hpqhCashAllowance,h.hpqhInstPerc,h.hpqhInstcharge,h.hpqhSurcharge,h.hpqhTotAdditional,
h.hpqhInstPrice,h.hpqhMonthilyPay,h.hpqhUserName,d.hpqdItemId,vw.itemdescription,
vw.code,d.hpqdSellingPrice from loshpDummyQuotationheader h,loshpDummyQuotationDetails d,vwitemdescription vw
where h.hpqhQuotationid=d.hpqdQuotationId and d.hpqdItemId=vw.itemid'
GO
/****** Object:  View [dbo].[vwhpPDChequeRegistry]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpPDChequeRegistry]'))
EXEC dbo.sp_executesql @statement = N'
---Created By     : Prasanth Joseph
---Created on     : 31-12-2007
---Created For    : To get PD cheque details
---Modified By    : Regin
---Modified on    : 23/09/2008
CREATE view [dbo].[vwhpPDChequeRegistry] as
select h.hphCompanYID,h.hphShopID,h.hphChqRegID,h.hphChqRegNO,h.hphDate,d.hpdChqNo,d.HpdBankName,
d.hpdChqDate,d.HpdChqAmount,d.hpdActualChqAmount,C.HpCustName,a.HpAgreementNo, h.hphCancel
from losHPChequeregisterHeader h inner join losHPChequeregisterDetail d on h.hphChqRegID=d.hpDChqRegID
inner join losHpCustomerDetails c on h.hphCustID=c.hpCustID
inner join ahPAgreementDetail a on h.hphagreementId=a.hpagreementID'
GO
/****** Object:  View [dbo].[vwHPOverDueBalanceTEST]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOverDueBalanceTEST]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHPOverDueBalanceTEST] as
select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphProcessingID TranID,hphProcessingNo TranNo,
hpdChequeDate DueDate,hpdRental Amount, hpdsettlementamount testamount,
hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Inst'' TranType
from
ahpprocessingHeader left outer join ahpprocessingDetail
on hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphProcessingID=hpdProcessingID
left outer join (loshpinvoiceheader left outer join ahpAgreementdetail ag
on hpqhReferenceID=ag.hpQuotationID)
on hphinvoiceid=hpqhQuotationID
where
hphCancel=0 and hphAmended=0 --- and --- hpdSettlementAmount=0
union all
Select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphPaymentID TranID,hphPaymentNo TranNo,
hphPaymentDate DueDate,hprdSettelmentAmount Amount, hprdSettelmentAmount testamount,
hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Pay'' TranType
from
ahpPaymentHeader left outer join (ahpPaymentdetail
inner join
(select
hprdCompanyID,hprdReceiptID,hprdDetailId,hprdSettelmentAmount,hpAgreementID,hpAgreementNO,hprdProcessingDetailId
from
loshpReceiptDetail left outer join (loshpinvoiceheader inv
left outer join ahpAgreementdetail ag on inv.hpqhReferenceID=ag.hpQuotationID )
on hprdInvoiceID=inv.hpqhQuotationID and inv.hpqhType=''I'' and inv.hpqhCancel=0
left outer join loshpReceiptHEader on  hprdReceiptID=hprhReceiptID
where hprhReceiptType=''S'' )Rec on
hpdReceiptID=hprdReceiptID )
on hphPaymentID=hpDpaymentID and hpdProcessingDetailID=hprdProcessingDetailId
and hphCancel=0 and hphPaymentId not in (
select hprdPaymentID from ahpReceiptHEader inner join ahpReceiptDetail
on hprhReceiptID=hprdReceiptID and hprhDepartmentID=hprdDepartmentID
and hprhCompanyID=hprdCompanyID and hprhCancel=0)'
GO
/****** Object:  View [dbo].[vwHPOverDueBalance]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPOverDueBalance]'))
EXEC dbo.sp_executesql @statement = N'
--Created by :  Prasanth Joseph
--Created on :  19-09-2008
--Purpos     :  To get over due balance, From processing will take
--              unsettle ProcessDetails+Payment Agaist the Agreement
--Modified By:
--Modifies on:
Create view [dbo].[vwHPOverDueBalance] as
select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphProcessingID TranID,hphProcessingNo TranNo,
hpdChequeDate DueDate,hpdRental Amount,hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Inst'' TranType
from
ahpprocessingHeader left outer join ahpprocessingDetail
on hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphProcessingID=hpdProcessingID
left outer join (loshpinvoiceheader left outer join ahpAgreementdetail ag
on hpqhReferenceID=ag.hpQuotationID)
on hphinvoiceid=hpqhQuotationID
where
hphCancel=0 and hphAmended=0 and hpdSettlementAmount=0
union all
Select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphPaymentID TranID,hphPaymentNo TranNo,
hphPaymentDate DueDate,hprdSettelmentAmount Amount,hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Pay'' TranType
from
ahpPaymentHeader left outer join (ahpPaymentdetail
inner join
(select
hprdCompanyID,hprdReceiptID,hprdDetailId,hprdSettelmentAmount,hpAgreementID,hpAgreementNO,hprdProcessingDetailId
from
loshpReceiptDetail left outer join (loshpinvoiceheader inv
left outer join ahpAgreementdetail ag on inv.hpqhReferenceID=ag.hpQuotationID )
on hprdInvoiceID=inv.hpqhQuotationID and inv.hpqhType=''I'' and inv.hpqhCancel=0
left outer join loshpReceiptHEader on  hprdReceiptID=hprhReceiptID
where hprhReceiptType=''S'' )Rec on
hpdReceiptID=hprdReceiptID )
on hphPaymentID=hpDpaymentID and hpdProcessingDetailID=hprdProcessingDetailId
and hphCancel=0 and hphPaymentId not in (
select hprdPaymentID from ahpReceiptHEader inner join ahpReceiptDetail
on hprhReceiptID=hprdReceiptID and hprhDepartmentID=hprdDepartmentID
and hprhCompanyID=hprdCompanyID and hprhCancel=0)'
GO
/****** Object:  View [dbo].[vwHPNonSettledCustomer]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPNonSettledCustomer]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by  : Regin
Created on  : 01/10/2008
Modified by :
Modified on :
Purpose     : To Get non settled hire purchase customers
*/
CREATE view [dbo].[vwHPNonSettledCustomer] as
select cd.hpCustID, cd.hpCustName, cd.hpCustPermanentadd, hpqhQuotationID InvoiceID,
hpqhQuotationNo InvoiceNo, hpqhQuotationDate InvoiceDate, hpAgreementNO,
IRFrameNo, hpqhInstPrice InvoiceAmount,
hpqhInstPrice-v.outStandingAmount SettledAmount, v.outStandingAmount Balance
from losHpInvoiceHeader ih inner join vwHPOutstandingAmount v on hpqhQuotationID= v.InvoiceID
left outer join aHPAgreementDetail ad on ih.hpqhReferenceID=ad.hpQuotationID
left outer join losHPItemRegistrationDetails ir on ad.hpItemRegID=ir.IRRegistrationID
left outer join losHPCustomerDetails cd on ih.hpqhCustomerID=cd.hpCustID'
GO
/****** Object:  View [dbo].[vwhpItemTransfer]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpItemTransfer]'))
EXEC dbo.sp_executesql @statement = N'
---Created by       : Prasanth Joseph
---Created On       : 06-12-2007
---Crated for       : Item Transfer Report
---Modified By      :
---Modified On      :
create view [dbo].[vwhpItemTransfer] as
select h.ithCompanyID,h.ithFinancialId,h.ithTransferID,h.ithTransferNo,h.ithTransferDate,
d.itdItemRegID,vw.ItemDescription,d.itdCurrentLocation LocationBeforeTransfer,d.itdTransLocation
from loshpitemregistrationdetails ir,vwitemdescription vw,ahpItemTransferheader h inner join ahpitemTransferDetail d on h.ithCompanyID=d.itdCompanyID
and h.ithTransferID=d.itdTransferID
where d.itditemRegId=ir.irRegistrationid and ir.irItemId=vw.itemid'
GO
/****** Object:  View [dbo].[vwHPInvoiceDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPInvoiceDetails]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by :  Shinu
Created on : 30/05/2008
Modified by :
Modified on :
Purpose      : To Get the Hire Purchase Invoice Details
*/
CREATE View [dbo].[vwHPInvoiceDetails] As
select Inv.hpqhCompanyID,Inv.hpqhShopId,Inv.hpqhQuotationID InvoiceID,Inv.hpqhQuotationNo InvoiceNo,
Inv.hpqhQuotationDate InvoiceDate,Qut.hpqhQuotationID QuotationID,Qut.hpqhQuotationNo QuotationNo,
Qut.hpqhQuotationDate  QuotationDate,hpqdDetailID,hpqdItemID,hpqdItemRegistrationID,hpqdFrameNo
From  losHpInvoiceHeader Inv
Inner Join losHpInvoiceDetail ON hpqhCompanyID=hpqdCompanyID And hpqhShopId =hpqdShopId
And hpqhQuotationID=hpqdQuotationID
Left Outer Join losHpInvoiceHeader Qut On Inv.hpqhCompanyID= Qut.hpqhCompanyID
And Inv.hpqhShopId=Qut.hpqhShopId And Inv.hpqhReferenceID =Qut.hpqhQuotationID And Qut.hpqhType=''Q'' And Qut.hpQhCancel=0 And Qut.hpQhConfirmEd=1
where Inv.hpqhType=''I'' And Inv.hpQhCancel=0 And Inv.hpQhConfirmEd=1'
GO
/****** Object:  View [dbo].[vwHPFinancialIncomeEarned]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFinancialIncomeEarned]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--------------------
--------------------------------------------------------------------------------------------------------------
---Created By       : Prasanth Joseph
---Created On       : 31-05-2008
---Created For      : To get interest details from HP Processing which settled.
---Modified By      :
---Modified On      :
--------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwHPFinancialIncomeEarned]
as
Select   hphCompanyID,hphCustomeriD, hphProcessingNo,hpCustName,hphinvoiceID,hpqhQuotationNo,
hpqhInstPrice,hpqdSellingPrice,hpqhAmount,hpdDepartmentID,hpdProcessingID,hpdDetailID,hpdChequeDate,hpdChequeNo,
max(ActualSettlmentDate)ActualSettlmentDate , Yearname,Monthly,
hpdInterest,hpAgreementNo,IRRegNo,IrFrameNo  from
(
select top 100000 ph.hphCompanyID,ph.hphCustomeriD, ph.hphProcessingNo,cu.hpCustName,ph.hphinvoiceID,inv.hpqhQuotationNo,
inv.hpqhInstPrice,hpqdSellingPrice,inv.hpqhAmount,pd.hpdDepartmentID,pd.hpdProcessingID,pd.hpdDetailID,pd.hpdChequeDate,hpdChequeNo,
case when Rec.HQRECEIPTDate is not null then Rec.HQRECEIPTDate else Rec.shopDate End ActualSettlmentDate,
--Rec.HQRECEIPTDate,
case when Rec.HQRECEIPTDate is not null then year(Rec.HQRECEIPTDate) else year(Rec.shopDate) End Yearname,
case when Rec.HQRECEIPTDate is not null then month(Rec.HQRECEIPTDate) else month(Rec.shopDate) End  Monthly,
pd.hpdInterest,ag.hpAgreementNo,ir.IRRegNo,ir.IrFrameNo
from ahpprocessingDetail pd inner  join ((ahpPRocessingHEader ph
inner join loshpCustomerDetails Cu on cu.hpCustID=ph.hphCustomeriD)
left outer join ((loshpInvoiceHEader inv
left outer join loshpInvoicedetail  on hpqhQuotationID=hpqdQuotationID and hpqhShopID=hpqdShopID)
left outer join (losHPinvoiceheader quo
left outer join (ahpAgreementDetail ag
left outer join losHPitemRegistrationdetails ir
on ag.hpitemREgID=ir.IRREgistrationID)
on ag.hpQuotationID=quo.hpqhQuotationID)
on inv.hpqhReferenceid=quo.hpqhQuotationID)
on ph.hphinvoiceID=inv.hpqhQuotationId  )
on pd.hpdProcessingId=ph.hphprocessingID and pd.hpdSettlementAmount = hpdAmount
inner join (
--Join with Receipt Details
select  max(HQrh.hprhReceiptDate) HQRECEIPTDate,rh.hprhReceiptDate shopDate,rh.hprhReceiptID,
rd.hprdProcessingId,rd.hprdProcessingDetailId
from (loshpReceiptDetail rd
inner join
loshpReceiptHEader rh on hprdReceiptID=hprhReceiptID and
rd.hprdShopId=rh.hprhShopId and rd.hprdCompanyID=rh.hprHCompanyID and rh.hprhCancel=0)
left outer join
--Payment and Receipt Checking
((aHpPaymentDetail PD inner join  ahpPaymentHEader ph on pd.hpdPaymentID=ph.hphPaymentID
and pd.hpdDepartmentID=ph.hphDepartmentID and pd.hpdCompanyID=ph.hphCompanyID and ph.hphCancel=0)
left outer join (aHpReceiptDetail HQRD  inner join ahpReceiptHeader HQRH on HQRD.hprdReceiptID=HQRH.hprhReceiptID
and HQRD.hprdDepartmentID=HQRH.hprhDepartmentID and HQRD.hprdCompanyID=HQRH.hprHCompanyID and HQRH.hprhCancel=0)
on PD.hpdPaymentID=HQRD.hprdPaymentID and PD.hpdDepartmentID=HQRD.hprdDepartmentID and PD.hpdCompanyID=HQRD.hprdCompanyID)
on rd.hprdReceiptID=PD.hpdReceiptID  and rd.hprdProcessingDetailId=PD.hpdProcessingDetailID
where  rd.hprdReceiptID not in (
select hpdreceiptID from aHpPaymentDetail
INNER JOIN aHpPaymentHeader ON  hpdPaymentID= hphPaymentID AND hphCancel=0
and hpdPaymentID not in (select hprdPaymentID from  aHpReceiptDetail HQRD  inner join ahpReceiptHeader HQRH on HQRD.hprdReceiptID=HQRH.hprhReceiptID
and HQRD.hprdDepartmentID=HQRH.hprhDepartmentID and HQRD.hprdCompanyID=HQRH.hprHCompanyID and HQRH.hprhCancel=0 ) --order by hpdreceiptID
)
--and  rh.hprhCustomerID=1211
Group by  rh.hprhReceiptID, rh.hprhReceiptDate,rh.hprhReceiptID,
rd.hprdProcessingId,rd.hprdProcessingDetailId )Rec
on  pd.hpdProcessingId= Rec.hprdProcessingId and pd.hpdDetailID=Rec.hprdProcessingDetailId
order by hphCustomeriD,pd.hpdChequeDate
) A
GROUP BY
hphCompanyID,hphCustomeriD, hphProcessingNo,hpCustName,hphinvoiceID,hpqhQuotationNo,
hpqhInstPrice,hpqdSellingPrice,hpqhAmount,hpdDepartmentID,hpdProcessingID,hpdDetailID,hpdChequeDate,hpdChequeNo,
Yearname,Monthly,
hpdInterest,hpAgreementNo,IRRegNo,IrFrameNo'
GO
/****** Object:  View [dbo].[vwitempackingonebarcode]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitempackingonebarcode]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 17/11/2001 9:21:14 PM ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwitempackingonebarcode    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[vwitempackingonebarcode] as
select i.itemid, i.itemcode, vw.itemdescription, ip.packingbarcode from aitempackingdetail ip, aitem i,
vwitemdescription vw
where vw.itemid =i.itemid and
i.itemid = ip.itemid and ip.PackingSlNo =1'
GO
/****** Object:  View [dbo].[gmwithlevel]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmwithlevel]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gmwithlevel    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 17/11/2001 9:21:12 PM ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.gmwithlevel    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[gmwithlevel] as
select groupid,parentgroupid, 1 levelgm from agroupmaster where parentgroupid is null'
GO
/****** Object:  StoredProcedure [dbo].[generatebc]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[generatebc]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.generatebc    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.generatebc    Script Date: 14/09/2002 12:48:14 AM ******/
CREATE proc [dbo].[generatebc] @intitemid as int as
declare @intitemcatid as int,
	@stritemcatcode as char(3),
	@intitemcountincat as int,
	@stritemcountincat as char(10),
	@intcount as int,
	@strbarcode as char(13),
	@intpackingslno as char(1),
	@intcount1 as int,
	@intnum as int,
	@intresult as int
create table #temp  (
	packingslno int)
set nocount on
select @intitemcatid = ItemCategoryID from aitem where itemid = @intitemid
select @stritemcatcode = ItemCategoryCode from aitemcategory where itemcategoryid = @intitemcatid
while len(@stritemcatcode) < 3
begin
	set @stritemcatcode = ''0'' + @stritemcatcode
end
select @intitemcountincat = isnull(max(substring(isnull(barcode,''''),4,len(barcode))),0) from aitem where
isnumeric(barcode) =1 and barcode like @stritemcatcode+''%'' and itemid < @intitemid
set @intitemcountincat = @intitemcountincat + 1
set @stritemcountincat = convert(char(7),@intitemcountincat)
while len(@stritemcountincat) < 7
begin
	set @stritemcountincat  = ''0'' + @stritemcountincat
end
set @stritemcountincat  = @stritemcatcode + @stritemcountincat
update aitem set barcode = @stritemcountincat, GenerateBC = 1 where itemid = @intitemid
delete from #temp
insert into #temp
select packingslno from aitempackingdetail where itemid = @intitemid
select @intcount = count(packingslno) from #temp
while @intcount <> 0
begin
	select @intpackingslno = packingslno from #temp
	set @strbarcode = ''2'' + convert(char(1),@intpackingslno) + @stritemcountincat
	set @intcount1 =1
	set @intresult =0
	while @intcount1 < 12
	begin
		set @intnum = substring(@strBarcode, @intcount1, 1)
	        set @intresult = @intresult + (@intnum  * 1)
	set @intcount1 = @intcount1 + 1
	        set @intnum = substring(@strBarcode, @intcount1, 1)
	set @intresult = @intresult + (@intnum * 3)
		set @intcount1 = @intcount1 + 1
	end
set @intresult = @intresult % 10
	set @intresult  = 10 - @intresult
	update aitempackingdetail set PackingBarCode = rtrim(@strbarcode) + convert(char(1), @intresult) where
	itemid = @intitemid and PackingSlNo = @intpackingslno
	delete from #temp where packingslno = @intpackingslno
	select @intcount = count(packingslno) from #temp
end
drop table #temp
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHPCustomerClassification]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPCustomerClassification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spHPCustomerClassification ''01/01/2008'',2,''P''
------------------------------------------------------------------
--Created By   : Prasanth Joseph
--Created On   : 10-01-2009
--Createed For : Sort Customer Performing or Non Perfoming,
--               After doing interest posting only will get the correct result
--Modified By  :
--Modified On  :
-----------------------------------------------------------------
Create  procedure [dbo].[spHPCustomerClassification] @ProcessDate as varchar(10),
@intDepartmentID as Int,
@strType as varchar as
Begin
set nocount on
create table #tempCustomerPerfomance
(
ProcessingID int,
Type nvarchar(20)
)
Declare @intProcessingID as Int,
@intunsettledPaymentCount as int,
@intUnsettledProcessingCount as int,
@intTotalUnsetteledCount as int,
@intNonPerfomer as int,
@strsql as nvarchar(500)
Begin
declare opcurt cursor for
select distinct(hphProcessingID) hphProcessingID from ahpprocessingdetail left outer join ahpprocessingheader
on hpdprocessingID=hphProcessingID and hpdDepartmentID=hphDepartmentID
and hpdCompanyID=hphCompanyID where hpdChequedate<=@ProcessDate and
hpdPosted=1 and hphCancel=0 and hphAmended=0 --and hphdepartmentid=@intDepartmentID
open opcurt
fetch next from opcurt into @intProcessingID
while @@fetch_status =0
begin
select @intunsettledPaymentCount=count(processingid) from vwhpunsettledProcessing
where processingid=@intProcessingID
select @intUnsettledProcessingCount=count(hpdProcessingID) from ahpProcessingDetail where  hpdChequedate<=@ProcessDate
and hpdSettlementAmount<=0  and hpdProcessingId=@intProcessingID
set @intTotalUnsetteledCount=@intunsettledPaymentCount+@intUnsettledProcessingCount
if @intTotalUnsetteledCount < 4
begin
select @intNonPerfomer=count(hpProcessingID) from aHPCustomerPerfomance where hpProcessingID=@intProcessingID
if @intNonPerfomer>0
begin
if ((select count(hpdProcessingID) from ahpProcessingDetail   where hpdProcessingId=@intProcessingID and hpdChequeDate<=@ProcessDate) =
(select count(hpdProcessingID) from ahpProcessingDetail   where hpdProcessingId=@intProcessingID and hpdChequeDate<=@ProcessDate and hpdSettlementAmount>0)-@intunsettledPaymentCount)
begin
insert into #tempCustomerPerfomance values(@intProcessingID,''P'')
end
else
begin
insert into #tempCustomerPerfomance values(@intProcessingID,''N'')
end
end
else
begin
insert into #tempCustomerPerfomance values(@intProcessingID,''P'')
end
end
else
begin
insert into #tempCustomerPerfomance values(@intProcessingID,''N'')
end
fetch next from opcurt into @intProcessingID
end
Close opcurt
Deallocate opcurt
end
select c.*,hpAgreementNO,inv.hpqhQuotationNo,@strType from ahpProcessingHEader inner join
loshpCustomerdetails c on hphcustomerid=hpCustID
inner join (loshpInvoiceheader inv  inner join
(loshpInvoiceheader quo inner join  ahpAgreementDetail ag on quo.hpqhQuotationID=ag.hpQuotationID)
on inv.hpqhReferenceid=quo.hpqhQuotationID and quo.hpqhType=''Q'')
on hphinvoiceid=inv.hpqhQuotationID and inv.hpqhType=''I''
where hphProcessingID in(select ProcessingID from #tempCustomerPerfomance where Type=@strType)
--select * from loshpCustomerdetails c  inner join
--(select distinct(hphCustomerID) from ahpProcessingheader where  hphProcessingID in (
--select ProcessingID from #tempCustomerPerfomance where Type=@strType))d
--on c.hpCustID=d.hphCustomerID
drop table #tempCustomerPerfomance
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertListItemDetails]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertListItemDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : Regin
--Created On : 05-11-2008
--Purpose    : To  insert/update details the List Item Detail Table [aListItemDetails]
-----------------------------------------------------------------------------------------------------------------------------
create PROC [dbo].[spInsertListItemDetails]
@intListID As Int,
@intItemID As Int,
@intQty As Numeric(18,3),
@intPackingTypeID As Int,
@intPQty As Numeric(18,3)
As
Begin
Insert InTo aListItemDetails(ListID,ItemID,Qty,PackingTypeID,PQty) Values(@intListID,@intItemID,@intQty,@intPackingTypeID,@intPQty)
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHPFinancialIncomeEarned]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPFinancialIncomeEarned]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--Created By   : Regin
--Created for  : To get Earned and unearned financil income()
--Created on   : 01-12-2008
--Modified by  : Nidheesh
--Modified on  : 04-12-2009
--Comments : To get unearned financial income report only
--: change the date to actualsettlement date and used this date to filter #HPFinIncomeAll
-------------------------------------------------------------
-- spHPFinancialIncomeEarned 1, 1, ''20080101'', ''20100101''
CREATE procedure [dbo].[spHPFinancialIncomeEarned]
@details as bit,
@asondate as bit,
@dtfromdate as varchar(8),
@dttodate as varchar(8)
as
set nocount on
CREATE table #HPFinIncomeAll(
fiComapanyID int, --fi stands for Financial Income
fiDepartmentID int,
fiCustomerID int,
fiCustomerName nvarchar(300),
fiInvoiceID int,
fiQuotationNo nvarchar(100),
fiAgreementNo nvarchar(50),
fiInstPrice numeric(18,2),
fiSellingPrice numeric(18,2),
fiInvoiceAmount numeric(18,2),
fiProcessingID int,
fiProcessingNo nvarchar(50),
fiChequeDate datetime,
fiSettlmentDate datetime,
fiYear int,
fiMonth int,
fiInterest numeric(18,2),
fiSettlementAmount numeric(18,2),
fiRegNo nvarchar(50),
fiFrameNo nvarchar(50))
CREATE table #HPFinIncomeSelected(
fiComapanyID int, --fi stands for Financial Income
fiDepartmentID int,
fiCustomerID int,
fiCustomerName nvarchar(300),
fiInvoiceID int,
fiQuotationNo nvarchar(100),
fiAgreementNo nvarchar(50),
fiInstPrice numeric(18,2),
fiSellingPrice numeric(18,2),
fiInvoiceAmount numeric(18,2),
fiProcessingID int,
fiProcessingNo nvarchar(50),
fiChequeDate datetime,
fiSettlmentDate datetime,
fiYear int,
fiMonth int,
fiInterest numeric(18,2),
fiSettlementAmount numeric(18,2),
fiRegNo nvarchar(50),
fiFrameNo nvarchar(50))
begin
--Inserting all invoice details
insert into #HPFinIncomeAll
Select   hphCompanyID,hpdDepartmentID,hphCustomeriD,hpCustName,hphinvoiceID,hpqhQuotationNo,
hpAgreementNo,
hpqhInstPrice,hpqdSellingPrice,hpqhAmount,hpdProcessingID,hphProcessingNo,hpdChequeDate,--hpdDetailID,hpdChequeNo,
max(ActualSettlmentDate)ActualSettlmentDate , Yearname,Monthly,
hpdInterest,hpdSettlementAmount,IRRegNo,IrFrameNo  from
(
select top 100000 ph.hphCompanyID,ph.hphCustomeriD, ph.hphProcessingNo,cu.hpCustName,ph.hphinvoiceID,inv.hpqhQuotationNo,
inv.hpqhInstPrice,hpqdSellingPrice,inv.hpqhAmount,pd.hpdDepartmentID,pd.hpdProcessingID,pd.hpdDetailID,pd.hpdChequeDate,hpdChequeNo,
--year(pd.hpdChequeDate) Yearname, month(pd.hpdChequeDate)  Monthly,
case when Rec.HQRECEIPTDate is not null then Rec.HQRECEIPTDate else Rec.shopDate End ActualSettlmentDate,
case when Rec.HQRECEIPTDate is not null then year(Rec.HQRECEIPTDate) else year(Rec.shopDate) End Yearname,
case when Rec.HQRECEIPTDate is not null then month(Rec.HQRECEIPTDate) else month(Rec.shopDate) End  Monthly,
--case when pd.hpdSettlementAmount=0 then 0 else pd.hpdinterest end hpdinterest
--pd.hpdinterest,ir.IRRegNo,ir.IrFrameNo
pd.hpdSettlementAmount,
pd.hpdInterest,ag.hpAgreementNo,ir.IRRegNo,ir.IrFrameNo
from ahpprocessingDetail pd inner  join ((ahpPRocessingHEader ph
inner join loshpCustomerDetails Cu on cu.hpCustID=ph.hphCustomeriD)
left outer join ((loshpInvoiceHEader inv
left outer join loshpInvoicedetail  on hpqhQuotationID=hpqdQuotationID and hpqhShopID=hpqdShopID)
left outer join (losHPinvoiceheader quo
left outer join (ahpAgreementDetail ag
left outer join losHPitemRegistrationdetails ir
on ag.hpitemREgID=ir.IRREgistrationID)
on ag.hpQuotationID=quo.hpqhQuotationID)
on inv.hpqhReferenceid=quo.hpqhQuotationID)
on ph.hphinvoiceID=inv.hpqhQuotationId  )
on pd.hpdProcessingId=ph.hphprocessingID and pd.hpdSettlementAmount = hpdAmount
inner join (
--Join with Receipt Details
select  max(HQrh.hprhReceiptDate) HQRECEIPTDate,rh.hprhReceiptDate shopDate,rh.hprhReceiptID,
rd.hprdProcessingId,rd.hprdProcessingDetailId
from (loshpReceiptDetail rd
inner join
loshpReceiptHEader rh on hprdReceiptID=hprhReceiptID and
rd.hprdShopId=rh.hprhShopId and rd.hprdCompanyID=rh.hprHCompanyID and rh.hprhCancel=0)
left outer join
--Payment and Receipt Checking
((aHpPaymentDetail PD inner join  ahpPaymentHEader ph on pd.hpdPaymentID=ph.hphPaymentID
and pd.hpdDepartmentID=ph.hphDepartmentID and pd.hpdCompanyID=ph.hphCompanyID and ph.hphCancel=0)
left outer join (aHpReceiptDetail HQRD  inner join ahpReceiptHeader HQRH on HQRD.hprdReceiptID=HQRH.hprhReceiptID
and HQRD.hprdDepartmentID=HQRH.hprhDepartmentID and HQRD.hprdCompanyID=HQRH.hprHCompanyID and HQRH.hprhCancel=0)
on PD.hpdPaymentID=HQRD.hprdPaymentID and PD.hpdDepartmentID=HQRD.hprdDepartmentID and PD.hpdCompanyID=HQRD.hprdCompanyID)
on rd.hprdReceiptID=PD.hpdReceiptID  and rd.hprdProcessingDetailId=PD.hpdProcessingDetailID
where  rd.hprdReceiptID not in (
select hpdreceiptID from aHpPaymentDetail
INNER JOIN aHpPaymentHeader ON  hpdPaymentID= hphPaymentID AND hphCancel=0
and hpdPaymentID not in (select hprdPaymentID from  aHpReceiptDetail HQRD  inner join ahpReceiptHeader HQRH on HQRD.hprdReceiptID=HQRH.hprhReceiptID
and HQRD.hprdDepartmentID=HQRH.hprhDepartmentID and HQRD.hprdCompanyID=HQRH.hprHCompanyID and HQRH.hprhCancel=0 ) --order by hpdreceiptID
)
Group by  rh.hprhReceiptID, rh.hprhReceiptDate,rh.hprhReceiptID,
rd.hprdProcessingId,rd.hprdProcessingDetailId )Rec
on  pd.hpdProcessingId= Rec.hprdProcessingId and pd.hpdDetailID=Rec.hprdProcessingDetailId
order by hphCustomeriD,pd.hpdChequeDate
) A
GROUP BY
hphCompanyID,hphCustomeriD, hphProcessingNo,hpCustName,hphinvoiceID,hpqhQuotationNo,
hpqhInstPrice,hpqdSellingPrice,hpqhAmount,hpdDepartmentID,hpdProcessingID,hpdDetailID,hpdChequeDate,hpdChequeNo,
Yearname,Monthly, A.hpdSettlementAmount,
hpdInterest,hpAgreementNo,IRRegNo,IrFrameNo
-- STEP 1: To get unearned financial income details based on given period of time
if @details = 1 --if details of cheques needed
begin
if @asondate = 1
begin
insert into #HPFinIncomeSelected
select * from #HPFinIncomeAll
where fiInterest > 0 and fiSettlmentDate <= @dttodate
end
else
begin
insert into #HPFinIncomeSelected
select * from #HPFinIncomeAll
where fiInterest > 0 and fiSettlmentDate >= @dtfromdate and fiSettlmentDate <= @dttodate
end
end
-- STEP 2: To remove selected invoices from #HPFinIncomeAll
delete from #HPFinIncomeAll where fiInvoiceID in
(select distinct fiInvoiceID from #HPFinIncomeSelected)
-- STEP 3: To clear settlement related details of remaining records of #HPFinIncomeAll
update #HPFinIncomeAll
set fiChequeDate =  null, fiProcessingID = 0, fiProcessingNo = '''',
fiYear = 0, fiMonth = 0, fiInterest = 0, fiSettlementAmount = 0
-- STEP 4: To add all remaining invoices from #HPFinIncomeAll to #HPFinIncomeSelected
insert into #HPFinIncomeSelected
select distinct * from #HPFinIncomeAll
select * from #HPFinIncomeSelected
order by fiInvoiceID, fiYear, fiMonth
drop table #HPFinIncomeAll
drop table #HPFinIncomeSelected
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHpReceiptTracking]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpReceiptTracking]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By   : Prasanth Joseph
--Created ON   : 17-05-2008
--Created For  : To get the balace customer payment in HP Shop Receipt
--Modified by  : Regin
--Modifies ON  : 28-11-2008
----------------------------------------
--Modified by  : Nidheesh P V
--Modifies ON  : 28-05-2011
--Comments : Changed the data type of ''''@setBal'''' to ''''numeric(18,2)'''' instead of ''''numeric''''
----------------------------------------
CREATE proc [dbo].[spHpReceiptTracking] @intCustomerID as int,@dtProcDate as datetime
as
set nocount on
create table #tempData(
QuotationNo  varchar(50),
QuotationDate datetime,
--Rental  numeric,    by regin
Rental  numeric(18,2),
ChequeAmount numeric(18,2),
ProcessingNo nvarchar(50),
ChequeDate  datetime,
BankName  nvarchar(50),
ChequeNo nvarchar(50),
QuotationID numeric,
ProcessingID  numeric,
DetailID  numeric)
declare @setBal as numeric(18,2) ,
@QuotationNo as nvarchar(50),
@QuotationDate as datetime,
--@Rental as numeric, by regin
@Rental as numeric(18,2),
@ProcessingNo as nvarchar(50),
@ChequeDate as datetime,
@BankName as nvarchar(50),
@ChequeNo as nvarchar(50),
@QuotationID as numeric,
@ProcessingID as numeric,
@DetailID as numeric,
@strSql as nvarchar(4000) ,
@ChequeAmount as numeric(18,2)
begin
set @setBal=0
declare opcurt cursor for
select hpqhQuotationNo,hpqhQuotationDate,hpdRental-hpdSettlementAmount as hpdRental,hpdRental as ChequeAmount,
hphProcessingNo,HpdChequeDate , hpdBankName,hpdChequeNo,hpqhQuotationID,hpdProcessingID,hpdDetailID
From loshpInvoiceHeader INNER JOIN aHpProcessingHeader
INNER JOIN  aHpProcessingDetail ON hphProcessingID=hpdProcessingID
-- Below condition is added to consider ONLY the active processing details.
-- Added by regin on 28-11-2008
and hphAmended = 0
--And hpdRental-hpdSettlementAmount>0
--and HpdChequeDate>= @dtProcDate
ON hpqhQuotationID=hphInvoiceID And hphCancel = 0  Where hpqhCancel = 0
and hpqhCustomerID=@intCustomerID
	open opcurt
	fetch next from opcurt into @QuotationNo,@QuotationDate,@Rental,@ChequeAmount,@ProcessingNo,@ChequeDate,@BankName,@ChequeNo,
	@QuotationID,@ProcessingID,@DetailID
	while @@fetch_status =0
	begin
		if @setBal= 0
		begin
			if @Rental<0
			begin
				set @setBal=@Rental----over settlmet=balance
			end
		end
		else
		begin
			set @Rental=@Rental+@setBal
			if @Rental<0
				begin
				set @setBal=@Rental
				end
			else
				begin
				set @setBal=0
				end
		end
----select @Rental,@setBal
insert into #tempData values(@QuotationNo,@QuotationDate,@Rental,@ChequeAmount,@ProcessingNo,@ChequeDate,@BankName,@ChequeNo,
@QuotationID,@ProcessingID,@DetailID)
fetch next from opcurt into @QuotationNo,@QuotationDate,@Rental,@ChequeAmount,@ProcessingNo,@ChequeDate,@BankName,@ChequeNo,
@QuotationID,@ProcessingID,@DetailID
end
close opcurt
deallocate opcurt
--select * from    #tempData
set @strsql=N''Select QuotationNo,QuotationNo,QuotationDate,Rental,ChequeAmount,ProcessingNo,ChequeDate,BankName,ChequeNo,
ChequeNo,QuotationID,ProcessingID,DetailID from #tempData where Rental>0''
print @strsql
exec sp_executesql @strsql
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHpProcessingtracking]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpProcessingtracking]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------
--CREATED BY   : PRASANTH JOSEPH
--CREATED ON   : 24-11-2009
--CREATED FOR  : WHILE SELECTION ONE PROCESSING NO, RENTAL SHOULD COME AS LIKE RECEIPT AREA
--USAGE        : EXEC SPHPPROCESSINGTRACKING   1106,200
------------------------------------------------------------------------------
CREATE  proc [dbo].[spHpProcessingtracking] @intCustomerID as int,@intProcessingID as int
as
set nocount on
create table #tempData(
hpdChequeDate  datetime,
hpdCapital numeric(18,2),
hpdRental numeric(18,2),
hpdInterest  numeric(18,2),
hpdcapitalRepayment  numeric(18,2),
hpdCapitalBalance numeric(18,2),
hpdBankName nvarchar(20),
hpdChequeNo  nvarchar(20),
hpdAmount  numeric(18,2),
hpdSettlementAmount numeric(18,2),
hpdInterestRate numeric(18,2)
)
declare @ChequeDate as datetime ,
@Capital as numeric,
@Rental as numeric(18,2),
@Interest as numeric(18,2),
@capitalRepayment as numeric(18,2),
@CapitalBalance as nvarchar(50),
@ChequeNo as nvarchar(50),
@BankName as nvarchar(50),
@Amount as numeric,
@SettlementAmount as numeric,
@InterestRate as numeric(18,2),
@setBal as numeric  ,
@strsql as nvarchar(500)
begin
set @setBal=0
declare opcurt cursor for
select hpdChequeDate,hpdCapital,hpdRental-hpdSettlementAmount as Rental,hpdInterest,hpdcapitalRepayment,hpdCapitalBalance,
hpdBankName,hpdChequeNo,hpdAmount,hpdSettlementAmount,hpdInterestRate
From  aHpProcessingHeader
INNER JOIN  aHpProcessingDetail ON hphProcessingID=hpdProcessingID
Where hphCancel = 0
and hphCustomerID=@intCustomerID   and  hphProcessingID=@intProcessingID
open opcurt
fetch next from opcurt into @ChequeDate,@Capital,@Rental,@Interest,@capitalRepayment,@CapitalBalance,@ChequeNo,
@BankName,@Amount,@SettlementAmount,@InterestRate
while @@fetch_status =0
begin
if @setBal= 0
begin
if @Rental<0
begin
set @setBal=@Rental
end
end
else
begin
set @Rental=@Rental+@setBal
if @Rental<0
begin
set @setBal=@Rental
end
else
begin
set @setBal=0
end
end
insert into #tempData values( @ChequeDate,@Capital,@Rental,@Interest,@capitalRepayment,@CapitalBalance,@ChequeNo,
@BankName,@Amount,@SettlementAmount,@InterestRate )
fetch next from opcurt into  @ChequeDate,@Capital,@Rental,@Interest,@capitalRepayment,@CapitalBalance,@ChequeNo,
@BankName,@Amount,@SettlementAmount,@InterestRate
end
close opcurt
deallocate opcurt
set @strsql=N''Select hpdChequeDate,hpdCapital, hpdRental,hpdInterest ,hpdcapitalRepayment,hpdCapitalBalance,hpdBankName,hpdChequeNo,hpdAmount,
hpdSettlementAmount,hpdInterestRate from #tempData where hpdRental >0''
print @strsql
exec sp_executesql @strsql
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateUserRights]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateUserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
/*
Created by :  Shinu
Created on : 03/02/2007
Modified by :
Modified on :
Purpose      : To Update User Rights Table while Updating User Groups
Modified by  : VinothMurugan V
Modified Date: 30/3/2010
Purpose      : rowguid column not present all the client machine Table.
*/
CREATE Proc [dbo].[SpUpdateUserRights] @intuserGroupid as int,@intCompanyID as int as
Begin
Declare @intUserID as int
declare @Columnpresent as int
set nocount on
Declare UserCur cursor for
Select userid From ausers where usergroupid= @intuserGroupid and CompanyID=@intCompanyID
open UserCur
fetch next FROM UserCur into @intUserID
while @@Fetch_status = 0
begin
---Deleting From user Rights
Delete From auserrights where userid=@intUserID
--Inserting into user rights
insert into auserrights select  @intUserID,ModuleCode,InterfaceID,FunctionRights,CompanyID,newid()
from aUsergrouprights where usergroupid=@intuserGroupid and companyid=@intCompanyID
--Deleting from UserDeoartmentDetails
delete from aUserDeptDetails  where userid=@intUserID
--Inserting into UserDeoartmentDetails
-------------------------------------------
	--Previous one.
	--insert into aUserDeptDetails select companyid,@intUserID,deptid
--from aUserGroupDeptDetails where usergroupid=@intuserGroupid and companyid=@intCompanyID
set @Columnpresent = (SELECT count(c.name) FROM syscolumns c, sysobjects t
	WHERE c.id = t.id AND t.name = ''aUserDeptDetails'' AND c.name = ''rowguid'')
	if @Columnpresent = 1
begin
	insert into aUserDeptDetails select companyid,@intUserID,deptid
from aUserGroupDeptDetails where usergroupid=@intuserGroupid and companyid=@intCompanyID
	end
	else
	begin
	insert into aUserDeptDetails(companyid,userid,deptid) select companyid,@intUserID,deptid
from aUserGroupDeptDetails where usergroupid=@intuserGroupid and companyid=@intCompanyID
	end
-------------------------------------------
--Deleting from mis Rights
delete from amisUserRights  where userid=@intUserID
--Inserting into from mis Rights
insert into amisUserRights select @intUserID,MenuID,CompanyID
from  aUserGroupmisUserRights where usergroupid=@intuserGroupid and companyid=@intCompanyID
--Deleting from Report Rights
delete from areportRights  where userid=@intUserID
--Inserting into from Report Rights
insert into areportRights select @intUserID, reportid,modulecode,Companyid
from aUserGroupreportrights where usergroupid= @intuserGroupid and companyid=@intCompanyID
fetch next FROM UserCur into @intUserID
end
Close UserCur
Deallocate UserCur
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPurchase]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetPurchase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 10/06/2004
-- Modified by   : venkitesh
--   : For Budgeted Sales and Purchase Reports
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spBudgetPurchase]   (@intplanid as int,
@intcompanyid as int,@intdepartmentid as int =0, @intcategoryonly as int =0 ) AS
begin
set nocount on
set ansi_warnings off
declare @strCondition  as varchar(50),
@strsql as nvarchar(4000)
set @strcondition=''''
Create table #TempPlannedPurchaseSales
(companyid int,
departmentid int,
BudgetPlanID int,
BudgetNo VARCHAR(50),
BudgetDate datetime,
ItemID int,
itemcategory int,
Jan numeric(18,2),
Feb numeric(18,2),
Mar numeric(18,2),
April numeric(18,2),
May numeric(18,2),
June numeric(18,2),
July numeric(18,2),
Aug numeric(18,2),
Sept numeric(18,2),
Oct numeric(18,2),
Nov numeric(18,2),
Dec numeric(18,2),
Type varchar(2),
Fstqtr numeric(18,2),
Sndqtr numeric(18,2),
TrdQtr numeric(18,2),
FoQtr numeric(18,2),
FinalValue Numeric(18,2))
if @intdepartmentid >0
set  @strCondition = '' and bphdepartmentid= ''+ convert(varchar(2), @intdepartmentid)
set @strsql = ''Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
case when bpditemcategory =0 then a.itemcategoryid else bpditemcategory end bpditemcategory,
0,0,0,0,0,0,0,0,0,0,0,0,''''P'''',0,0,0,0,0
from budgetplanheader,budgetitemplandetail
left outer join aitem a on
itemid=bpdIBudgetItemID
where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID = ''+ convert(varchar(5),@intplanid) +
'' and  bphCompanyID='' + convert(varchar(2),@intcompanyid ) +
'' and bphtype=''''I'''''' + @strcondition + '' group by  bpdIBudgetItemID,
bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID''
exec sp_executesql @strsql
--Updating jan purchase
Update #TempPlannedPurchaseSales set
Jan =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=1
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  CompanyID= @intcompanyid
--Updating jan Sales and Cost Feb
Update #TempPlannedPurchaseSales set
Feb =   bpdIPurchaseAmt
from budgetitemplandetail where
#TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=2 and
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost March
Update #TempPlannedPurchaseSales set
Mar =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=3
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost April
Update #TempPlannedPurchaseSales set
April =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=4
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost May
Update #TempPlannedPurchaseSales set
May =  bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=5
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost June
Update #TempPlannedPurchaseSales set
June =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=6
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost July
Update #TempPlannedPurchaseSales set
July =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=7
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Aug
Update #TempPlannedPurchaseSales set
Aug =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=8
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost sept
Update #TempPlannedPurchaseSales set
sept =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=9
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Oct
Update #TempPlannedPurchaseSales set
oct =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=10
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Nov
Update #TempPlannedPurchaseSales set
Nov =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=11
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Dec
Update #TempPlannedPurchaseSales set
Dec =   bpdIPurchaseAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno=12
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost First qtr
Update #TempPlannedPurchaseSales set
fstqtr =  jan+feb+mar
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno  in(1,2,3)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Second qtr
Update #TempPlannedPurchaseSales set
Sndqtr = april+may+june
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno  in(4,5,6)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Third qtr
Update #TempPlannedPurchaseSales set
TrdQtr = july+aug+sept
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno in(7,8,9)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Fourth qtr
Update #TempPlannedPurchaseSales set
FoQtr =oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno in (10,11,12)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Full
Update #TempPlannedPurchaseSales set
FinalValue =  jan+feb+mar+april+may+june+july+aug+sept+oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID
and budgetitemplandetail.bpdIBudgetItemID <> 0) or
(#TempPlannedPurchaseSales.itemcategory = budgetitemplandetail.bpditemcategory and
budgetitemplandetail.bpditemcategory<> 0))
and #TempPlannedPurchaseSales.type=''P''
and  bpdimonthno >0
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
if @intcategoryonly>0
select  companyid, departmentid, BudgetPlanID, BudgetNo, BudgetDate, 0 ItemID,
itemcategory, sum(Jan) Jan, sum(Feb)Feb, sum(Mar)Mar, sum(April)April, sum(May)may,
sum(June)June, sum(July)July, sum(Aug)Aug, sum(Sept)sept, sum(Oct)Oct,
sum(Nov)Nov, sum(Dec)Dec, Type, sum(Fstqtr)Fstqtr, sum(Sndqtr)Sndqtr,
sum(TrdQtr)TrdQtr, sum(FoQtr)Foqtr, sum(FinalValue)Finalvalue,
CategoryNameDescription , '''' itemdescription
from #TempPlannedPurchaseSales T,aitemcategory b
where T.itemcategory =b.ItemCategoryID
group by BudgetPlanID,itemcategory,Type,companyid,departmentid,
BudgetNo,BudgetDate,CategoryNameDescription
else
select a.*,b.CategoryNameDescription,c.itemdescription from
#TempPlannedPurchaseSales a LEFT OUTER JOIN aitemcategory b ON
a.itemcategory=b.itemcategoryid left outer join aitem c on
a.ItemID =c.itemid
drop table #TempPlannedPurchaseSales
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetCostSales]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetCostSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spBudgetCostSales  3, 1, 1, 1
-- Last Modified : 04/09/2004, 16/10/2004
-- Modified by   : Hariharan
-- For Budgeted Sales and Purchase Reports
-- Corrected Category wise processing
--Corrected Margin calculation item/category wise
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spBudgetCostSales]   (@intplanid as int,
@intcompanyid as int,@intdepartmentid as int=0,@intcategoryonly as int = 0) AS
begin
set nocount on
set ansi_warnings off
declare
@strcondition as varchar(1000),
@strsql as nvarchar(4000)
Create table #TempPlannedPurchaseSales
(companyid int,
departmentid int,
BudgetPlanID int,
BudgetNo VARCHAR(50),
BudgetDate datetime,
ItemID int,
itemcategory int,
Jan numeric(18,2),
Feb numeric(18,2),
Mar numeric(18,2),
April numeric(18,2),
May numeric(18,2),
June numeric(18,2),
July numeric(18,2),
Aug numeric(18,2),
Sept numeric(18,2),
Oct numeric(18,2),
Nov numeric(18,2),
Dec numeric(18,2),
Type varchar(2),
margin numeric(18,2),
MainType varchar(2),
Fstqtr numeric(18,2),
Sndqtr numeric(18,2),
TrdQtr numeric(18,2),
FoQtr numeric(18,2),
FinalValue Numeric(18,2))
if @intdepartmentid >0
set  @strCondition = '' and bphdepartmentid= ''+ convert(varchar(2), @intdepartmentid)
set @strsql =''Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
case when bpditemcategory =0 then a.itemcategoryid else bpditemcategory end bpditemcategory,
0,0,0,0,0,0,0,0,0,0,0,0,''''S'''',0,''''A'''',0,0,0,0,0
from budgetplanheader,budgetitemplandetail left outer join aitem a on
itemid=bpdIBudgetItemID
where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID = '' + convert(varchar(5),@intplanid) +
'' and  bphCompanyID= ''+ convert(varchar(5), @intcompanyid) +
'' and bphtype=''''I'''''' + @strcondition +
''group by  bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID''
exec sp_executesql @strsql
set @strsql = ''Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID = 0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
case when bpditemcategory =0 then a.itemcategoryid else bpditemcategory end bpditemcategory,
0,0,0,0,0,0,0,0,0,0,0,0,''''C'''',0,''''A'''',0,0,0,0,0
from budgetplanheader,budgetitemplandetail left outer join aitem a on
itemid=bpdIBudgetItemID
where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID =''+ convert(varchar(5),@intplanid) +
'' and  bphCompanyID= ''+ convert(varchar(3), @intcompanyid )+
'' and bphtype=''''I'''''' + @strcondition +
''group by  bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID''
exec sp_executesql @strsql
--Updating jan Sales and Cost Jan
Update #TempPlannedPurchaseSales set
Jan =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=1
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  CompanyID= @intcompanyid
Update #TempPlannedPurchaseSales set
jan =   bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=1
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Feb
Update #TempPlannedPurchaseSales set
Feb =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=2
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Feb = bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=2
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost March
Update #TempPlannedPurchaseSales set
Mar =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=3
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Mar =   bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=3
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost April
Update #TempPlannedPurchaseSales set
April =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=4
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
April =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=4
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost May
Update #TempPlannedPurchaseSales set
May =  bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=5
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
May =   bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=5
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost June
Update #TempPlannedPurchaseSales set
June =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=6
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
June =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=6
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost July
Update #TempPlannedPurchaseSales set
July =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=7
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
July =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=7
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and companyid= @intcompanyid
--Updating jan Sales and Cost Aug
Update #TempPlannedPurchaseSales set
Aug =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=8
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Aug =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=8
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost sept
Update #TempPlannedPurchaseSales set
sept =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=9
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
sept =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=9
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Oct
Update #TempPlannedPurchaseSales set
oct =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=10
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
oct =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=10
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Nov
Update #TempPlannedPurchaseSales set
Nov =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=11
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Nov =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=11
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Dec
Update #TempPlannedPurchaseSales set
Dec =   bpdISalesAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno=12
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Dec =  bpdIcostAmt
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno=12
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost First qtr
Update #TempPlannedPurchaseSales set
fstqtr =  jan+feb+mar
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno  in(1,2,3)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
fstqtr =  jan+feb+mar
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno  in(1,2,3)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Second qtr
Update #TempPlannedPurchaseSales set
Sndqtr = april+may+june
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno  in(4,5,6)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
Sndqtr = april+may+june
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno in(4,5,6)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Third qtr
Update #TempPlannedPurchaseSales set
TrdQtr = july+aug+sept
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno in(7,8,9)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
TrdQtr = july+aug+sept
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno in(7,8,9)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Fourth qtr
Update #TempPlannedPurchaseSales set
FoQtr =oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno in (10,11,12)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
FoQtr =oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno in(10,11,12)
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
--Updating jan Sales and Cost Full
Update #TempPlannedPurchaseSales set
FinalValue =  jan+feb+mar+april+may+june+july+aug+sept+oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''S''
and  bpdimonthno >0
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
Update #TempPlannedPurchaseSales set
FinalValue = jan+feb+mar+april+may+june+july+aug+sept+oct+nov+dec
from budgetitemplandetail where
((#TempPlannedPurchaseSales.ItemID=budgetitemplandetail.bpdIBudgetItemID and
#TempPlannedPurchaseSales.ItemID<>0)
or (#TempPlannedPurchaseSales.itemcategory=budgetitemplandetail.bpdItemCategory and
#TempPlannedPurchaseSales.ItemID = 0))
and #TempPlannedPurchaseSales.type=''C''
and  bpdimonthno >0
and bpdIBudgetPlanID = @intplanid and BudgetPlanID=bpdIBudgetPlanID
and  companyid= @intcompanyid
if @intcategoryonly =0
Begin
--Updating margin
update  #TempPlannedPurchaseSales set margin= (margin.marginper)*100 from
(select bpdIBudgetItemID, case  sum(isnull(bpdISalesAmt,0)) when 0 then 0
else (sum(bpdISalesAmt)- sum(bpdICostAmt)) /sum(bpdISalesAmt) end marginper
from budgetplanheader,budgetitemplandetail where bphBudgetPlanID=bpdIBudgetPlanID
and bphBudgetPlanID = @intplanid and  bphcompanyid= @intcompanyid
and bpdIBudgetItemID >0 group by bpdIBudgetItemID)Margin
where #TempPlannedPurchaseSales.ItemID=margin.bpdIBudgetItemID
update  #TempPlannedPurchaseSales set margin= (margin.marginper)*100 from
(select bpditemcategory, case sum(bpdISalesAmt) when 0 then 0
else (sum(bpdISalesAmt)- sum(bpdICostAmt)) /sum(bpdISalesAmt) end marginper
from budgetplanheader, budgetitemplandetail where bphBudgetPlanID=bpdIBudgetPlanID
and bphBudgetPlanID =  @intplanid and bphcompanyid = @intcompanyid
and bpdIBudgetItemID =0 group by budgetitemplandetail.bpditemcategory)Margin
where #TempPlannedPurchaseSales.itemcategory = margin.bpditemcategory
End
Else
Begin
update  #TempPlannedPurchaseSales set margin= (margin.marginper)*100 from
(select ItemCategoryId bpditemcategory, case sum(bpdISalesAmt) when 0 then 0
else (sum(bpdISalesAmt)- sum(bpdICostAmt)) /sum(bpdISalesAmt) end marginper
from budgetplanheader, budgetitemplandetail, aitem where
bphBudgetPlanID=bpdIBudgetPlanID and bphBudgetPlanID =  @intplanid and
bphcompanyid = @intcompanyid and (bpdIBudgetItemID = aitem.ItemId or
bpditemcategory = aitem.itemcategoryid)
group by aitem.ItemCategoryId)Margin
where #TempPlannedPurchaseSales.itemcategory = margin.bpditemcategory
End
--adding GpRation
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
0,
0,
0,0,0,0,0,0,0,0,0,0,0,0,''Z'',0,''Z'',0,0,0,0,0
from budgetplanheader
where bphBudgetPlanID = @intplanid
and  bphCompanyID= 1
update #TempPlannedPurchaseSales set
jan= a.jan,
feb=a.feb,
mar=a.mar,
april=a.april,
may=a.may,
june=a.june,
july=a.july,
aug=a.aug,
sept=a.sept,
oct=a.oct,
nov =a.nov,
dec=a.dec,
fstqtr =a.fstqtr,
Sndqtr =a.Sndqtr,
TrdQtr =a.TrdQtr,
FoQtr =  a.FoQtr,
FinalValue =a.FinalValue
from
(select
case sum(isnull(jansales,0)) when 0 then 0 else sum(jan)/sum(jansales)*100 end jan,
case sum(isnull(febsales,0)) when 0 then 0 else sum(Feb)/sum(febsales)*100 end feb,
case sum(isnull(marsales,0)) when 0 then 0 else sum(mar)/sum(marsales)*100 end mar,
case sum(isnull(aprilsales,0)) when 0 then 0 else sum(april)/sum(aprilsales)*100 end april,
case sum(isnull(maysales,0)) when 0 then 0 else sum(may)/sum(maysales)*100 end may,
case sum(isnull(junesales,0)) when 0 then 0 else sum(june)/sum(junesales)*100 end june,
case sum(isnull(julysales,0)) when 0 then 0 else sum(july)/sum(julysales)*100 end july,
case sum(isnull(augsales,0)) when 0 then 0 else sum(aug)/sum(augsales)*100 end aug,
case sum(isnull(septsales,0)) when 0 then 0 else sum(sept)/sum(septsales)*100 end sept,
case sum(isnull(octsales,0)) when 0 then 0 else sum(oct)/sum(octsales)*100 end oct,
case sum(isnull(novsales,0)) when 0 then 0 else sum(nov)/sum(novsales)*100 end nov,
case sum(isnull(decsales,0)) when 0 then 0 else sum(dec)/sum(decsales)*100 end dec ,
case sum(isnull(fstqtrsales,0)) when 0 then 0 else sum(Fstqtr)/sum(fstqtrsales)*100 end fstqtr,
case sum(isnull(Sndqtrsales,0)) when 0 then 0 else sum(Sndqtr )/sum(Sndqtrsales)*100 end Sndqtr,
case sum(isnull(TrdQtrsales,0)) when 0 then 0 else sum(TrdQtr)/sum(TrdQtrsales)*100 end TrdQtr,
case sum(isnull(FoQtrsales,0)) when 0 then 0 else sum(FoQtr)/sum(FoQtrsales) * 100 end FoQtr,
case sum(isnull(FinalValuesales,0)) when 0 then 0 else sum(FinalValue)/sum(FinalValuesales)*100 end FinalValue
from
(select
sum(jan)jan,sum(jan)jansales,
sum(feb)feb,sum(feb)febsales,
sum(mar)mar,sum(mar)marsales,
sum(april)april,sum(april)aprilsales,
sum(may)may,sum(may)maysales,
sum(june)june,sum(june)junesales,
sum(july)july,sum(july)julysales,
sum(aug)aug,sum(aug)augsales,
sum(sept)sept,sum(sept)septsales,
sum(oct)oct,sum(oct)octsales,
sum(nov)nov,sum(nov)novsales,
sum(dec)dec,sum(dec)decsales,
sum(Fstqtr)Fstqtr ,sum(Fstqtr )fstqtrsales,
sum(Sndqtr )Sndqtr  ,sum(Sndqtr)Sndqtrsales,
sum(TrdQtr)TrdQtr ,sum(TrdQtr)TrdQtrsales,
sum(FoQtr)FoQtr ,sum(FoQtr)FoQtrsales,
sum(FinalValue) FinalValue ,sum(FinalValue)FinalValuesales
from #TempPlannedPurchaseSales
where type=''S''
union all
select
-sum(jan)jan,0,
-sum(feb)feb,0,
-sum(mar)mar,0,
-sum(april)april,0,
-sum(may)may,0,
-sum(june)june,0,
-sum(july)july,0,
-sum(aug)aug,0,
-sum(sept)sept,0,
-sum(oct)oct,0,
-sum(nov)nov,0,
-sum(dec)dec,0,
-sum(Fstqtr)Fstqtr ,0,
-sum(Sndqtr )Sndqtr  ,0,
-sum(TrdQtr)TrdQtr ,0,
-sum(FoQtr)FoQtr ,0,
-sum(FinalValue)FinalValue,0
from #TempPlannedPurchaseSales
where type=''C'')salesplan)a
where maintype=''Z''
if @intcategoryonly =0
select a.*,b.CategoryNameDescription,c.itemdescription from #TempPlannedPurchaseSales a
LEFT OUTER JOIN aitemcategory b ON
a.itemcategory=b.itemcategoryid
left outer join aitem c on
a.ItemID =c.itemid
else
Select  companyid,departmentid,BudgetPlanID,BudgetNo ,
BudgetDate,0 ItemID,itemcategory, sum(Jan)jan,
sum(Feb)feb,sum(Mar)mar,sum(April)april,sum(May)may,sum(June)june,sum(July)july,
sum(Aug)aug,sum(Sept)sept,sum(Oct)oct,
sum(Nov)nov,sum(Dec)dec,Type ,sum(margin)margin,maintype,sum(Fstqtr)Fstqtr,
sum(Sndqtr)sndqtr,sum(TrdQtr)trdqtr,
sum(FoQtr)Foqtr,sum(FinalValue)Finalvalue,
b.CategoryNameDescription,'''' itemdescription
from #TempPlannedPurchaseSales T left outer join aitemcategory b
on T.itemcategory =b.ItemCategoryID where ItemID = 0
group by maintype,Type,BudgetPlanID,itemcategory,companyid,departmentid,
BudgetNo,BudgetDate,CategoryNameDescription
Union All
Select  companyid,departmentid,BudgetPlanID,BudgetNo ,
BudgetDate,0 ItemID,itemcategory, sum(Jan)jan,
sum(Feb)feb,sum(Mar)mar,sum(April)april,sum(May)may,sum(June)june,sum(July)july,
sum(Aug)aug,sum(Sept)sept,sum(Oct)oct,
sum(Nov)nov,sum(Dec)dec,Type , margin ,maintype,sum(Fstqtr)Fstqtr,
sum(Sndqtr)sndqtr,sum(TrdQtr)trdqtr,
sum(FoQtr)Foqtr,sum(FinalValue)Finalvalue,
b.CategoryNameDescription,'''' itemdescription
from #TempPlannedPurchaseSales T left outer join aitemcategory b
on T.itemcategory =b.ItemCategoryID where ItemID <> 0
group by maintype,Type,BudgetPlanID,itemcategory,companyid,departmentid,
BudgetNo,BudgetDate,CategoryNameDescription, margin
--Select * from #TempPlannedPurchaseSales
drop table #TempPlannedPurchaseSales
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spQuoteDiscount]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spQuoteDiscount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 20/11/2001 9:59:12 AM ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 17/11/2001 9:22:19 PM ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spQuoteDiscount    Script Date: 09/03/2001 02:32:29 ******/
CREATE PROCEDURE [dbo].[spQuoteDiscount] (@strin  varchar(250) ) AS
select wpqty, dpqty from vweligiblefordiscount  where replace(ItemDescription,"''","?") =@strin' 
END
GO
/****** Object:  View [dbo].[vwAccountGroupOrderCounter]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccountGroupOrderCounter]'))
EXEC dbo.sp_executesql @statement = N'
--created by dheena
--created date 21052004
--purpose : arrange order
CREATE view [dbo].[vwAccountGroupOrderCounter] as
	select
		b.GroupID,b.CompanyID,b.GroupDesc,b.AccountType,b.ParentGroupID,
		b.levelcode,
		(select
			count(*)
		 from agroupmaster a
		 where 	a.GroupID<=b.GroupID  and a.CompanyID<=b.CompanyID and
		 a.ParentGroupID<=b.ParentGroupID and a.AccountType=b.AccountType
		 and a.levelcode<=b.levelcode)as counter
	from
		agroupmaster b
	group by  b.GroupID,b.CompanyID,b.GroupDesc,b.AccountType,b.ParentGroupID,
	b.levelcode'
GO
/****** Object:  View [dbo].[vwHPAgreement]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAgreement]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHPAgreement] as
select a.hpAgreementID,a.hpAgreementNO,a.hpagreementDate,day(a.hpagreementDate) AgDate,
month(a.hpagreementDate) AgMonth,year(a.hpagreementDate) AgYear,
a.hpDeliveryDate,day(a.hpDeliveryDate) DeDate,month(a.hpDeliveryDate) DeMonth,year(a.hpDeliveryDate)DeYear
,a.hpDeOfficialName,a.HpDeDesignation,
a.HpDeWitnessNAme,a.HpDeWitnessAddress,a.hpWitnessNIC,a.hpDeWitnessName2,a.hpDeWitnessAddress2,a.hpWitnessNIC2,
a.hpDevVehicleDescription,a.hpDevSoldColor,
c.HPCustID,c.hpDeCustName,
c.hpDeCustAddress,c.hpDeCustIsland,c.HpDeCustAtoll,c.hpNCCNO,
c.HpcustPremphno,c.hpDeGaName,c.hpDeGaAddress,c.hpGaNICNO,c.hpGaPermPHNO,
ir.IRregistrationID,ir.IRRegNo,vw.ItemDescription,Ir.IrCustomerID,
col.ColorName as SoldColor,ir.IrFrameNO,ir.iRModelNO,ir.IREngineNo,
q.hpqhQuotationID,q.hpqhFirstInstAmt,a.hpDevDownPayment,q.hpqhinstPeriod,q.hpQhInstprice,a.hpDevInstAmount,
q.hpqhMonthilyPay,a.hpDevMonthlyPay,(q.hpQhInstprice-q.hpqhFirstInstAmt) hpqhBalanceAmt,a.hpDevBalAmt
from acolor col,vwItemDescription vw,ahpagreementDetail a left outer join losHPCustomerDetails c on a.HpcustID=c.hpCustID ---where a.hpCustID=1
left outer join losHpitemRegistrationdetails ir on a.HpItemRegID=ir.irregistrationID ---where a.HpitemregID=2
left outer join losHpInvoiceHeader q on a.hpQuotationId=q.hpqhQuotationID where ir.IRSoldColor=col.ColorID and
ir.irItemID=vw.ItemID'
GO
/****** Object:  View [dbo].[vwPackQuantity]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPackQuantity]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Created By  :Aadyakumar.D.V
--Created Date:05/10/2011
--Purpose     :To list Pack Quantity in Purchase Bill Interface.
CREATE view [dbo].[vwPackQuantity]  as
select Quantity,a.ItemID,pcd.PackingTypeID from
aItem a
inner join aitempackingdetail pd on a.ItemID=pd.ItemID
inner join aPackingTypeCapacityDetail pcd on pcd.PackingTypeID=pd.PackingTypeID
and pcd.UnitsID=a.UnitsID'
GO
/****** Object:  View [dbo].[vwpackingtype]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpackingtype]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpackingtype    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
CREATE view [dbo].[vwpackingtype] as
select pk.packingtypeid, pd.unitsid, pk.packingtypecode, pk.packingtypename,
case pd.quantity when 1 then a.unitcode else pk.packingtypecode  end
packunitcode, a.unitid, a.unitcode, a.unitname, pd.quantity from apackingtype pk,
apackingtypecapacitydetail pd,aunit a where pk.packingtypeid=pd.packingtypeid and
pd.unitsid=a.unitid'
GO
/****** Object:  View [dbo].[vwHpCustomerDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpCustomerDetails]'))
EXEC dbo.sp_executesql @statement = N'
----Created By          : Prasanth Joseph
----Created On          : 08-12-2007
----Ceated For          : Get HP  Agreement, Customer and itemDetails
----Modified By         :
----ModiFied on         :
CREATE  view [dbo].[vwHpCustomerDetails] as
select a.HpCompanyID,a.hpAgreementNo,a.hpAgreementDate,a.HpcustId,c.hpCustName,
c.hpNccNo,c.hpCustPermanentAdd,c.hpCustPremPhno,
a.hpItemRegID,ir.IrFrameNo,ir.irEngineNo,vw.itemDescription
from ahpagreementDetail a left outer join loshpCustomerdetails c on a.hpCustID=c.hpCustID
left outer join losHpitemRegistrationdetails ir on a.hpItemRegID=ir.irRegistrationID,vwitemDescription vw
where vw.itemid=ir.irItemID'
GO
/****** Object:  View [dbo].[vwHpChequeReceived]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpChequeReceived]'))
EXEC dbo.sp_executesql @statement = N'
---Created by       : Prasanth Joseph
---Created On       : 06-12-2007
---Crated for       : Item Transfer Report
---Modified By      :
---Modified On      :
CREATE view [dbo].[vwHpChequeReceived] as
select ag.hpAgreementNo,c.hpCustName,inv.hpqhQuotationNo,
cqh.hphDate,cqd.hpdChqNo,cqd.hpdBankName,cqd.hpdChqAmount,cqd.hpdchqDate,cqd.hpdchequeStatus from
loshpChequeRegisterHeader cqh left outer join loshpChequeRegisterDetail cqd
on cqh.hphChqRegID=cqd.HpdChqRegID left outer join ahpAgreementdetail ag
on cqh.hphAgreementID=ag.hpAgreementID left outer join loshpInvoiceheader inv
on inv.hpqhQuotationID=cqh.hphInvoiceID left outer join loshpCustomerDetails c
on cqh.hphCustID=c.hpCustID'
GO
/****** Object:  View [dbo].[vwHPAdvancePayment]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAdvancePayment]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Benzigar S D
--Created On : 22/01/2009
--Comment    : For HP Advance Payment Report
CREATE view [dbo].[vwHPAdvancePayment] as
select (hpdAmount-hpdSettlementamount) Amount,hphCustomerID,hpdChequedate,hpqhreferenceid Quotationid,hpagreementid,hpagreementno,hpcustname,hpcustpresentadd from  ahpProcessingdetail
left outer join ahpProcessingHEader on hpdProcessingId=hphProcessingID and hpdDepartmentID=hphDepartmentID
left outer join losHPinvoiceheader on hpqhquotationid=hphinvoiceid and hpqhtype=''I''
left outer join aHPagreementdetail on  hpQuotationid=hpqhreferenceid
left outer join loshpcustomerdetails ahpc on ahpc.hpcustid=hphCustomerID'
GO
/****** Object:  StoredProcedure [dbo].[SPLatestSegmentRates]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPLatestSegmentRates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- ==============================================================================
-- Author: PRAVEEN S. & LAWRENCE M.
-- Create date: 14 October 2010
-- Description: Assign the selling price to Dish based on the dish segment.
-- If the selling price is exist then update the new price otherwise insert the new dish details
-- ==============================================================================
-- Upgraded By : LAWRENCE M.
-- Upgraded On : 26-11-2010
-- Upgrade     : To change the data type from numeric to float
-- in the temporary table for save the digits after the decimal point
-- ==============================================================================
CREATE PROCEDURE [dbo].[SPLatestSegmentRates]
AS
BEGIN
	DECLARE @intRow INT
	DECLARE @intMaxRow INT
	DECLARE @intDishID INT
	DECLARE @intSegmentID INT
	DECLARE @intShopID INT
	DECLARE @intCompanyID INT
	DECLARE @intExist INT
	DECLARE @dblDishSpFig FLOAT
	DECLARE @dblDishSpPer FLOAT
	-- Create #MyTempDishSegmentDetail For Storing
	-- The Datas From TempDishSegmentDetail
	CREATE TABLE #MyTempDishSegmentDetail
	(
		seg_id INT IDENTITY(1,1) NOT NULL,
		seg_detail_Tid INT,
		seg_detail_Theader_id INT,
		seg_detail_Tdishid INT,
		seg_detail_Toutletid INT,
		--  seg_detail_Tdish_cp NUMERIC,
		--  seg_detail_Tdish_sp_fig NUMERIC,
		--  seg_detail_Tdish_sp_per NUMERIC,
		seg_detail_Tdish_cp FLOAT,
		seg_detail_Tdish_sp_fig FLOAT,
		seg_detail_Tdish_sp_per FLOAT,
		seg_detail_Tcompanyid INT,
		seg_detail_TUpdateTime DATETIME,
		seg_detail_TUserID INT,
		seg_detail_TLatestID INT
	)
	-- Insert the datas to #MyTempDishSegmentDetail
	-- From TempDishSegmentDetail
	-- Based ON the max seg_detail_TLatestID
	INSERT INTO #MyTempDishSegmentDetail
	SELECT *
	FROM TempDishSegmentDetail
	WHERE seg_detail_TLatestID = (SELECT max(seg_detail_TLatestID)
	FROM TempDishSegmentDetail)
	SET @intRow = 1
	SELECT @intMaxRow = count(1) FROM #MyTempDishSegmentDetail
	WHILE @intRow <= @intMaxRow
	BEGIN
		SET @intDishID = 0
		SET @intSegmentID = 0
		SET @intShopID = NULL
		SET @intCompanyID = 0
		SET @dblDishSpFig = 0
		SET @dblDishSpPer = 0
		-- Retrieve DishID, SegmentID, ShopID
		SELECT @intDishID = seg_detail_Tdishid,
		@intSegmentID = seg_detail_Theader_id,
		@intShopID = seg_detail_Toutletid,
		@intCompanyID = seg_detail_Tcompanyid,
		@dblDishSpFig = seg_detail_Tdish_sp_fig,
		@dblDishSpPer = seg_detail_Tdish_sp_per
		FROM #MyTempDishSegmentDetail
		WHERE seg_id = @intRow
		-- Check the Dish / Segment / Shop / CompanyID Exist
		SET @intExist = 0
		IF ISNULL(@intShopID,0) = 0
		BEGIN
			SELECT @intExist = count(1)
			FROM DishSegmentDetail
			WHERE  seg_detail_dishid=@intDishID AND
			seg_detail_header_id = @intSegmentID AND
			seg_detail_outletid IS NULL AND
			seg_detail_companyid = @intCompanyID
		END
		ELSE
		BEGIN
			SELECT @intExist = count(1)
			FROM DishSegmentDetail
			WHERE  seg_detail_dishid=@intDishID AND
			seg_detail_header_id = @intSegmentID AND
			seg_detail_outletid = @intShopID AND
			seg_detail_companyid = @intCompanyID
		END
		IF @intExist = 0  -- Not exist Need to Insert
		BEGIN
			INSERT INTO DishSegmentDetail
			(seg_detail_id,
			seg_detail_header_id,
			seg_detail_dishid,
			seg_detail_outletid,
			seg_detail_dish_cp,
			seg_detail_dish_sp_fig,
			seg_detail_dish_sp_per,
			seg_detail_companyid,
			seg_Detail_updatetime,
			seg_Detail_userid)
			SELECT
			seg_detail_Tid,
			seg_detail_Theader_id,
			seg_detail_Tdishid,
			seg_detail_Toutletid,
			seg_detail_Tdish_cp,
			seg_detail_Tdish_sp_fig,
			seg_detail_Tdish_sp_per,
			seg_detail_Tcompanyid,
			seg_detail_TUpdateTime,
			seg_detail_TUserID
			FROM #MyTempDishSegmentDetail
			WHERE seg_id = @intRow
		END
		ELSE -- Exist Need to Update
		BEGIN
			IF ISNULL(@intShopID,0) = 0
			BEGIN
				UPDATE DishSegmentDetail
				SET seg_detail_dish_sp_fig = @dblDishSpFig,
				seg_detail_dish_sp_per = @dblDishSpPer
				WHERE  seg_detail_dishid=@intDishID AND
				seg_detail_header_id = @intSegmentID AND
				seg_detail_outletid IS NULL AND
				seg_detail_companyid = @intCompanyID
			END
			ELSE
			BEGIN
				UPDATE DishSegmentDetail
				SET seg_detail_dish_sp_fig = @dblDishSpFig,
				seg_detail_dish_sp_per = @dblDishSpPer
				WHERE  seg_detail_dishid=@intDishID AND
				seg_detail_header_id = @intSegmentID AND
				seg_detail_outletid = @intShopID AND
				seg_detail_companyid = @intCompanyID
			END
		END
		DELETE FROM #MyTempDishSegmentDetail
		WHERE seg_id = @intRow
		SET @intRow = @intRow + 1
	END
	DROP TABLE #MyTempDishSegmentDetail
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteListItemDetails]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDeleteListItemDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Created By : Regin
--Created On : 05-11-2008
--Purpose    : To delete details in the List Item Detail Table [aListItemDetails]
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spDeleteListItemDetails]
@intListID as int
as
begin
delete from aListItemDetails where ListID=@intListID
end' 
END
GO
/****** Object:  View [dbo].[vwDenominationTotal]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDenominationTotal]'))
EXEC dbo.sp_executesql @statement = N'
--created by venkitesh on 160403
-- Purpose : Getting Total only
CREATE  View [dbo].[vwDenominationTotal] as
select denominationid,shopid,denomdate, sum(damount)damount,sum(ddepamount)depamount,remarks
from denominationheader a
left outer join
denominationdetail b on dshopid=shopid and denominationid=ddenominationid
and cancelled=0
group by denominationid,shopid,denomdate,remarks
union all
select denominationid,shopid,denomdate,sum(dcdAmount) damount,
sum(dcdDepAmount)depamount,remarks from denominationheader a
left outer join
denominationchequedetails c on shopid= dcdshopid and
denominationid=dcddenomid and  cancelled=0
group by denominationid,shopid,denomdate,remarks'
GO
/****** Object:  View [dbo].[vwDishIngrdItems]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDishIngrdItems]'))
EXEC dbo.sp_executesql @statement = N'
---Create View vwDishIngrdItems
CREATE VIEW [dbo].[vwDishIngrdItems]
-- Created by Praveen
-- Date : 19th July 2010
-- Outlets - Ingredients Entry - DishItems
AS
(
SELECT  DISTINCT fb_dd_dishid ItemID ,fb_dd_dishcode ItemCode,
FB_dg_Dishgroupname + '' '' + Fb_Ds_DishSubGroupName + '' '' + fb_dd_dishname
AS ItemDescription
FROM fb_dishdetails
INNER JOIN  fb_dishsubgroup ON  Fb_Ds_DishSubGroupID = fb_dd_dishsubgroupid
INNER JOIN fb_dishgroup ON  FB_dg_Dishgroupid = Fb_Ds_DishGroupID
INNER JOIN Fb_recipedetails ON
Fb_rd_dishid = fb_dd_dishid
)'
GO
/****** Object:  View [dbo].[vwdummyQuotationReport]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyQuotationReport]'))
EXEC dbo.sp_executesql @statement = N'
------Created by  : Prasanth KNR
-----To get the   : Dummy Quotation Report
-----Created On   :ON 02/09/2007
-----Modified On  :
-----Modified on  :
CREATE view [dbo].[vwdummyQuotationReport] as
select h.hpqhShopiD,h.hpqhQuotationid,h.hpqhQuotationNo,h.hpqhQuotationDate,h.hpqhAmount,h.hpqhScheme,
h.hpqhCustName,h.hpqhcustAddress,h.hpQhFirstInstamt,h.HpqhBalAmt,h.hpqhInstPeriod,
h.hpqhCashAllowance,h.hpqhInstPerc,h.hpqhInstcharge,h.hpqhSurcharge,h.hpqhTotAdditional,
h.hpqhInstPrice,h.hpqhMonthilyPay,h.hpqhUserName,d.hpqdItemId,vw.itemdescription,
vw.code,d.hpqdSellingPrice from loshpdummyQuotationheader h,loshpdummyQuotationdetails d,vwitemdescription vw
where h.hpqhQuotationid=d.hpqdQuotationId and d.hpqdItemId=vw.itemid'
GO
/****** Object:  StoredProcedure [dbo].[spLeafNodeValues]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeafNodeValues]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last MOdified on 	: 28/05/03
--Modified by		: leo
CREATE proc [dbo].[spLeafNodeValues] @CompanyID as int, @GroupID as int as
begin
Declare
	@intGroupID as int,
	@intMinGroupID as int,
	@intRowCount as int
	set nocount on	
	CREATE TABLE #Result (GroupID int)
	CREATE TABLE #Stack(GroupID int)
	SELECT @intGroupID = GroupID
	FROM aGroupMaster
	WHERE ParentGroupID = @GroupID
	if @@rowcount = 0
	begin
		INSERT INTO #Result VALUES(@intGroupID)
	end
	else
	begin	
		INSERT INTO #Stack
		SELECT GroupID
		FROM aGroupMaster
		WHERE ParentGroupID = @GroupID
		while (SELECT count(*) FROM #Stack )<> 0
		begin
	  		SELECT @intMinGroupID = min(GroupID) FROM #Stack
			DELETE FROM #Stack WHERE GroupID = @intMinGroupID
			SELECT @intRowCount = count(*)
			FROM aGroupMaster
			WHERE ParentGroupID = @intMinGroupID
			if @intRowCount=0
			begin
				INSERT INTO #Result VALUES(@intMinGroupID)
			end
			else
				INSERT INTO #Stack
				SELECT GroupID
				FROM aGroupMaster
				WHERE ParentGroupID = @intMinGroupID
		end	
	end
	SELECT distinct GroupID FROM #Result
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLeafNode]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeafNode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 20/11/2001 9:59:12 AM ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 17/11/2001 9:22:16 PM ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spLeafNode    Script Date: 09/03/2001 02:32:29 ******/
CREATE proc [dbo].[spLeafNode] @CompanyID as int, @Groupid as int, @strGroupID as varchar(50) output as
begin
Declare
	@intGroupID as int,
	@intMinGroupID as int,
	@intRowCount as int
	set nocount on	
	CREATE TABLE #Stack(GroupID int)
	SET @strGroupID = ''''
	SELECT @intGroupID = GroupID
	FROM aGroupMaster
	WHERE ParentGroupID = @GroupID
	if @@rowcount = 0
	begin
		SET @strGroupID = cast(@GroupID as varchar(5))
	end
	else
	begin	
		INSERT INTO #Stack
		SELECT GroupID
		FROM aGroupMaster
		WHERE ParentGroupID = @GroupID
		while (SELECT count(*) FROM #Stack )<> 0
	  	begin
	  		SELECT @intMinGroupID = min(GroupID) FROM #Stack
			DELETE FROM #Stack WHERE GroupID = @intMinGroupID
			SELECT @intRowCount = count(*)
			FROM aGroupMaster
			WHERE ParentGroupID = @intMinGroupID
			if @intRowCount=0
			begin
				if @strGroupID = ''''
					SET @strGroupID = @strGroupID + cast(@intMinGroupID as varchar(5))
				else
					SET @strGroupID = @strGroupID +  '','' + cast(@intMinGroupID as varchar(5))
			end
			else
				INSERT INTO #Stack
				SELECT GroupID
				FROM aGroupMaster
				WHERE ParentGroupID = @intMinGroupID
		end
	end
	set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vAllIndexes]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vAllIndexes]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vAllIndexes]
AS
SELECT
TABLE_NAME = OBJECT_NAME(i.id),
INDEX_NAME = i.name,
COLUMN_LIST = dbo.GetIndexColumns(OBJECT_NAME(i.id), i.id, i.indid),
IS_CLUSTERED = INDEXPROPERTY(i.id, i.name, ''IsClustered''),
IS_UNIQUE = INDEXPROPERTY(i.id, i.name, ''IsUnique''),
FILE_GROUP = g.GroupName
FROM
sysindexes i
INNER JOIN
sysfilegroups g
ON
i.groupid = g.groupid
WHERE
(i.indid BETWEEN 1 AND 254)
-- leave out AUTO_STATISTICS:
AND (i.Status & 64)=0
-- leave out system tables:
AND OBJECTPROPERTY(i.id, ''IsMsShipped'') = 0'
GO
/****** Object:  StoredProcedure [dbo].[UpdateData]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[UpdateData] As
Begin
Declare @RecID as varchar
Declare @DetailID as varchar
Declare @intNo as integer
Declare @intStid as integer
Declare @intDivid as integer
Begin Tran
Declare CurHeader Cursor For Select LtimeID from ltimeheader Order By LtimeID
Open CurHeader
Fetch next from CurHeader into @RecId
While @@Fetch_status = 0
Begin
Set @intNo = 1
Declare CurDetail Cursor For Select LtimeStageID,LtimeDivisionID from ltimeDetail
Where LtimeID=@RecId
Open CurDetail
Fetch next from CurDetail into @intStid,@intDivid
While @@Fetch_status = 0
Begin
Update ltimeDetail set LtimeDetailNo=@intNo Where LtimeID=@RecId
And ltimeStageId=@intStid And ltimeDivisionId=@intDivid
set @intNo = @intNo + 1
Fetch next from CurDetail into @intStid,@intDivid
End
Close CurDetail
Deallocate CurDetail
Fetch next from CurHeader into @RecId
End
Close CurHeader
Deallocate CurHeader
Commit Tran
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spFindInActiveItems]    Script Date: 10/06/2012 14:17: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].[spFindInActiveItems]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spFindInActiveItemsL 1,''K''
--spFindInActiveItemsL 13,''L''
create procedure [dbo].[spFindInActiveItems]
	@ID as int,@ItemType as char,
	@InactiveItems as int=0 output
as
	declare @Active as int
	declare @getActive as cursor
set @InactiveItems=0
if @ItemType=''K''
	begin
		set @getActive = CURSOR  FOR
		select case when A.Active=0 OR A.forsales=0 OR KM.Active=0 then 0 else 1 end   Active
		from aKitItemMaster KM
		inner join aKitItemDetail KD on KM.KitID=KD.KitID
		inner join aItem A on KD.ItemId = A.ItemID
		where KM.KitID=@ID
	end
else
	begin
		set @getActive = CURSOR  FOR
		select case when A.Active=0 OR A.forsales=0 then 0 else 1 end Active
		from alistitemmaster LM
		inner join alistitemdetails LD on LM.ListID=LD.ListID
		inner join aItem A on LD.ItemId = A.ItemID
		where LD.ListID=@ID
	end
open @getActive
fetch next
from @getActive into @Active
while @@FETCH_STATUS=0
begin
if @Active=0
	 begin
		 set @InactiveItems=1
	 end
--print @Active
fetch next
from @getActive into @Active
end
close @getActive
--print ''Inactive'' print @InactiveItems
return @InactiveItems
deallocate @getActive' 
END
GO
/****** Object:  StoredProcedure [dbo].[spfetchforsegment]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spfetchforsegment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spfetchforsegment    Script Date: 18/01/2003 9:45:43 PM ******/
-- for fetching selected data to the list view for the form formsellingfix
CREATE PROCEDURE [dbo].[spfetchforsegment] (@strin  varchar(250) ) AS
select distinct a.itemcode,a.itemid,a.ItemDescription,
a.costingvalue
from aitempackingdetail aip,apackingtype ptype,
aitem a where aip.itemid=a.itemid and
aip.packingtypeid=ptype.packingtypeid  and
a.ItemDescription  =@strin' 
END
GO
/****** Object:  View [dbo].[vwfinyearperiod]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfinyearperiod]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwfinyearperiod    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwfinyearperiod    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwfinyearperiod    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwfinyearperiod    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.vwfinyearperiod    Script Date: 17/11/2001 9:21:12 PM ******/
--Last Modified : 09/11/01
-- Modified by  :hariharan
-- Modified by  : leo 15/10/01
CREATE view [dbo].[vwfinyearperiod] as
select companyid, financialid,CurFinancialYear, convert(datetime,convert(varchar(4),startyear) +
''/''+convert(varchar(2),startmonth) +''/''+''01'') as sdate,
dateadd(dd,-1,dateadd(m,NoOfPeriod,convert(datetime,convert(varchar(4),startyear) +
''/''+convert(varchar(2),startmonth) +''/''+''01''))) as edate from afinancialyear where
companyid = 1'
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedKOTDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SelectedKOTDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =================================================================================
-- Author: LAWRENCE M.
-- Create date: 09 November 2010
-- Description: To show the KOT details based on the selected KOT numbers
-- If the added item is exist inside the selected KOT then need to show seperatly.
-- Modified by : Lawrence M.
-- Modified Date: 18 February 2011
-- Description : To handle the null for checking the AddedItemType[@intDishtype]
-- Modified by : Lawrence M.
-- Modified Date: 29 March 2011
-- Description : To fix the duplication[Not consider the ShopOutletId] problem
-- =================================================================================
CREATE PROCEDURE [dbo].[SP_SelectedKOTDetails](@KotId AS INT,@OutletId AS INT)
AS
BEGIN
DECLARE @intFirstRow AS INT
DECLARE @intMaxRow AS INT
DECLARE @intDishtype AS INT
DECLARE @intKOTDetailId AS INT
CREATE TABLE #TempSelectedKOT
(
intRowId INT IDENTITY(1,1) NOT NULL,
intDishId INT,
intQty INT,
intDetailId INT,
dblRate DECIMAL,
dblAmount DECIMAL,
DtmKOTDateTime datetime,
intAddedItemType INT
)
CREATE TABLE #TempFinalKOT
(
FKOTNo VARCHAR (50),
FDishID INT,
FstrDish VARCHAR (250),
FQty INT,
FRate DECIMAL,
FAmount DECIMAL,
FKOTDateTime datetime,
FDishGroupID INT,
FAddedDishType INT
)
INSERT INTO #TempSelectedKOT (intDishId,intQty,intDetailId,dblRate,dblAmount,DtmKOTDateTime,intAddedItemType)
SELECT Fb_kd_dishid,fb_kd_kotquantity,Fb_kd_KOTDetailId,fb_kd_rate,( fk.fb_kd_rate * fk.fb_kd_kotquantity ) as Amount,Fb_kh_kotdatetime,fb_kd_addeditemtype
FROM fb_kotheader  kh  inner join fb_kotdetails fk on fk.fb_kd_kotid=kh.fb_kh_kotid and
fb_kd_processed=0 AND kh.Fb_kh_outletid=fk.fb_kd_Outletid where  kh.fb_kh_kotid=@KotId AND Fb_kh_outletid=@OutletId
SET @intFirstRow=1
SELECT @intMaxRow=COUNT(intRowId) FROM #TempSelectedKOT
WHILE @intMaxRow >= @intFirstRow
BEGIN
SET @intDishtype=0
SET @intKOTDetailId=0
SELECT @intDishtype=intAddedItemType,@intKOTDetailId=intDetailId FROM #TempSelectedKOT WHERE intRowId=@intFirstRow
IF (@intDishtype=0 or @intDishtype is null)
BEGIN
INSERT INTO #TempFinalKOT (FKOTNo,FstrDish,FQty,FRate,FAmount,FDishID,FKOTDateTime,FDishGroupID,FAddedDishType)
SELECT  kh.fb_kh_kotno , ( fe.fb_dd_dishname) as Dish, fk.fb_kd_kotquantity  ,fk.fb_kd_rate ,
( fk.fb_kd_rate * fk.fb_kd_kotquantity ) as Amount  , fe.fb_dd_DishID,kh.Fb_kh_kotdatetime,
Fb_Ds_DishGroupID,0
FROM Fb_kotheader kh inner join fb_kotdetails fk on fb_kh_kotId=fb_kd_kotId and fb_kd_processed=0 and
kh.Fb_kh_outletid=fk.fb_kd_Outletid inner join fb_dishdetails fe on
fe.fb_dd_dishid = fk.fb_kd_DishId inner join fb_shopdishdetails ss on
ss.Fb_Sd_Dishid= fk.fb_kd_DishId  and Fb_Sd_Outletid=fk.fb_kd_Outletid inner join fb_dishsubgroup fd on
fd.Fb_Ds_DishSubGroupID= fe.FB_dd_dishsubgroupid  inner join fb_dishgroup fg on
fg.FB_dg_Dishgroupid=fd.Fb_Ds_DishGroupID
WHERE fb_kd_kotid=@KotId and fb_kd_kotdetailid=@intKOTDetailId and fb_kd_Outletid=@OutletId
END
IF @intDishtype=1
BEGIN
INSERT INTO #TempFinalKOT (FKOTNo,FstrDish,FQty,FRate,FAmount,FDishID,FKOTDateTime,FDishGroupID,FAddedDishType)
SELECT kh.fb_kh_kotno , +''        ''+( fe.fb_dd_dishname) as Dish, fk.fb_kd_kotquantity  ,fk.fb_kd_rate ,
( fk.fb_kd_rate * fk.fb_kd_kotquantity ) as Amount  , fe.fb_dd_DishID,kh.Fb_kh_kotdatetime,
Fb_Ds_DishGroupID,1
FROM Fb_kotheader kh inner join fb_kotdetails fk on fb_kh_kotId=fb_kd_kotId and fb_kd_processed=0 and
kh.Fb_kh_outletid=fk.fb_kd_Outletid inner join fb_dishdetails fe on fb_dd_dishid=fb_kd_dishid
inner join fb_shopdishdetails ss on ss.Fb_Sd_Dishid= fk.fb_kd_DishId  and Fb_Sd_Outletid=fk.fb_kd_Outletid inner join fb_dishsubgroup fd on
fd.Fb_Ds_DishSubGroupID= fe.FB_dd_dishsubgroupid  inner join fb_dishgroup fg on
fg.FB_dg_Dishgroupid=fd.Fb_Ds_DishGroupID
WHERE fb_kd_kotid=@KotId  and fb_kd_Outletid=@OutletId and fb_kd_kotdetailid=@intFirstRow
END
IF @intDishtype=2
BEGIN
INSERT INTO #TempFinalKOT (FKOTNo,FstrDish,FQty,FRate,FAmount,FDishID,FKOTDateTime,FDishGroupID,FAddedDishType)
SELECT kh.fb_kh_kotno , +''        ''+( it.ItemDescription) AS Dish, fk.fb_kd_kotquantity  ,fk.fb_kd_rate ,
( fk.fb_kd_rate * fk.fb_kd_kotquantity ) AS Amount  , it.itemid,kh.Fb_kh_kotdatetime,
ic.itemcategoryid,2
FROM Fb_kotheader kh inner join fb_kotdetails fk on fb_kh_kotId=fb_kd_kotId and fb_kd_processed=0 and
kh.Fb_kh_outletid=fk.fb_kd_Outletid inner join aitem it on it.itemid=fk.fb_kd_dishid
inner join aitemcategory ic on ic.itemcategoryid=it.ItemCategoryID
inner join aparentitemcategory pc on
pc.PItemCategoryID=ic.PItemCategoryId
where fb_kd_kotid=@KotId  and fb_kd_Outletid=@OutletId and fb_kd_kotdetailid=@intFirstRow
END
SET @intFirstRow=@intFirstRow+1
END
SELECT @KotId as fb_kh_kotId,FKOTNo as fb_kh_kotno,FDishID as fb_dd_DishID,FstrDish as Dish,FQty as fb_kd_kotquantity,
FRate as fb_kd_rate,FAmount as Amount,FKOTDateTime as Fb_kh_kotdatetime,FDishGroupID as Fb_Ds_DishGroupID,FAddedDishType as AddedDishType
FROM #TempFinalKOT
DROP TABLE #TempSelectedKOT
DROP TABLE #TempFinalKOT
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Sp_KotItemDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sp_KotItemDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
CREATE PROC [dbo].[Sp_KotItemDetails](@Kotid AS INT,@qty AS int, @dishID AS INT,
@row AS INT,@outletid INT,@AddedItemtype INT)
--Created by Prabish VT
--To handle Alternate ingredients
--Created on 08/10/08
--Modified by Praveen S
--Add @outletid and fb_rd_costprice
--Modified by LAWRENCE M.
--To check the added item or normal dish based on this add the values in to the Fb_alternate table
--@AddedItemtype -- 1-Added Dish 2-Added Item 0-Ordinary Dish
--Modified by LAWRENCE M.
--Modified on 25/11/2010
--While inserting the cost price in to fb_alternate table,
--the cost price is take from aitem table not take from ingredients table[Fb_recipedetails] because
--the cost price is not fixed
AS
BEGIN
	DECLARE @intDishID AS INT
	DECLARE @intRow AS INT
	SET @intDishID=0
	SET @intRow=0
	DECLARE @RecipeFirstRow AS INT
	DECLARE @RecipeLastRow AS INT
	DECLARE @Futurebit AS BIT
	IF @AddedItemtype=0
	BEGIN
		--  INSERT INTO Fb_alternate(fb_kotID,fb_dishID,fb_ItemID,fb_row,KotOrder,
		--  Fb_outletid,fb_costprice)
		--  SELECT @Kotid,@dishID,Fb_rd_itemid,@row,Sum(fb_rd_quantity)*@qty KotOrder,
		--  @outletid,fb_rd_costprice
		--  FROM dbo.Fb_recipedetails WHERE Fb_rd_dishid = @dishID
		--  GROUP BY Fb_rd_itemid,fb_rd_costprice
		SELECT @RecipeLastRow=count(Fb_rd_dishid) FROM Fb_recipedetails WHERE Fb_rd_dishid=@dishID
		SET @RecipeFirstRow=1
		WHILE @RecipeLastRow>=@RecipeFirstRow
		BEGIN
			SELECT @Futurebit=Fb_rd_Futurebit
			FROM Fb_recipedetails
			WHERE Fb_rd_dishid=@dishID AND Fb_rd_recipedetailid=@RecipeFirstRow
			IF @Futurebit=0
			BEGIN
				INSERT INTO Fb_alternate(fb_kotID,fb_dishID,fb_ItemID,fb_row,KotOrder,
				Fb_outletid,fb_costprice)
				SELECT @Kotid,@dishID,Fb_rd_itemid,@row,Sum(fb_rd_quantity)*@qty KotOrder,
				@outletid,ItemRate
				FROM Fb_recipedetails INNER JOIN aitem ON Fb_rd_itemid=ItemID
				WHERE  Fb_rd_recipedetailid=@RecipeFirstRow AND Fb_rd_dishid=@dishID
				GROUP BY Fb_rd_itemid,ItemRate
			END
			ELSE
			BEGIN
				INSERT INTO Fb_alternate(fb_kotID,fb_dishID,fb_ItemID,fb_row,KotOrder,
				Fb_outletid,fb_costprice)
				SELECT @Kotid,@dishID,Fb_rd_itemid,@row,Sum(fb_rd_quantity)*@qty KotOrder,
				@outletid,fb_dd_dishcp
				FROM Fb_recipedetails INNER JOIN fb_dishdetails ON Fb_rd_itemid=fb_dd_dishid
				WHERE  Fb_rd_recipedetailid=@RecipeFirstRow AND Fb_rd_dishid=@dishID
				GROUP BY Fb_rd_itemid,fb_dd_dishcp
			END
			SET @RecipeFirstRow=@RecipeFirstRow+1
		END
	END
	IF @AddedItemtype=1
	BEGIN
		SELECT @intRow=MAX(fb_row) FROM Fb_alternate WHERE fb_kotid=@Kotid AND Fb_outletId=@outletid
		SELECT @intDishID=fb_dishid FROM fb_alternate WHERE fb_kotid=@Kotid AND Fb_row=@intRow AND Fb_outletId=@outletid
		INSERT INTO Fb_alternate(fb_kotID,fb_dishID,fb_ItemID,fb_row,KotOrder,
		Fb_outletid,fb_costprice)
		SELECT @Kotid,fb_da_dishid,Fb_da_itemid,@row,sum(fb_da_quantity)*@qty KotOrder,
		@outletid,fb_dd_dishcp
		FROM fb_Dishadds INNER JOIN Fb_dishdetails  ON fb_da_Itemid=fb_dd_dishid
		WHERE fb_da_Itemid=@dishID and fb_da_dishid=@intDishID
		GROUP BY fb_da_dishid,Fb_da_itemid,fb_dd_dishcp
	END
	IF @AddedItemtype=2
	BEGIN
		SELECT @intRow=MAX(fb_row) FROM Fb_alternate WHERE fb_kotid=@Kotid AND Fb_outletId=@outletid
		SELECT @intDishID=MAX(fb_dishid) FROM fb_alternate WHERE fb_kotid=@Kotid AND Fb_row=@intRow AND Fb_outletId=@outletid
		INSERT INTO Fb_alternate(fb_kotID,fb_dishID,fb_ItemID,fb_row,KotOrder,
		Fb_outletid,fb_costprice)
		SELECT @Kotid,fb_da_dishid,Fb_da_itemid,@row,sum(fb_da_quantity)*@qty KotOrder,
		@outletid,ItemRate
		FROM fb_Dishadds INNER JOIN aitem ON itemid=fb_da_Itemid
		WHERE fb_da_Itemid=@dishID and fb_da_dishid=@intDishID
		GROUP BY fb_da_dishid,fb_da_dishid,Fb_da_itemid,ItemRate
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[CrmSpGetTask]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CrmSpGetTask]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[CrmSpGetTask]
@Taskid as int
as
select * from CrmTask where TaskId=@Taskid' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_help_column]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_help_column]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Regin customized sp_help into sp_help_column
-- To display only coulumn details
-- on 17-01-2009
create proc [dbo].[sp_help_column]
@objname nvarchar(776) = NULL  -- object name we''re after
as
-- PRELIMINARY
set nocount on
declare @dbname sysname
-- OBTAIN DISPLAY STRINGS FROM spt_values UP FRONT --
declare @no varchar(35), @yes varchar(35), @none varchar(35)
select @no = name from master.dbo.spt_values where type = ''B'' and number = 0
select @yes = name from master.dbo.spt_values where type = ''B'' and number = 1
select @none = name from master.dbo.spt_values where type = ''B'' and number = 2
-- If no @objname given, give a little info about all objects.
if @objname is null
begin
-- DISPLAY ALL SYSOBJECTS --
select
''Name''          = o.name,
''Owner''         = user_name(uid),
''Object_type''   = substring(v.name,5,31)
from sysobjects o, master.dbo.spt_values v
where o.xtype = substring(v.name,1,2) collate database_default and v.type = ''O9T''
order by Object_type desc, Name asc
print '' ''
-- DISPLAY ALL USER TYPES
select
''User_type''  = name,
''Storage_type'' = type_name(xtype),
''Length''  = length,
''Prec''   = TypeProperty(name, ''precision''),
''Scale''   = TypeProperty(name, ''scale''),
''Nullable''  = case when TypeProperty(name, ''AllowsNull'') = 1
then @yes else @no end,
''Default_name'' = isnull(object_name(tdefault), @none),
''Rule_name''  = isnull(object_name(domain), @none),
''Collation''  = collation
from systypes
where xusertype > 256
order by name
return(0)
end
-- Make sure the @objname is local to the current database.
select @dbname = parsename(@objname,3)
if @dbname is not null and @dbname <> db_name()
begin
raiserror(15250,-1,-1)
return(1)
end
-- @objname must be either sysobjects or systypes: first look in sysobjects
declare @objid int
declare @sysobj_type char(2)
select @objid = id, @sysobj_type = xtype from sysobjects where id = object_id(@objname)
-- IF NOT IN SYSOBJECTS, TRY SYSTYPES --
if @objid is null
begin
-- UNDONE: SHOULD CHECK FOR AND DISALLOW MULTI-PART NAME
select @objid = xusertype from systypes where name = @objname
-- IF NOT IN SYSTYPES, GIVE UP
if @objid is null
begin
select @dbname=db_name()
raiserror(15009,-1,-1,@objname,@dbname)
return(1)
end
-- DATA TYPE HELP (prec/scale only valid for numerics)
select
''Type_name''  = name,
''Storage_type'' = type_name(xtype),
''Length''  = length,
''Prec''   = TypeProperty(name, ''precision''),
''Scale''   = TypeProperty(name, ''scale''),
''Nullable''  = case when allownulls=1 then @yes else @no end,
''Default_name'' = isnull(object_name(tdefault), @none),
''Rule_name''  = isnull(object_name(domain), @none),
''Collation''  = collation
from systypes
where xusertype = @objid
return(0)
end
-- DISPLAY COLUMN IF TABLE / VIEW
if @sysobj_type in (''S '',''U '',''V '',''TF'',''IF'')
begin
-- SET UP NUMERIC TYPES: THESE WILL HAVE NON-BLANK PREC/SCALE
declare @numtypes nvarchar(80)
select @numtypes = N''tinyint,smallint,decimal,int,real,money,float,numeric,smallmoney''
-- INFO FOR EACH COLUMN
print '' ''
select
''Column_name''   = name,
''Type''     = type_name(xusertype),
''Computed''    = case when iscomputed = 0 then @no else @yes end,
''Length''    = convert(int, length),
''Prec''     = case when charindex(type_name(xtype), @numtypes) > 0
then convert(char(5),ColumnProperty(id, name, ''precision''))
else ''     '' end,
''Scale''     = case when charindex(type_name(xtype), @numtypes) > 0
then convert(char(5),OdbcScale(xtype,xscale))
else ''     '' end,
''Nullable''    = case when isnullable = 0 then @no else @yes end,
''TrimTrailingBlanks'' = case ColumnProperty(@objid, name, ''UsesAnsiTrim'')
when 1 then @no
when 0 then @yes
else ''(n/a)'' end,
''FixedLenNullInSource'' = case
when type_name(xtype) not in (''varbinary'',''varchar'',''binary'',''char'')
Then ''(n/a)''
When status & 0x20 = 0 Then @no
Else @yes END,
''Collation''  = collation
from syscolumns where id = @objid and number = 0 order by colid
end
return (0) -- sp_help' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmGetCurrency]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmGetCurrency]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[SpLmGetCurrency]
as
select CurrencyID,CurrencyName from aCurrencyMaster' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumCurrencyPrw]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSumCurrencyPrw]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---spDebtorAgeSumCurrencyPrw ''20070101'',''20110630'',''9984'',0,0,0,'''','''',1
-----------------------------------------------------------------------------
-- Created by   : Nidheesh P V
-- Created on  : 10/06/2010
-- Comments  : To show outstanding invoice report in the selected currency.
-----------------------------------------------------------------------------
-- Altered by  : Nidheesh P V
-- Altered on  : 12/04/2011
-- Comments  : To get dollar exchange rate correctly.
--  before ''20110411'' it is 12.85 and after this date it is being taken from exchnagerate table
-----------------------------------------------------------------------------
-- Altered by  : Nidheesh P V
-- Altered on  : 12/04/2011
-- Comments  : Created tables to track exchnage history.And these are used in
-- the sp to get correct exchanhge rate between any two dates.
--Refered Area : Outstanding Invoices Currencywise report
--Ref No : Ref-01
-----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spDebtorAgeSumCurrencyPrw] (
@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)='''',@ToCurrencyId as int )
as
begin
set nocount on
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)
declare @strToCurrencyID as Varchar(2)
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,9),
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),
age int
)
Create Table #tmpSettlements
(customerid int,
ReceiptNo varchar(50),
companyid int,
invoiceid int,
shopid int,
settleddate datetime,
departmentid int,
settledamt numeric(18,9),
Type varchar(50))
-- Commented (RefNo-1)
-------------Ref-01----------------------------------------------------------------
--This stores the exchange history with the first Exchange date as the START DATE
--and second Excnage date as the END DATE from ExchangeRateHistoryHeader table.
--This table returns the excnage rate between two dates.
create Table #ExchangeHistory
(
id int,    		            --Exchange ID
currencyid int,             --Currency ID
sellingrate numeric(18,2),  --Exchange Rate
startdate datetime,         --Exchange Rate Start Date
enddate datetime,           --Exchange Rate End Date
)
--------------Ref-01---------------------------------
;with cteExch(ID,exid,startdate,enddate,Exdate)
as
(
select top 1 ExchangeID,ExchangeID,getdate(),ExchangeDate,getdate()
from ExchangeRateHistoryHeader order by ExchangeID desc
union all
select ExchangeID,ExchangeID-1,ExchangeDate,cte.exdate,ExchangeDate
from ExchangeRateHistoryHeader t inner join cteExch cte on cte.exid=t.ExchangeID
)
insert into #ExchangeHistory
select ID,currencyid,sellingrate,startdate,enddate
from cteExch c inner join ExchangeRateHistoryDetails ed on c.ID=ed.exchangeid
where startdate<=enddate
----------------Ref-01-------------------------------------------------------------------
set @strToCurrencyID=(select convert(varchar(2),@ToCurrencyId))
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 = ''vwsettlements. 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
begin
set @strquery =''insert #tmpInvoices
Select
vwInvoices.CompanyID,vwInvoices.shopid,vwInvoices.DepartmentID,vwInvoices.InvoiceID,
vwInvoices.customerid,invoicedate,invoiceno,Referenceno,remarks,
convert(numeric(18,9),invamt*ToCurr.sellingrate/fromCurr.sellingrate) as InvAmt,
Due,Type,Debtortype,updatetime,vwInvoices.CustomerCategory,
duedate,depexrate,InterFaceID,SalesPersonID,
vwInvoices.CustomerType,DutyAmt,CostPrice,vwInvoices.CustGroupName,0
from vwInvoices
LEFT OUTER JOIN aCustomerMaster on vwInvoices.customerid = aCustomerMaster.CustomerID
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
invoicedate between fromCurr.startdate and fromCurr.enddate
INNER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)    ---Ref-01
end
else
begin
set @strquery =''insert #tmpInvoices
Select
vwInvoices.CompanyID,vwInvoices.shopid,vwInvoices.DepartmentID,vwInvoices.InvoiceID,
vwInvoices.customerid,invoicedate,invoiceno,Referenceno,remarks,
convert(numeric(18,9),invamt*ToCurr.sellingrate/fromCurr.sellingrate) as InvAmt,
Due,Type,Debtortype,updatetime,vwInvoices.CustomerCategory,
duedate,depexrate,InterFaceID,SalesPersonID,
vwInvoices.CustomerType,DutyAmt,CostPrice,vwInvoices.CustGroupName,0
from vwInvoices
LEFT OUTER JOIN aCustomerMaster on vwInvoices.customerid = aCustomerMaster.CustomerID
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
invoicedate between fromCurr.startdate and fromCurr.enddate
INNER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @Invcustid + @strCatCond + @strGroupCond +                           --Ref-01
'' invoicedate <='''''' + @dtinvdate + ''''''''
end
End
Else
Begin
if @intdepartid >0
begin
set @strquery =''insert #tmpInvoices
Select
vwInvoices.CompanyID,vwInvoices.shopid,vwInvoices.DepartmentID,vwInvoices.InvoiceID,
vwInvoices.customerid,invoicedate,invoiceno,Referenceno,remarks,
convert(numeric(18,9),invamt*ToCurr.sellingrate/fromCurr.sellingrate) as InvAmt,
Due,Type,Debtortype,updatetime,vwInvoices.CustomerCategory,
duedate,depexrate,InterFaceID,SalesPersonID,
vwInvoices.CustomerType,DutyAmt,CostPrice,vwInvoices.CustGroupName,0
from vwInvoices
LEFT OUTER JOIN aCustomerMaster on vwInvoices.customerid = aCustomerMaster.CustomerID
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
invoicedate between fromCurr.startdate and fromCurr.enddate
INNER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''                    --Ref-01
end
else
begin
set @strquery =''insert #tmpInvoices
Select
vwInvoices.CompanyID,vwInvoices.shopid,vwInvoices.DepartmentID,vwInvoices.InvoiceID,
vwInvoices.customerid,invoicedate,invoiceno,Referenceno,remarks,
convert(numeric(18,9),invamt*ToCurr.sellingrate/fromCurr.sellingrate) as InvAmt,
Due,Type,Debtortype,updatetime,vwInvoices.CustomerCategory,
duedate,depexrate,InterFaceID,SalesPersonID,
vwInvoices.CustomerType,DutyAmt,CostPrice,vwInvoices.CustGroupName,0
from vwInvoices
LEFT OUTER JOIN aCustomerMaster on vwInvoices.customerid = aCustomerMaster.CustomerID
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
invoicedate between fromCurr.startdate and fromCurr.enddate
INNER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''' +
'''''' and invoicedate >='''''' + @dtstartdate + ''''''''                    --Ref-01
end
End
----print @strquery
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
begin
set @strquery  = '' insert #tmpSettlements
select vwsettlements.customerid,ReceiptNo,
vwsettlements.companyid,vwsettlements.invoiceid,vwsettlements.shopid,settleddate,vwsettlements.departmentid,
convert(numeric(18,9),isnull(settledamt,0)*ToCurr.sellingrate/fromCurr.sellingrate)as settledamt,
vwsettlements.Type
from vwsettlementsements
LEFT OUTER JOIN aCustomerMaster on vwsettlements.customerid = aCustomerMaster.CustomerID
INNER JOIN vwInvoices vwinv on vwinv.customerid = vwsettlements.customerid AND
vwinv.CompanyID = vwsettlements.companyid AND vwinv.InvoiceID = vwsettlements.invoiceid AND
vwinv.type = vwsettlements.type AND vwinv.shopid = vwsettlements.shopid
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
vwinv.invoicedate between fromCurr.startdate and fromCurr.enddate
LEFT OUTER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  ''''''''                  --Ref-01
end
else
begin
set @strquery  = ''insert #tmpSettlements
select vwsettlements.customerid,ReceiptNo,
vwsettlements.companyid,vwsettlements.invoiceid,vwsettlements.shopid,settleddate,vwsettlements.departmentid,
convert(numeric(18,9),isnull(settledamt,0)*ToCurr.sellingrate/fromCurr.sellingrate)as settledamt,
vwsettlements.Type
from vwsettlements
LEFT OUTER JOIN aCustomerMaster on vwsettlements.customerid = aCustomerMaster.CustomerID
INNER JOIN vwInvoices vwinv on vwinv.customerid = vwsettlements.customerid AND
vwinv.CompanyID = vwsettlements.companyid AND vwinv.InvoiceID = vwsettlements.invoiceid AND
vwinv.type = vwsettlements.type AND vwinv.shopid = vwsettlements.shopid
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
vwinv.invoicedate between fromCurr.startdate and fromCurr.enddate
LEFT OUTER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + ''''''''                                        ---Ref-01
end
End
Else
Begin
if @intdepartid >0
begin
set @strquery  = '' insert #tmpSettlements
select vwsettlements.customerid,ReceiptNo,
vwsettlements.companyid,vwsettlements.invoiceid,vwsettlements.shopid,settleddate,vwsettlements.departmentid,
convert(numeric(18,9),isnull(settledamt,0)*ToCurr.sellingrate/fromCurr.sellingrate)as settledamt,
vwsettlements.Type
from vwsettlements
LEFT OUTER JOIN aCustomerMaster on vwsettlements.customerid = aCustomerMaster.CustomerID
INNER JOIN vwInvoices vwinv on vwinv.customerid = vwsettlements.customerid AND
vwinv.CompanyID = vwsettlements.companyid AND vwinv.InvoiceID = vwsettlements.invoiceid AND
vwinv.type = vwsettlements.type AND vwinv.shopid = vwsettlements.shopid
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
vwinv.invoicedate between fromCurr.startdate and fromCurr.enddate
LEFT OUTER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''                       --Ref-01
end
else
begin
set @strquery  = ''insert #tmpSettlements
select vwsettlements.customerid,ReceiptNo,
vwsettlements.companyid,vwsettlements.invoiceid,vwsettlements.shopid,settleddate,vwsettlements.departmentid,
convert(numeric(18,9),isnull(settledamt,0)*ToCurr.sellingrate/fromCurr.sellingrate)as settledamt,
vwsettlements.Type
from vwsettlements
LEFT OUTER JOIN aCustomerMaster on vwsettlements.customerid = aCustomerMaster.CustomerID
INNER JOIN vwInvoices vwinv on vwinv.customerid = vwsettlements.customerid AND
vwinv.CompanyID = vwsettlements.companyid AND vwinv.InvoiceID = vwsettlements.invoiceid AND
vwinv.type = vwsettlements.type AND vwinv.shopid = vwsettlements.shopid
INNER JOIN #ExchangeHistory fromCurr on fromCurr.currencyid=aCustomerMaster.currencyid and
vwinv.invoicedate between fromCurr.startdate and fromCurr.enddate
LEFT OUTER JOIN ExchangeRateDetail ToCurr on ToCurr.currencyid=''''''+@strToCurrencyID+''''''
where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''                  --Ref-01
end
End
-----print @strquery
exec sp_Executesql @strquery
-----RefNo:01
set @strquery = ''SELECT
convert(numeric(18,2),max(invamt))invamt,
convert(numeric(18,2),sum(isnull(settledamt,0)))settledamt,
#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,
#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,aCurrencyMaster.currencyname,aCurrencyMaster.symbol,PrvwCurr.symbol[PrevwCurr] ,#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)
LEFT OUTER JOIN aCustomerMaster on #tmpInvoices.customerid = aCustomerMaster.CustomerID
LEFT OUTER JOIN aCurrencyMaster PrvwCurr on PrvwCurr.currencyId=''''''+@strToCurrencyID+''''''
,aCurrencyMaster , 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,aCurrencyMaster.currencyname,aCurrencyMaster.symbol, #tmpInvoices.duedate,
PrvwCurr.currencyname,PrvwCurr.symbol,address1, address2, address3, #tmpInvoices.referenceno, debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID
having max(convert(numeric(18,2),invamt))<>convert(numeric(18,2),sum(isnull(settledamt,0)))''       --Ref-01
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
----print @strquery
exec sp_Executesql @strquery
--select * from #tempvwsettlements
-- Commented (RefNo-1)
-- drop table #tempvwInvoices
-- drop table #tempvwsettlements
drop table #tmpInvoices
drop table #tmpSettlements
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SPHPOVERDUE]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPHPOVERDUE]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
CREATED BY  : SHINE DAS
ON   : 01/JUNE/2009
COMMENTS : CREATED FOR GETTING OVERDUE BALANCE FOR SELECT CUSTOMER BASED ON DATE.
THIS PROCEDURE IS CREATED FROM VWSPOVEDUEBALANCE.
*/
CREATE PROC [dbo].[SPHPOVERDUE] AS
DECLARE @COMPANY_ID INT
DECLARE @DEPARTMENT_ID INT
DECLARE @FINANCIAL_ID INT
DECLARE @TRAN_ID INT
DECLARE @TRAN_NO NVARCHAR(200)
DECLARE @DUE_DATE DATETIME
DECLARE @R_AMOUNT DECIMAL(18,3)
DECLARE @SETLD_AMOUNT DECIMAL(18,3)
DECLARE @PAID_AMOUNT DECIMAL(18,3)
DECLARE @CUST_ID INT
DECLARE @CUST_NAME  NVARCHAR(250)
DECLARE @AGREEMENT_ID INT
DECLARE @AGREEMENT_NO NVARCHAR(200)
DECLARE @TRANTYPE  NVARCHAR(10)
DECLARE @DUMMY_BALANCE DECIMAL(18,3)
DECLARE @BALANCE_AMOUNT DECIMAL(18,3)
DECLARE @ft int
DECLARE @lt int
DECLARE @ORGSETLD_AMOUNT DECIMAL
CREATE TABLE #TEMPOVERDUEBALANCE(
COMPANY_ID INT,
DEPARTMENT_ID INT,
FINANCIAL_ID INT,
TRAN_ID INT,
TRAN_NO NVARCHAR(200),
DUE_DATE DATETIME,
R_AMOUNT DECIMAL(18,3),
SETLD_AMOUNT DECIMAL(18,3),
PAID_AMOUNT DECIMAL(18,3),
BALANCE_AMOUNT DECIMAL(18,3),
CUST_ID INT,
AGREEMENT_ID INT,
AGREEMENT_NO NVARCHAR(200),
TRANTYPE  NVARCHAR(10),
DUMMY_BALANCE DECIMAL(18,3),
CUST_NAME VARCHAR(250))
SET @DUMMY_BALANCE =0
-------------------------------
/*select @BALANCE_AMOUNT = SUM(TESTAMOUNT-AMOUNT) from VWHPOVERDUEBALANCETEST
WHERE TESTAMOUNT>AMOUNT  ---WHERE tranno like ''07/YAM/HPPR/57''
---and AMOUNT<TESTAMOUNT
*/
--------------------
DECLARE cur_HPOVERDUEBALANCE CURSOR FOR
----------------
select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphProcessingID TranID,hphProcessingNo TranNo,
hpdChequeDate DueDate,hpdRental Amount, hpdsettlementamount testamount,
hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Inst'' TranType,hpCustName
from
ahpprocessingHeader left outer join ahpprocessingDetail
on hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphProcessingID=hpdProcessingID left outer  join loshpcustomerdetails on
hphCustomerID=hpCustID
left outer join (loshpinvoiceheader left outer join ahpAgreementdetail ag
on hpqhReferenceID=ag.hpQuotationID)
on hphinvoiceid=hpqhQuotationID
where
hphCancel=0 and hphAmended=0
UNION ALL
Select
hphCompanyID companyid,hphDepartmentID DepartmentID,hphFinancialID FianancialID,
hphPaymentID TranID,hphPaymentNo TranNo,
hphPaymentDate DueDate,hprdRentalAmount Amount, hprdSettelmentAmount testamount,
hphCustomerID CustomerID,hpAgreementID,hpAgreementNO,''Pay'' TranType,hpCustName
from
ahpPaymentHeader LEFT JOIN ahpReceiptDetail ON
HPHPAYMENTID=HPRDPAYMENTID AND HPHCANCEL=0
left outer join (ahpPaymentdetail
inner join
(select
hprdCompanyID,hprdReceiptID,hprdDetailId,hprdRentalAmount,hprdSettelmentAmount,
hpAgreementID,hpAgreementNO,hprdProcessingDetailId
from
loshpReceiptDetail left outer join (loshpinvoiceheader inv
left outer join ahpAgreementdetail ag on inv.hpqhReferenceID=ag.hpQuotationID )
on hprdInvoiceID=inv.hpqhQuotationID and inv.hpqhType=''I'' and inv.hpqhCancel=0
left outer join loshpReceiptHEader on  hprdReceiptID=hprhReceiptID
where hprhReceiptType=''S'' )Rec on
hpdReceiptID=hprdReceiptID )
on hphPaymentID=hpDpaymentID and
hpdProcessingDetailID=hprdProcessingDetailId
and hphCancel=0 and hphPaymentId not in (
select hprdPaymentID from ahpReceiptHEader inner join ahpReceiptDetail
on hprhReceiptID=hprdReceiptID and hprhDepartmentID=hprdDepartmentID
and hprhCompanyID=hprdCompanyID and hprhCancel=0)left outer  join loshpcustomerdetails on
hphCustomerID=hpCustID order by    hphCustomerID
OPEN cur_HPOVERDUEBALANCE
FETCH NEXT FROM cur_HPOVERDUEBALANCE INTO
@COMPANY_ID,
@DEPARTMENT_ID,
@FINANCIAL_ID,
@TRAN_ID,
@TRAN_NO,
@DUE_DATE,
@R_AMOUNT,
@SETLD_AMOUNT,
@CUST_ID,
@AGREEMENT_ID,
@AGREEMENT_NO,
@TRANTYPE,
@CUST_NAME
set @ft=@CUST_ID ---@TRAN_ID
select @BALANCE_AMOUNT = (SUM(TESTAMOUNT) - SUM(AMOUNT)) from VWHPOVERDUEBALANCETEST
WHERE TESTAMOUNT<>AMOUNT
WHILE @@FETCH_STATUS = 0
BEGIN
set @PAID_AMOUNT = @SETLD_AMOUNT
IF (@SETLD_AMOUNT<@R_AMOUNT)
BEGIN
IF (@BALANCE_AMOUNT>=@R_AMOUNT)
BEGIN
SET @DUMMY_BALANCE = @SETLD_AMOUNT-@R_AMOUNT
SET @SETLD_AMOUNT=@R_AMOUNT
SET @BALANCE_AMOUNT=@BALANCE_AMOUNT+@DUMMY_BALANCE
END
ELSE IF (@BALANCE_AMOUNT>0 and @BALANCE_AMOUNT<@R_AMOUNT)
BEGIN
IF (@BALANCE_AMOUNT>=(@R_AMOUNT-@SETLD_AMOUNT))
BEGIN
SET @SETLD_AMOUNT=@R_AMOUNT
SET @BALANCE_AMOUNT=@BALANCE_AMOUNT-(@R_AMOUNT-@SETLD_AMOUNT)
END
ELSE IF (@BALANCE_AMOUNT<(@R_AMOUNT-@SETLD_AMOUNT))
BEGIN
SET @SETLD_AMOUNT=@SETLD_AMOUNT+@BALANCE_AMOUNT
SET @BALANCE_AMOUNT=@SETLD_AMOUNT-@R_AMOUNT
END
END
ELSE
BEGIN
SET @BALANCE_AMOUNT=@BALANCE_AMOUNT+ (@SETLD_AMOUNT-@R_AMOUNT)
END
/*  SET @SETLD_AMOUNT=@BALANCE_AMOUNT
SET @DUMMY_BALANCE=@SETLD_AMOUNT-@R_AMOUNT
SET @BALANCE_AMOUNT=@DUMMY_BALANCE   */
END
ELSE
BEGIN
SET @DUMMY_BALANCE = @SETLD_AMOUNT-@R_AMOUNT
SET @SETLD_AMOUNT=@R_AMOUNT
SET @BALANCE_AMOUNT = @BALANCE_AMOUNT+@DUMMY_BALANCE
END
---end
INSERT INTO #TEMPOVERDUEBALANCE VALUES(@COMPANY_ID,
@DEPARTMENT_ID,
@FINANCIAL_ID,
@TRAN_ID,
@TRAN_NO,
@DUE_DATE,
@R_AMOUNT,
@SETLD_AMOUNT,
@PAID_AMOUNT,
@BALANCE_AMOUNT,
@CUST_ID,
@AGREEMENT_ID,
@AGREEMENT_NO,
@TRANTYPE,
@DUMMY_BALANCE,
@CUST_NAME)
set @ft=@CUST_ID---@TRAN_ID
FETCH NEXT FROM cur_HPOVERDUEBALANCE INTO @COMPANY_ID,
@DEPARTMENT_ID,
@FINANCIAL_ID,
@TRAN_ID,
@TRAN_NO,
@DUE_DATE,
@R_AMOUNT,
@SETLD_AMOUNT,
@CUST_ID,
@AGREEMENT_ID,
@AGREEMENT_NO,
@TRANTYPE,
@CUST_NAME
set @lt=@CUST_ID---@TRAN_ID
if @ft<>@lt
begin
set @BALANCE_AMOUNT= 0
end
END
CLOSE cur_HPOVERDUEBALANCE
DEALLOCATE cur_HPOVERDUEBALANCE
SELECT * FROM #TEMPOVERDUEBALANCE
ORDER BY DUE_DATE' 
END
GO
/****** Object:  View [dbo].[gmlevelone]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelone]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gmlevelone    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.gmlevelone    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.gmlevelone    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.gmlevelone    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.gmlevelone    Script Date: 17/11/2001 9:21:13 PM ******/
/****** Object:  View dbo.gmlevelone    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.gmlevelone    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[gmlevelone] as
select gm.groupid, gm.parentgroupid, gmg.levelgm + 1 levelgm from agroupmaster gm, gmwithlevel gmg
where gm.parentgroupid = gmg.groupid'
GO
/****** Object:  UserDefinedFunction [dbo].[GenerateNextTransactionNo]    Script Date: 10/06/2012 14:17: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].[GenerateNextTransactionNo]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--================================================================
--Created By : MANUNADH.U On 09-04-2010
--================================================================
CREATE FUNCTION [dbo].[GenerateNextTransactionNo]
(
	@InterfaceId int,
	@FinancialYearId int,
	@CompanyId int
)
RETURNS varchar(50)
AS
BEGIN
	declare @shopId as int
	declare @TransactionNo as varchar(50)
	declare @Prefix as varchar(50)
	select @shopId=shopId from crmSettings
	select @prefix=Prefix from APREFIX where shopid = @shopId and InterfaceID=@InterfaceId and Financialid=@FinancialYearId and CompanyID=@CompanyId
	if(@InterfaceId=6108)			--==> For CRM-QUOTATION
	begin
		select @TransactionNo=
		case count(*)
				when 0 then @Prefix+''1''
				ELSE @Prefix+cast(max(cast(right(QuotationNo,(len(QuotationNo)-len(@Prefix)))as int))+1 as varchar(50))
		end
		from  [dbo].[crmquotation]
		where QuotationNo like @prefix+''%'' and [FinancialYearId]=@FinancialYearId and [CompanyId]=@CompanyId		
	end
	return 	@TransactionNo
END
----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwinterdepsales]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinterdepsales]'))
EXEC dbo.sp_executesql @statement = N'
/*
Last Modified By : Shine Das
Joined Department id with tohDepartmentID from mesTransferOutHeader
Reason : it was dislpaying requested shops currency symbol
On: 29-06-2010
-- Modified by 	- Santhosh M
--Added tohcancelled on 30/09/2003	
--Added TOHtoShopid on 03/10/2003	
*/
CREATE  view  [dbo].[vwinterdepsales] as
select TOHid,TOHno,TOHShopid,TOHdate,TOHrequestid ,TODitemid,TODissuedGoodQty,
TODcostprice,todSellingPrice,UnitCode,u.unitid,vw.itemdescription,
a.itemcode,TOHremarks,unitname,tohexchangerates,tohdepexrate, case when TOHCancelled =0 then TOHCancelledRemarks else '''' end Remark,
s.shopName,isnull(s.Address,'''') Address,c.Symbol,TOHCancelled,TOHtoShopid
from mesTransferOutHeader left outer join aShops s on s.ShopID=TOHtoShopid
--left outer join adepartmentmaster dep on dep.companyid=s.companyid and  dep.DepartmentID=s.DepartmentID
left outer join adepartmentmaster dep on dep.companyid=s.companyid and  dep.DepartmentID=tohDepartmentID
left outer join acurrencymaster c on c.CurrencyID=dep.depcurrencyid, mesTransferOutDetail d,aitem a,
vwitemdescription vw,aunit u where TOHShopid= d.TODshopid and
TOHtoShopid=d.TODtoShopid and TOHid=d.TODid and d.TODitemid=a.itemid
and a.itemid=vw.itemid and u.unitid=a.unitsid and tohType=''IS'''
GO
/****** Object:  View [dbo].[vwinterdeppurchase]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinterdeppurchase]'))
EXEC dbo.sp_executesql @statement = N'
/*
Last Modified By : Shine Das
Joined Department id with tohDepartmentID from mesTransferOutHeader
Reason : it was dislpaying requested shops currency symbol
On: 29-06-2010
--Last modified by		:Santhosh M
--Added TIHCancel on30/09/2003
*/
CREATE  view [dbo].[vwinterdeppurchase] as
select h.TIHID,h.TIHNO,h.TIHShopid,h.TIHDate,d.TIDrecievedgoodqty,d.TIDCostprice,
d.TIDSellingPrice,case when h.TIHcancel=0 then h.TIHcancelledremarks else '''' end remarks,
s.shopname,isnull(address,'''') address,UnitCode,u.unitid,vw.itemdescription,
a.itemcode,unitname,c.Symbol,h.TIHfromshopID,h.TIHcancel from LOstransferinheader h
left outer join ashops s on h.TIHfromshopID=s.shopid
left outer join adepartmentmaster dep on dep.companyid=s.companyid
--left outer join adepartmentmaster dep on dep.companyid=tihDepartmentID
--and  dep.DepartmentID=s.DepartmentID left outer join acurrencymaster c
and  dep.DepartmentID=tihDepartmentID left outer join acurrencymaster c
on c.CurrencyID=dep.depcurrencyid,LOstransferindetail d,aitem a,
vwitemdescription vw,aunit u where TIHShopid= d.TIDshopid and
h.TIHID=d.TIDID and d.TIDitemID=a.itemid
and a.itemid=vw.itemid and u.unitid=a.unitsid and TIHType=''IP'''
GO
/****** Object:  StoredProcedure [dbo].[spConvertequiamounttemp]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertequiamounttemp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spConvertequiamounttemp] @intfromid as int, @strfromtype as char(1), @inttoid as int,
	@strtotype as char(1), @strexrates as varchar(250), @numAmount as numeric(18,4),
	@numequiamount as numeric(18,2) = 1 output, @strSelectType as char(1) = ''S'' as
begin
	set nocount on
	declare @intcurid as int,
		@numfromer as numeric(18,7),
		@numtoer as numeric(18,7)
	if @strfromtype =''c''
		select @intcurid = currencyid from acustomermaster where customerid = @intfromid
	if @strfromtype =''d''
		select @intcurid = depcurrencyid from adepartmentmaster where departmentid = @intfromid
	if @strfromtype =''v''
		select @intcurid = currencyid from avendormaster where vendorid = @intfromid
	if @strfromtype =''a''
		select @intcurid = currencyid from aaccountmaster where accountid = @intfromid
	if @strfromtype =''m''
		select @intcurid = @intfromid
	exec spReturnExrate @intcurid, @strexrates, @numfromer output
	if @strtotype =''c''
		select @intcurid = currencyid from acustomermaster where customerid = @inttoid
	if @strtotype =''d''
		select @intcurid = depcurrencyid from adepartmentmaster where departmentid = @inttoid
	if @strtotype =''v''
		select @intcurid = currencyid from avendormaster where vendorid = @inttoid
	if @strtotype =''a''
		select @intcurid = currencyid from aaccountmaster where accountid = @inttoid
	if @strtotype =''m''
		select @intcurid = @inttoid
	exec spReturnExrate @intcurid, @strexrates, @numtoer output
	exec spconvertcurrency @numfromer, @numtoer, @numamount, @numequiamount output
	if @strSelectType = ''S''
	begin
		set @numequiamount = @numequiamount
print @numequiamount
end
	set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwHPFeePaymentVoucherdetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentVoucherdetails]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by            Prasanth Joseph
Created For           To HP FeePaymentRepaort
Created on            23-01-2007
Modified on
Modified by
*/
CREATE view [dbo].[vwHPFeePaymentVoucherdetails] as
select hpdcompanyid, hpdpaymentid, a.accountdesc,pdd.hpdExRate, pdd.hpdamount,hf.Feename,HPI.IRFrameNo from
aaccountmaster a, ahpfeePaymentDetail pdd,aFeemaster hf,losHPItemREgistrationDetails HPI
where a.companyid = pdd.hpdcompanyid and a.accountid = pdd.hpdDebitaccountid and hf.feeid=pdd.HPFeeID
and HPI.IRRegistrationID=pdd.HPDRegID'
GO
/****** Object:  View [dbo].[vwHPFeePaymentCheckList]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPFeePaymentCheckList]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by            Prasanth Joseph
Created For           To HP FeePaymentRepaort
Created on            23-01-2007
Modified on
Modified by
*/
CREATE VIEW [dbo].[vwHPFeePaymentCheckList] AS
select ph.hphCompanyId, ph.hphPaymentID, hphPaymentNo, hphPaymentDate, hphpayee,
''HPFP''  as caption, ''N/A''  as custorven,
bacc.accountdesc,hphremarks, hphposted, hphcancel, hphamount,
hphreferenceno as bankrefno,
hphexrate,ph.hphDepExRate,dm.departmentname,ph.hphdepartmentid, hphUpdateTime
from ahpFeePaymentHeader  ph , aAccountMaster bacc, adepartmentmaster dm
where ph.hphCompanyId = bacc.CompanyId
and ph.hphAccountid = bacc.accountid
and ph.hphCompanyId = dm.CompanyId
and ph.hphdepartmentid = dm.departmentid'
GO
/****** Object:  View [dbo].[vwHpItemRegistrationDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpItemRegistrationDetails]'))
EXEC dbo.sp_executesql @statement = N'
--*********************************************************************************
-- Created by  :  Shinu
-- Created on  : 28/08/2007
-- Purpose     : To Populate Hire Purchase Item Registration Details In Master Grid
--*********************************************************************************
-- Modified by :
-- Modified on :
-- Purpose     :
--*********************************************************************************
CREATE View [dbo].[vwHpItemRegistrationDetails] AS
select IRCompanyId,IRFinancialID,IRRegistrationID,IRRegistrationNo,IRShopID,IRRegistrationDate,IRShipment,IRMode,ac_1.ColorName,IRItemID,Itemdescription,
isnull(ac_2.ColorName,'''')SoldColor,IRFrameNo,IrEngineNo,IRModelNo,IRCase,IRLocation,isnull(IRRegNo,'''')RegNo,
IRCustomerID,isnull(CustomerName,'''')CustomerName,IRRoadWorthiness,IRProduction,isnull(IRSold,'''')Status,
isnull(IRRemarks,'''')Remarks,case IRForSales when 1 then ''Ready'' when 0 then ''Not Ready'' end  ForSales,
case IRCancel when 1 then ''Yes'' when 0 then ''No'' end  Cancel,IRUSerName,IRUpdateUser,IRUpdateTime
from loshpitemregistrationdetails
inner join aitem on itemID=IRItemID
inner join acolor ac_1 on ac_1.colorID=IRColorID
left outer join acolor ac_2 on ac_2.colorID=IRSoldColor
left outer join aCustomerMaster on CustomerID=IRCustomerID'
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetExchangeRates]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetExchangeRates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------
--CREATED BY : NIDHEESH PV
--CREATED ON :  09/04/2011
--COMMENTS : TO GET EXCHNAGE RATES OF ALL CURRENCIES
---------------------------------------------------------------
CREATE PROC [dbo].[spMagnolia_GetExchangeRates](
@IntCompanyId AS INT,
@strExchangeRates AS VARCHAR(8000)='''' OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
WITH cteExRate(ID,CURR,EXRATE)
AS
(
SELECT 1,CAST('''' AS VARCHAR(8000)),CAST('''' AS VARCHAR(8000))
UNION ALL
SELECT cm.CurrencyID+1,
CAST(CAST(cte.CURR AS VARCHAR(8000))+ CAST(cm.CurrencyID AS VARCHAR(8000))+ '':'' AS VARCHAR(8000)),
CAST(CAST(cte.EXRATE AS VARCHAR(8000))+ CAST(EX.SellingRate AS VARCHAR(8000))+ '':'' AS VARCHAR(8000))
FROM aCurrencyMaster cm
INNER JOIN ExchangeRateDetail ex ON cm.CurrencyID=ex.CurrencyID AND cm.CompanyID=ex.CompanyID
INNER JOIN cteExRate cte ON cm.CurrencyID=cte.ID
WHERE cm.CompanyID=@IntCompanyId
)
SELECT TOP 1 @strExchangeRates=CURR+''-''+EXRATE FROM cteExRate AS EXCHANGERATES ORDER BY ID DESC
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSelectAllSubDepartments]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSelectAllSubDepartments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by    : Kishore
-- Created on    : 10/12/2003
-- Comments      : This sp returns given department id and all sub department ids
--                 of the given department id
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE procEDURE [dbo].[spSelectAllSubDepartments] (@intDepartmentId as int,
@intCompanyId as int) AS
Begin
DECLARE @Count as int
DECLARE @TempDepId as int
SET NOCOUNT ON
-- create temporary table
-- status field holds whether the department is processed
-- or not. i.e. sub depts are taken or not
CREATE TABLE #SubDepts
(DeptId int PRIMARY KEY,
Status bit)
-- insert the immediate sub departments
INSERT INTO #SubDepts
SELECT DepartmentId, 1
FROM aDepartmentMaster
WHERE ParentDepId = @intDepartmentId
AND CompanyId = @intCompanyId
-- get the count of unprocessed departments
SELECT @Count = COUNT(*) FROM #SubDepts
WHERE Status <> 0
-- if unprocessed depts exist
WHILE (@Count <> 0)
Begin
-- get a department id from SubDepts where status is not zero
SELECT TOP 1 @TempDepId = DeptId
FROM #SubDepts
WHERE Status <> 0
-- then insert sub departments of that dep id
INSERT INTO #SubDepts
SELECT DepartmentId, 1
FROM aDepartmentMaster
WHERE ParentDepId = @TempDepId
AND CompanyId = @intCompanyId
-- update the status of current dep id, as its sub departments are inserted
UPDATE #SubDepts
SET Status = 0
WHERE DeptId = @TempDepId
-- get the count of unprocessed departments
SELECT @Count = COUNT(*) FROM #SubDepts
WHERE Status <> 0
End
-- now select (return) all sub depts
SELECT @intDepartmentId SubDepartments
UNION ALL
SELECT DeptId FROM #SubDepts
-- delete the temporary table
DROP TABLE #SubDepts
SET NOCOUNT OFF
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionTrans]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionTrans]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------
--Created on 		: 22/05/2003
--Created by		: R Harikrishnan
--Comments		: For Sales commission Report
-----------------------------------------------------------------
--Last Modified on 	: 13/06/2003
--Last Modified by	: R Harikrishnan
--Comments		: Added some more fields
-----------------------------------------------------------------
CREATE Procedure [dbo].[spSalesCommissionTrans]
	@intCompanyID 		as int,
	@intCommissionID 	as int,
	@intDepartmentID 	as int
as
declare @strSql as nVarchar(2000),@strDepCurSymbol as varchar(25)
select
	@strDepCurSymbol=cm.symbol
from
	aDepartmentMaster dm, aCurrencyMaster Cm
where
	dm.DepCurrencyID=cm.CurrencyID and dm.companyID=cm.companyID and
	dm.DepartmentID=@intDepartmentID
set @strSql = N''select
	sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBy,
	sch.schFromDate, sch.schToDate, sch.schTargetAmount, sch.schTargetType,
	sch.SchRemarks,	scd.scdCommisionAmount,ih.invoicedate,ih.invoiceamount,ih.customername,
	ih.InvoiceNo,ih.spername SalesPerson,'''''' + @strDepCurSymbol
Set @strSql=@strSql + N'''''' Symbol,ih.settleddate,ih.SettleDays,ih.customerType,ih.DutyAmt,
	ih.ReceiptNo,scd.scdEligiblePer,scd.scdCommissionPer, sch.schCancelled from
	HQSalesCommisionHeader sch,HQSalesCommisionDetail scd,vwcreditinvoicesettlecommision ih
where
	sch.schCommisionID=scd.scdCommisionID and sch.schcompanyid=scd.scdcompanyid and
	sch.schdepartmentid=ih.departmentid and scd.scdcompanyid=ih.companyid and
	scd.scdShopID=ih.shopid and scd.scdtransactionID=ih.invoiceid and
	scd.scdInterfaceID=ih.interfaceID and
	sch.schCommisionid='' + convert(varchar(10),@intCommissionID) +
	N'' and sch.schCompanyID='' + convert(varchar(10),@intCompanyID)
exec sp_ExecuteSql @strSql' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionPayment]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionPayment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Created  on  : 25/05/2003
-- Created  by : R Harikrishnan
-- Comments : For Sales Commission Payment Report
------------------------------------------------------------------------
-- Modified on  : 01/09/2003
-- Modified by  : Kishore
-- Comments     : Added UpdateTime, schCancelled fields
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--exec spSalesCommissionPayment 1,0,''20100101'',''20101001'',0,''N''
------------------------------------------------------------------------
--Modified By : VinothMurugan V.
--Date		  : 27/11/2010
--RefNo: 01
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSalesCommissionPayment]
@intCompanyID  as int,
@intDepartmentID  as int,
@strFromDate   as varchar(8),
@strToDate  as varchar(8),
@intSalesPersonID  as int=0,
@strType  as char(1)--if @strType=''O'' then means outstanding
AS
begin
--set @intCompanyID=1
--set @intShopID =1
--set @strFromDate =''20030101''
--set @strToDate=''20030530''
--set @intCustomerID=0
--set @intSalesPersonID=0
declare @strSql as nVarchar(4000),@strDepCurrSymbol as varchar(25)
set @strDepCurrSymbol ='''' --RefNo: 01
select
@strDepCurrSymbol=cm.Symbol
from
aCurrencyMaster cm , aDepartmentMaster dm
where
cm.CompanyID=dm.companyID and cm.CurrenCyID=dm.DepCurrencyID and
cm.CompanyID =@intCompanyID and dm.DepartmentID=@intDepartmentID
set @strSql =  N''select
sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBY,
sch.schFromDate,sch.schTodate, sm.sperName SalesPerson,
sum(scd.scdCommisionAmount) scdCommisionAmount,
avg(isnull(pay.DeptEquiAmt,0)) DeptEquiAmt,'''''' + @strDepCurrSymbol +
N'''''' Symbol, Pay.UpdateTime, Min(Cast(sch.schCancelled AS int)) schCancelled
From HQSalesCommisionHeader sch
Left Outer Join (select
scp.companyID, scp.SalesCommID, sum(scp.DeptEquiAmt) DeptEquiAmt,
ph.UpdateTime
from
aHQPaymentVoucherSCDetails scp, aHQPaymentVoucherHeader ph
where
scp.PaymentID = ph.phPaymentID and scp.companyID = ph.phCompanyID and
ph.phCancelled=0
group by
scp.companyID, scp.SalesCommID, ph.UpdateTime) Pay
on sch.schCompanyID = pay.CompanyID and sch.schCommisionID = pay.SalesCommID ,
HQSalesCommisionDetail scd,aSalesPersonMaster sm
where
sch.schCompanyID = scd.scdCompanyID and sch.schCommisionID = scd.scdCommisionID and
sch.schCompanyID = sm.companyID and sch.schSalesPersonID = sm.sperID and
sch.schCancelled=0 and sch.schCompanyID ='' + convert(varchar(10),@intCompanyID)
if @strType<>''O'' --Not outsatnding
set @strSql = @strSql + N'' and sch.schSalesCommisionDate between '''' '' + @strFromDate
+ '''''' and '''''' + @strToDate + ''''''''
if @intSalesPersonID>0
set @strSql = @strSql + N'' and sch.schSalesPersonID=''
+ convert(varchar(10),@intSalesPersonID)
if @intDepartmentID>0
set @strSql = @strSql + N'' and sch.schDepartmentID=''
+ convert(varchar(10),@intDepartmentID)
set @strSql = @strSQl + N'' group by
sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBY,
sch.schFromDate, sch.schTodate, sm.SperName, Pay.UpdateTime ''
print @strSql
if @strType=''O'' --All outsatnding
set @strSql = @strSql + N'' Having sum(scd.scdCommisionAmount) >
avg(isnull(pay.DeptEquiAmt,0))''
--print @strSql
exec sp_executeSql @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionEligiblity]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionEligiblity]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--spSalesCommissionEligiblity 1,0,0,''20010101'',''20110101''
--Modified By : Hariharan
--MOdified Date : 05/05/2004
--Comments : For Sales Commission Eligibility Report
--  : Included Margin Percentage
-----------------------------------------------------
--Modified By : Nidheesh P V
--MOdified Date : 31/05/2011
--Reason   : While loading the report departmentwise it was wrong.
--Comments : Added the condition of Companywise(@intDepartmentID=0)
--Modified Area : SalesCommissionEligiblity report
--Ref         : Ref:-1
-----------------------------------------------------
CREATE procedure [dbo].[spSalesCommissionEligiblity]
@intCompanyID   as int,
@intDepartmentID  as int,
@intSalesPersonID as int=0,
@strFromDate  varchar(8),
@strToDate  varchar(8)
as
declare @strSql as nVarchar(2500), @strDepCurSymbol as varchar(25)
begin
set nocount on
select
@strDepCurSymbol=cm.symbol
from
aDepartmentMaster dm, aCurrencyMaster Cm
where
dm.DepCurrencyID=cm.CurrencyID and dm.companyID=cm.companyID and
dm.DepartmentID=@intDepartmentID
set @strSql= N''Select
a.invoiceno,a.InvoiceDate,a.customername,a.invoiceamount,a.rebateamount,a.settledamount,
a.shopid,a.invoiceid,a.InterfaceID,a.DutyAmt,a.ReceiptNo,a.SperName SalesPerson, b.scdEligiblePer,
b.scdCommissionPer,isnull(b.scdCommisionAmount,0) scdCommisionAmount,b.scdtransactionID,
a.SettleDays,case when a.CustomerType=''''P'''' then isnull(spd.phpercentage,0)
else isnull(spd.percentage,0) end percentage,'''' + @strDepCurSymbol + '''' Symbol, a.SalesMarginAmt
From
vwcreditinvoicesettlecommision a left outer join
(select
sch.schdepartmentid,scd.scdcompanyid,scd.scdShopID,scd.scdtransactionID,
scd.scdInterfaceID ,scd.scdEligiblePer,scd.scdCommissionPer,
sum(scd.scdCommisionAmount)  scdCommisionAmount
From
HQSalesCommisionHeader sch,HQSalesCommisionDetail scd
Where
sch.schCommisionid = scd.scdCommisionID and sch.SchCancelled=0 And
sch.schcompanyid = scd.scdcompanyid
Group By
sch.schdepartmentid,scd.scdCommisionID,scd.scdcompanyid,scd.scdShopID,
scd.scdtransactionID,scd.scdInterfaceID,scd.scdEligiblePer,
scd.scdCommissionPer ) b
on a.departmentid=b.schdepartmentid and a.companyid=b.scdcompanyid and
a.shopid=b.scdShopID and a.invoiceid=b.scdtransactionID and
a.interfaceID=b.scdInterfaceID
Left outer join aSalesPersonCommisionDetail spd
on a.ihsalespersonid = spd.SalesPersonID and a.SettleDays
between spd.FromRange and spd.ToRange
Where round(a.invoiceamount-a.settledamount,0)= 0 and isnull(b.scdtransactionID,0)=0 and
a.companyid='' + convert(varchar(10),@intCompanyID) +
N'' and ( a.departmentid='' + convert(varchar(10),@intDepartmentID) +      --Ref:-1
N'' or '' + convert(varchar(10),@intDepartmentID) +
N''=0 ) and a.settleddate between '''''' + @strFromDate + N'''''' and '''''' +
@strTodate + N''''''''
if @intSalesPersonID>0
begin
set @strSql=@strSql + N'' and a.ihsalespersonid='' + convert(varchar(10),@intSalesPersonID)
set @strSql=@strSql + N'' order by
a.invoicedate,a.customername,a.invoiceid''
end
exec sp_executesql @strSql
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionDetail]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommissionDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
/*
--Created on 	: 22/05/2003
--Created by	: R Harikrishnan
--Comments	: For Sales commission Report
/*
Altered By: SHINE DAS
On			: 08/07/2011
When added to source safe sme unwanted quots came with. So corrected it
*/
*/
CREATE Procedure [dbo].[spSalesCommissionDetail]
	@intCompanyID 		as int,
	@intDepartmentID 	as int,
	@intSalesPersonID	as int=0,
	@strFromDate		varchar(8),
	@strToDate		varchar(8)
as
declare @strSql as nVarchar(2000),@strDepCurSymbol as varchar(25)
BEGIN
select
	@strDepCurSymbol=cm.symbol
from
	aDepartmentMaster dm, aCurrencyMaster Cm
where
	dm.DepCurrencyID=cm.CurrencyID and dm.companyID=cm.companyID and
	dm.DepartmentID=@intDepartmentID
set @strSql = N''select
	sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBy,
	sch.schFromDate,  sch.schTargetAmount,
	sch.schTargetType,
	scd.scdCommisionAmount,ih.invoicedate,ih.invoiceamount,ih.customername,
	ih.InvoiceNo,ih.spername SalesPerson,'''''' + @strDepCurSymbol
Set @strSql=@strSql + N'''''' Symbol from
	HQSalesCommisionHeader sch,HQSalesCommisionDetail scd,vwcreditinvoicesettlecommision ih
where
	sch.schCommisionID=scd.scdCommisionID and sch.schcompanyid=scd.scdcompanyid and
	sch.schdepartmentid=ih.departmentid and scd.scdcompanyid=ih.companyid and
	scd.scdShopID=ih.shopid and scd.scdtransactionID=ih.invoiceid and
	scd.scdInterfaceID=ih.interfaceID and sch.schCancelled=0 and
	sch.schdepartmentid='' + convert(varchar(10),@intDepartmentID) +
	N'' and sch.schCompanyID='' + convert(varchar(10),@intCompanyID) +
	N'' and ih.InvoiceDate between '''''' + @strFromDate + N'''''' and '''''' + @strToDate + N''''''''
if @intSalesPersonID>0
	set @strSql=@strSql + N'' and sch.schsalespersonid='' + convert(varchar(10),@intSalesPersonID)
set @strSql=@strSql + N'' order by ih.invoicedate,ih.customername,ih.invoiceid''
exec sp_ExecuteSql @strSql
END
--print @strSql
---EXEC spSalesCommissionDetail 1,1,0,''20100101'',''20101231''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommission]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesCommission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--spSalesCommission 1,10,0,''20030101'',''20031201''
-----------------------------------------------------------------
--Created on  : 22/05/2003
--Created by : R Harikrishnan
--Comments : For Sales commission Report
-----------------------------------------------------------------
--Modified By : VinothMurugan V
--Date    : 27/11/2010
--RefNo:01
----------------------------------------------------------------
--Modified By : Nidheesh P V
--Date    : 31/05/2011
--Reason   : While taking reprot an error is coming.
--Comments : Added the date checking correctly
--Modified Area : SalesCommission report
--Ref         : Ref:-1
----------------------------------------------------------------
CREATE Procedure [dbo].[spSalesCommission]
@intCompanyID   as int,
@intDepartmentID  as int,
@intSalesPersonID as int=0,
@strFromDate  varchar(8),
@strToDate  varchar(8)
as
declare @strSql as nVarchar(2000),@strDepCurSymbol as varchar(25)
begin
set nocount on
set @strDepCurSymbol =''''  --RefNo:01
select
@strDepCurSymbol=cm.symbol
from
aDepartmentMaster dm, aCurrencyMaster Cm
where
dm.DepCurrencyID=cm.CurrencyID and dm.companyID=cm.companyID and
dm.DepartmentID=@intDepartmentID
set @strSql = N''select
sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBy,
sch.schFromDate, sch.schToDate,
sch.schTargetAmount, sch.schTargetType,
sum(scd.scdCommisionAmount) scdCommisionAmount,sm.SperName as SalesPerson,'''' +
@strDepCurSymbol  + '''' symbol,Avg(isnull(scd.scdEligiblePer,0)) scdEligiblePer,
Avg(isnull(scd.scdCommissionPer,0)) scdCommissionPer from
HQSalesCommisionHeader sch,HQSalesCommisionDetail scd,aSalesPersonMaster sm
where
sch.schCommisionID=scd.scdCommisionID and sch.schcompanyid=scd.scdcompanyid and
sch.schSalesPersonID=sm.Sperid and sch.schCompanyID = sm.CompanyID and
sch.schCancelled=0 and sch.schdepartmentid='' + convert(varchar(10),@intDepartmentID) +
N'' and sch.schCompanyID='' + convert(varchar(10),@intCompanyID) +
N'' and sch.schSalesCommisionDate between '''''' + @strFromDate + N'''''' and '''''' + @strToDate + N''''''''
if @intSalesPersonID>0
begin
set @strSql=@strSql + N'' and sch.schsalespersonid='' + convert(varchar(10),@intSalesPersonID)
end
set @strSql=@strSql + N'' Group by sch.schSalesCommisionNo, sch.schSalesCommisionDate, sch.schApprovedBy,
sch.schFromDate, sch.schToDate,  sch.schTargetAmount,
sch.schTargetType, sm.SperName''
--print @strSql
exec sp_ExecuteSql @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesPromotionDetails]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesPromotionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spSalesPromotionDetails 1,0,''20010101'',''20100530'',0,''B''
------------------------------------------------------------------------
--Created on  : 25/05/2003
--Created by : R Harikrishnan
--Comments : For Sales Commission Payment Report
------------------------------------------------------------------------
--Modified on  : 31/05/2011
--Modified by : Nidheesh P V
--Reason   : To avoid error message while loading the report
--Comments : Added the BEGIN-END CONDITION correctly
--Modified Area : SalesPromotion Details report
--Ref         : Ref:-1
------------------------------------------------------------------------
CREATE procedure [dbo].[spSalesPromotionDetails]
@intCompanyID  as int,
@intDepartmentID  as int,
@strFromDate   as varchar(8),
@strToDate  as varchar(8),
@intCustomerID   as int=0,
@strType  as char(1)--if @strType=''O'' then means outstanding
as
declare @strSql as nVarchar(4000),@strDepCurrSymbol as varchar(25)
begin
set nocount on
--set @intCompanyID=1
--set @intShopID =1
--set @strFromDate =''20030101''
--set @strToDate=''20030530''
--set @intCustomerID=0
--set @intSalesPersonID=0
select
@strDepCurrSymbol=cm.Symbol
from
aCurrencyMaster cm , aDepartmentMaster dm
where
cm.CompanyID=dm.companyID and cm.CurrenCyID=dm.DepCurrencyID and
cm.CompanyID =@intCompanyID and dm.DepartmentID=@intDepartmentID
set @strSql = N''select
sph.sphPromotionNo,sph.sphPromotionDate,sph.sphFromDate,sph.sphToDate,
sph.sphApprovedBy,sph.sphTotSalesAmt,sph.sphTotprofitAmt,
spd.spdCustomerID,spd.spdSalesAmt,spd.spdSalesPer,spd.spdProfitAmt,
spd.spdProfitPer,spd.spdPromotionAmt,spd.spdToBePaid,sp.phPaymentDate,
1 depexrate,sp.DeptEQuiAmt,cm.CustomerName,'''' + @strDepCurrSymbol + '''' Symbol
from
HQSalesPromotionHeader sph, HQSalesPromotionDetail spd
Left outer join
(select
Max(ph.phPaymentDate) phPaymentDate,spp.CompanyID,spp.PromotionID,
spp.PromotionDetailID, sum(DeptEquiAmt) DeptEquiAmt
from
aHQPaymentVoucherHeader ph, aHQPaymentVoucherSPDetails spp
where
ph.phPaymentID=spp.PaymentID and ph.phCompanyID=spp.CompanyID and
ph.phCancelled=0
group by
spp.CompanyID,spp.PromotionID,spp.PromotionDetailID) SP
on spd.spdCompanyID=sp.CompanyID and spd.spdPromotionID = sp.PromotionID and
spd.spdDetailID = sp.PromotionDetailID, aCustomerMaster cm
where
sph.sphCompanyID=spd.spdCompanyID and sph.sphPromotionID=spd.spdPromotionID and
spd.spdCustomerID=cm.CustomerID and sph.sphcancelled=0 and
sph.sphCompanyID='' + convert(varchar(10),@intCompanyID) +
N'' and spd.spdToBePaid=1''    -- Ref:-1
if @strType<>''O'' --Not outsatnding
begin
set @strSql = @strSql + N'' and (sph.sphFromDate between '''''' + @strFromDate
+ '''''' and '''''' + @strToDate + '''''' or sph.sphToDate between '''''' + @strFromDate
+ '''''' and '''''' + @strToDate + '''''')''
end
if @intCustomerID>0
begin
set @strSql = @strSql + N'' and spd.spdCustomerID=''
+ convert(varchar(10),@intCustomerID)
end
if @intDepartmentID>0
begin
set @strSql = @strSql + N'' and sph.sphDepartmentID=''
+ convert(varchar(10),@intDepartmentID)
end
set @strSql=@strSQl + N'' union all select
sph.sphPromotionNo,sph.sphPromotionDate,sph.sphFromDate,sph.sphToDate,
sph.sphApprovedBy,sph.sphTotSalesAmt,sph.sphTotprofitAmt,
spd.spdCustomerID,spd.spdSalesAmt,spd.spdSalesPer,spd.spdProfitAmt,
spd.spdProfitPer,spd.spdPromotionAmt,spd.spdToBePaid,dc.DCNDate,
dc.dcndepexrate,dc.DCNAmount,cm.CustomerName,''''  + @strDepCurrSymbol + '''' Symbol
from
HQSalesPromotionHeader sph, HQSalesPromotionDetail spd
Left outer join
(select
dcn.DCNDate,dcn.dcnCompanyID,dcn.dcnSalesPromotionID,
dcn.dcnSalesPromotionDetID, dcn.DCNAmount,dcn.dcndepexrate
from
DebitCreditNote dcn
where
dcn.dcnCompanyID='' + convert(varchar(10),@intCompanyID) + N''
and dcn.dcnCancelled=0 and dcn.dcnSalesPromotionID is not null) dc
on spd.spdCompanyID=dc.dcnCompanyID and spd.spdPromotionID = dc.dcnSalesPromotionID and
spd.spdDetailID = dc.dcnSalesPromotionDetID, aCustomerMaster cm
where
sph.sphCompanyID=spd.spdCompanyID and sph.sphPromotionID=spd.spdPromotionID and
spd.spdCustomerID=cm.CustomerID and sph.sphcancelled=0 and
sph.sphCompanyID=''+ convert(varchar(10),@intCompanyID) + N'' and
spd.spdToBePaid=0''
if @strType<>''O'' --Not outsatnding
begin   --Ref:-1
set @strSql = @strSql + N'' and (sph.sphFromDate between '''''' + @strFromDate
+ '''''' and '''''' + @strToDate + '''''' or sph.sphToDate between '''''' + @strFromDate
+ '''''' and '''''' + @strToDate + '''''')''
end  --Ref:-1
if @intCustomerID>0
begin  --Ref:-1
set @strSql = @strSql + N'' and spd.spdCustomerID=''
+ convert(varchar(10),@intCustomerID)
end  --Ref:-1
if @intDepartmentID>0
begin  --Ref:-1
set @strSql = @strSql + N'' and sph.sphDepartmentID=''
+ convert(varchar(10),@intDepartmentID)
end  --Ref:-1
--print @strSql
exec sp_executeSql @strSql
end' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fnGetExchangeRates]    Script Date: 10/06/2012 14:17: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].[fnGetExchangeRates]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--DECLARE @STAR AS VARCHAR(8000)
--EXEC @STAR=DBO.fnGetExchangeRates 1
--SELECT @STAR
--EXEC DBO.fnGetExchangeRates 1
---------------------------------------------------------------
--CREATED BY : NIDHEESH PV
--CREATED ON :  09/04/2011
--COMMENTS : TO GET EXCHNAGE RATES OF ALL CURRENCIES
---------------------------------------------------------------
CREATE FUNCTION [dbo].[fnGetExchangeRates](
@IntCompanyId AS INT
--@intCurRid as int=0,
--@numExrate as numeric(18,2)=0.00
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @strExchangeRates AS VARCHAR(8000)
WITH CTECURREXRATES(ID,CURR,EXRATE)
AS
(
SELECT 1,CAST('''' AS VARCHAR(8000)),CAST('''' AS VARCHAR(8000))
UNION ALL
SELECT cm.CurrencyID+1,
CAST(CAST(cte.CURR as varchar(8000))+ CAST(cm.CurrencyID as varchar(8000))+ '':'' AS VARCHAR(8000)),
CAST(CAST(cte.EXRATE as varchar(8000))+ CAST(EX.SellingRate as varchar(8000))+ '':'' AS VARCHAR(8000))
FROM aCurrencyMaster cm
INNER JOIN ExchangeRateDetail ex on cm.CurrencyID=ex.CurrencyID and cm.CompanyID=ex.CompanyID
INNER JOIN CTECURREXRATES cte ON cm.CurrencyID=cte.ID
WHERE cm.CompanyID=@IntCompanyId
)
SELECT TOP 1 @strExchangeRates=CURR+''-''+EXRATE FROM CTECURREXRATES AS EXCHANGERATES ORDER BY ID DESC
RETURN @strExchangeRates
END' 
END
GO
/****** Object:  View [dbo].[vwhpReceiptDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpReceiptDetails]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwhpReceiptDetails] as
select hprhCompanyID,hprhDepartmentId,HprhReceiptID,HprhReceiptNo,hprhReceiptDate,
hprhRefNo,hprhFinancialID,cu.AccountDesc,c.HPcustName,hprhAmount,
hprhRemarks,hprhCancel,hphPaymentNo,hphPaymentAmount
from aHPReceiptHeader,losHPCustomerDetails c,aAccountMaster cu,aHpPaymentHeader,ahpReceiptDetail
where hprhCustomerID=c.HPCustID and hprhReceiptId=hprdReceiptId
and hprdPaymentId=hphPaymentId'
GO
/****** Object:  View [dbo].[vwHPProcessingDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPProcessingDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- View
---------------
/*
Created by :  Shinu
Created on : 30/05/2008
Modified by : Regin
Modified on : 19-12-2008
Purpose      : To Get the Header and Detail Table of  HPPProcessing
	-- Regin Added hphAmended field
*/
CREATE View [dbo].[vwHPProcessingDetails] As
Select hphCompanyId,hphDepartmentID,DepartmentName,hphProceSsingID,hphProcessingNo,hphProcessingDate, hphInvoiceID,hphFinancialID,
hphCancel,hphCashPrice,hphDownPayment,hphBalance,hphNoOfRentals,hphInterestRate,
hphInstallmentPrice,hphRentalAmount,hpdDetailID,hpdChequeDate,hpdCapital,hpdRental,hpdInterest,
hpdCapitalRepayment,hpdCapitalBalance,hpdBankName,hpdChequeNo,hpdAmount,hpdSettlementAmount,hpdInterestRate, hphAmended
From aHpProcessingHeader
Inner Join  aHpProcessingDetail ON hpdCompanyID=hphCompanyId And hpdDepartmentID=hphDepartmentID
And hpdProcessingID=hphProceSsingID
Left Outer Join aDepartmentMaster On DepartmentID=hphDepartmentID'
GO
/****** Object:  View [dbo].[vwpcpaymentlisting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentlisting]'))
EXEC dbo.sp_executesql @statement = N'
--Created on : 21/12/2007
--Created by : Shinu
--Comments   : For Reports
CREATE view [dbo].[vwpcpaymentlisting] as
select  ph.phcompanyid companyid, ph.phpaymentid paymentid, ph.phpaymentno, ph.phpaymentdate paymentdate,
ph.phPayee Payee,ph.phremarks remarks, ph.phAccountid bankcashid,
ph.phAmount Aamount, ph.phCancel, ph.phDepartmentID, ph.phCancelRemarks, ph.phPosted,
d.DepartmentName, ph.phAmount, c.symbol
from
aHqPettyCashPaymentHeader ph, aaccountmaster acc, aDepartmentMaster d, acurrencymaster c
where
ph.phcompanyid = acc.companyid and ph.phAccountid = acc.accountid and
ph.phDepartmentID = d.DepartmentID and ph.phCompanyID=d.CompanyID and
acc.companyid = c.companyid and acc.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwpcpaymentCLbankwise]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentCLbankwise]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------------------------------
--Created on : 21/12/2007
--Created by : Shinu
--Comments   : For Edit Reports(Petty Cash Payments Reports)
--------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwpcpaymentCLbankwise] as
select phcompanyid companyid, phpaymentid paymentid, phpaymentdate paymentdate, phpaymentno paymentno,
phpayee payee, phAccountid bankcashid, phamount amount, case when phcancel =1
then ''Yes'' else ''No'' end as cancelled, phCancelRemarks cancelledremarks, a.accountdesc, phDepartmentID,
symbol, phremarks from aHqPettyCashPaymentHeader  ph, aaccountmaster a, acurrencymaster c where
ph.phcompanyid = a.companyid and
phAccountid = a.accountid and a.companyid = c.companyid and a.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwPCPaymentCheckList]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPCPaymentCheckList]'))
EXEC dbo.sp_executesql @statement = N'
--Created on : 21/12/2007
--Created by : Shinu
--Comments   : For Edit Reports(Petty Cash Payments Reports)
--------------------------------------------------------------------------------------------------------------------
--modified on : 10/01/2009
--modified by : Yogesh
--Comments    : For Showing preview in petty cash payment interface
--Added fiels : phUserName
--Added tables:acuurencymaster(Symbol)
----------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwPCPaymentCheckList] AS
select ph.phCompanyId, ph.phPaymentID, phPaymentNo, phPaymentDate, phpayee,
''PCP''  as caption, ''N/A''  as custorven,
bacc.accountdesc,phremarks, phposted, phcancel, phamount,
phreferenceno as bankrefno,
phexrate,ph.phDepExRate,dm.departmentname,ph.phdepartmentid, phUpdateTime,case when phUpdateUserName is null then ph.phUserName else phUpdateUserName end Username,c.Symbol
from aHqPettyCashPaymentHeader  ph , aAccountMaster bacc, adepartmentmaster dm ,acurrencymaster c
where ph.phCompanyId = bacc.CompanyId
and ph.phAccountid = bacc.accountid
and ph.phCompanyId = dm.CompanyId
and ph.phdepartmentid = dm.departmentid
and bacc.CurrencyID=c.CurrencyID'
GO
/****** Object:  View [dbo].[vwpcpaymentvoucherdetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentvoucherdetails]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwpcpaymentvoucherdetails] as
select pdcompanyid, pdpaymentid, a.accountdesc,pdd.pdExRate, pdd.pdamount from
aaccountmaster a, aHqPettyCashPaymentDetails pdd
where a.companyid = pdd.pdcompanyid and a.accountid = pdd.pdDebitaccountid'
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetShowDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsGetShowDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[SpLmsGetShowDetails]
@id as int
as
SELECT     dbo.aCustomerMaster.CustomerName, dbo.LMSCardRegistration.RegistrationDate, dbo.LMSCardRegistration.ExpairyDate, dbo.lmsPoint.PointDesc,
dbo.LMSCardRegistration.CardNumber
FROM         dbo.LMSCardRegistration INNER JOIN
dbo.aCustomerMaster ON dbo.LMSCardRegistration.CustmerId = dbo.aCustomerMaster.CustomerID INNER JOIN
dbo.lmsPoint ON dbo.LMSCardRegistration.TypeID = dbo.lmsPoint.PointsID
WHERE     (dbo.LMSCardRegistration.CardRegistrationID = @id)' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpLmsDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by jyothish
CREATE PROCEDURE [dbo].[SpLmsDetails] AS
SELECT     dbo.aCustomerMaster.CustomerName, dbo.lmsPoint.PointDesc, dbo.LMSCardRegistration.CardNumber, CONVERT(varchar(10),
dbo.LMSCardRegistration.RegistrationDate, 101) AS RegistrationDate, CONVERT(varchar(10), dbo.LMSCardRegistration.ExpairyDate, 101)
AS ExpairyDate
FROM         dbo.lmsPoint INNER JOIN
dbo.LMSCardRegistration ON dbo.lmsPoint.CompanyID = dbo.LMSCardRegistration.CompanyID AND
dbo.lmsPoint.PointsID = dbo.LMSCardRegistration.CardRegistrationID INNER JOIN
dbo.aCustomerMaster ON dbo.lmsPoint.CompanyID = dbo.aCustomerMaster.CompanyID AND
dbo.LMSCardRegistration.CustmerId = dbo.aCustomerMaster.CustomerID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSum]    Script Date: 10/06/2012 14:17: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].[spCreditorAgeSum]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spcreditoragesum '''',''20060517'',84,9,0
-- Modified on   : 10/06/2003
-- Modified by          : Kishore
-- Comments             : (comment from v2)
--      giving  sum(a.pbhbillamount) instead of max(a.pbhbillamount)
--      at times when one bill is entered with multiple accounts
--     in detail table
--      Filtering those bills which have the bill amount settled completely
--      given max(pbhbillamount) <> sum(paidamount)
--     as there are some bills which are settled with more amount
--                        (on comparison with v2)
-- altered on   : 24/09/2002, 24/09/2003, 08/12/2004
-- Altered by   : venki, R Harikrishnan , Hariharan
-- comments  : added creditaccid
--    : Added account desc
-- Modified By :shinu
-- Modified ON :18062007
-- Comments : Removed Department Condition Because Bill Entered in One Department Can be settled in
--              another department.so if the condition is there then it will show as unsettled
-------------------------------------------------------------------------------------------------------------------------
-- exec spCreditorAgeSum '''', ''20090101'', '''', 0,0,''''
CREATE PROCEDURE [dbo].[spCreditorAgeSum] ( @dtstartdate varchar(11),@dtbilldate as varchar(11),
@strvendorid varchar(500), @intdepartid int=0,@intageTodate int=0,@intVenGroupid as varchar(500) )
as
set ansi_Warnings off
set nocount on
begin
Create table #tmpBills
(CompanyID int,
shopid int,
DepartmentID int,
billsid int,
pbhVendorID int,
Billsno varchar(50),
pbhremarks varchar(1000),
Referenceno varchar (100),
pbhBilldate datetime,
duedate datetime ,
pbhBillAmount numeric(18,2),
Due varchar(7),
Type varchar(4),
updatetime datetime,
age int  )
Create Table #tmpSettlements
(
companyid int,
departmentid int,
billsid  int,
settleddate datetime,
paidamount  numeric(18,2),
vendorid int,
shopid int,
Type varchar(50))
declare @strquery as nvarchar(4000)
declare @SettleVendId as varchar(1500), @BillVendid as varchar(1500)
SET @SettleVendId = ''''
set @BillVendid = ''''
-----------------------------------------------------------------------  RefNo :1
if @strvendorid = '''' and isnull(@intVenGroupid,0) <> 0
begin
--declare @strvendorid as varchar(1000)
declare @count as int
declare @index as int
create table #temp1 (id int identity(1,1), Venid int,VenGrpId int)
insert into #temp1 select vendorid, VenGroupId from avendormaster  where VenGroupId = @intVenGroupid
--drop table #temp1 select * from #temp1
set @count =(select count(*) from #temp1)
set @index = 1
set @strvendorid=''''
while(@index < = @count )
begin
print len(@strvendorid)
if  len(@strvendorid) = 0
begin
set @strvendorid =(select Venid from #temp1  where VenGrpId = @intVenGroupid and id= @index )
end
else
begin
set @strvendorid = (convert(varchar(8000), @strvendorid) +'',''+ convert(varchar(8000),(select Venid from #temp1
where VenGrpId = @intVenGroupid and id = @index)))
end
set @index= @index + 1
end
--select @strvendorid
drop table #temp1
end
-----------------------------------------------------------------------
if @strvendorid <>'' ''    --hari given to handle with out customerid also
Begin
--set @strvendorid = '' a.pbhvendorid in ('' + @strvendorid + '')''
set @SettleVendId = '' vendorid in ('' + @strvendorid + '') and ''
set @BillVendid = '' vwBills.pbhVendorID in ('' + @strvendorid + '') and ''
End
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpBills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and pbhbilldate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpbills
Select *,0 from vwbills where '' + @BillVendid +
'' pbhbilldate <='''''' + @dtbilldate + '''' +
'''''' and pbhbilldate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' +
@SettleVendId + '' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where ''
+ @SettleVendId + '' settleddate <='''''' + @dtbilldate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwpayments where '' + @SettleVendId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtbilldate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwpayments where '' + @SettleVendId +
''  settleddate <='''''' + @dtbilldate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
--select * from #tmpSettlements
--select * from #tmpBills
set @strquery = ''select max(a.pbhbillamount) billamount,
sum(a.paidamount) paidamount , a.pbhvendorid ,
a.shopid,a.departmentid,a.billsid,a.type,a.due, a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,
creditoraccid,b.AccountDesc from (SELECT
vwbills.companyid, vwbills.shopid, vwbills.departmentid,
vwbills.billsid,vwbills.pbhVendorID, vwbills.billsno,
vwbills.pbhremarks, vwbills.referenceno,
vwbills.pbhbilldate, vwbills.duedate, vwbills.pbhBillAmount,
vwbills.Due,vwbills.type, vwbills.updatetime,
isnull(vwpayments.PaidAmount,0) paidamount,
aVendorMaster.VendorName,
aCurrencyMaster.CurrencyName, aCurrencyMaster.Symbol,creditoraccid
FROM { oj ((#tmpBills vwbills INNER JOIN aVendorMaster
aVendorMaster ON vwbills.pbhVendorID = aVendorMaster.VendorID)
LEFT OUTER JOIN #tmpSettlements vwpayments ON
vwbills.companyid = vwpayments.companyid AND
vwbills.billsid = vwpayments.billsid AND
vwbills.pbhVendorID = vwpayments.vendorid AND
vwbills.shopid = vwpayments.shopid and
vwbills.type = vwpayments.type and
/*vwbills.departmentid = vwpayments.departmentid and  */
(vwpayments.settleddate <='''''' + @dtbilldate + '''''' or
vwpayments.settleddate is null))
INNER JOIN aCurrencyMaster aCurrencyMaster ON
aVendorMaster.CurrencyID = aCurrencyMaster.CurrencyID AND
aVendorMaster.CompanyID = aCurrencyMaster.CompanyID})  a,
aAccountMaster b
where a.CreditorAccID = b.AccountID and a.pbhbilldate<='''''' + @dtbilldate + '''''''' +
''group by a.pbhvendorid , a.shopid,a.departmentid,a.billsid,a.type,a.due,a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,creditoraccid,b.AccountDesc
having max(a.pbhbillamount) <> sum(a.paidamount)''
if @intageTodate=1
begin
update #tmpBills set age=datediff(day,pbhBilldate,CONVERT(DATETIME, @dtbilldate,102))
update #tmpBills 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
drop table #tmpBills
drop table #tmpSettlements
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCRM_GeneratePrefix]    Script Date: 10/06/2012 14:17: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].[spCRM_GeneratePrefix]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- =============================================
-- Author		:	MANUNADH. U
-- Create Date	:	09-04-2010
-- Description	:	To return the Prefix
CREATE PROCEDURE [dbo].[spCRM_GeneratePrefix]		
	@InterfaceId int = 0,
	@FinancialYearId int = 0,
	@CompanyId int = 0,
	@Prefix varchar(50)='''' output
AS
BEGIN 	
	SET NOCOUNT ON;
	select @Prefix=dbo.[GenerateNextTransactionNo](@InterfaceId,@FinancialYearId,@CompanyId)
	if @Prefix is null
		begin
			DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
			set @ErrMsg=''Prefix not set!!!''
			set @ErrSeverity=16
			RAISERROR(@ErrMsg, @ErrSeverity, 1)
		end   	  	
END
------------------------------------------------------------------------------------------------------
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[CRMVersion]'') AND type in (N''U''))
DROP TABLE [dbo].[CRMVersion]' 
END
GO
/****** Object:  View [dbo].[vwInhousePurchasesAgainstVendors]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesAgainstVendors]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view lists out all inhouse purchases done
-- against vendors in vendor master.
-- Here, prefix ip stands for Inhouse Purchase
--------------------------------------------------------------------------------
-- Coded By : Regin T.
-- Coded On : 03-03-2010
--------------------------------------------------------------------------------
CREATE view [dbo].[vwInhousePurchasesAgainstVendors] as
select iphId ipId, iphNo ipNo, iphDate ipDate, sum(ipdQuantity*ipdRate) ipAmount,
iphVendorId ipVendorId, VendorName ipVendorName, iphDepartmentId ipDepartmentId
from loaInhousePurchaseHeader
inner join loaInhousePurchaseDetail on iphId=ipdid
inner join aVendorMaster on iphVendorId=VendorId
where iphCancel=0
group by iphId, iphNo, iphDate, iphVendorId, VendorName, iphDepartmentId'
GO
/****** Object:  View [dbo].[vwinhousepurchase]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinhousepurchase]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwinhousepurchase]  as
select iphid,iphvendorname,iphvendoraddress,iphdate,iphno,ipdid,ipditemcode,ipditemDescription,
ipdquantity,ipdrate,ipdamount,iphDepartmentId from loaInhousePurchaseHeader h left outer join adepartmentmaster dep
on dep.companyid=h.iphcompanyid ,loaInhousePurchaseDetail d
where iphid=ipdid and  dep.DepartmentID=h.iphDepartmentID'
GO
/****** Object:  View [dbo].[gmleveltwo]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmleveltwo]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gmleveltwo    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 17/11/2001 9:21:14 PM ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.gmleveltwo    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[gmleveltwo] as
select gm.groupid, gm.parentgroupid, gm1.levelgm + 1 levelgm from agroupmaster gm,
gmlevelone gm1
where gm.parentgroupid = gm1.groupid'
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchDepartments]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchDepartments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Author:  Rajesh Kamalakshan
-- Create date: 30-04-2010
-- Description: To get the departments in a company
-- =============================================
CREATE PROCEDURE [dbo].[SpMag_FetchDepartments]( @CompanyID int )
AS
BEGIN
SET NOCOUNT ON;
select * from aDepartmentMaster where CompanyID=@CompanyID
SET NOCOUNT OFF;
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spNonBuyingCustomersItemwise]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spNonBuyingCustomersItemwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--select * from adepartmentmaster
--exec spNonBuyingCustomersItemwise 2009,0,0,1,'''','''','''',0,804292
--exec spCustomerSalesQtyWise 2009,0,0,1,'''','''','''',0
--------------------------------------------------------------------------------
-- Created By   : VinothMurugan V
-- Created Date : 02/02/2010
-- Purpose  : Generate a Report for ItemWise Non Buying Customers.
--------------------------------------------------------------------------------
create  proc [dbo].[spNonBuyingCustomersItemwise] (@intYear as int, @intShopid as int,
@intDepId as int, @intCompanyId as int, @strBrand as varchar(2000),
@strItemCategoryid as varchar(2000),@strCustomerIDs as varchar(5000)='''',
@intEnableSalesDrilldown as int = 0,@itemid as int)
as
begin
create table #temp(tempcusid  int,tempcusname  varchar(250))
insert into #temp
select Customerid,customername from acustomermaster
create table #temp2 (shopid int,itemdescription varchar(250),CustomerName varchar(250),
Quantity varchar(250), MonthNo varchar(250), vunitcode varchar(250), vUnitName varchar(250), code varchar(250),
vBrand varchar(250), vitemCategoryid varchar(250), salesvalue varchar(250),
SalesType varchar(250),salespersonid varchar(250),Spername varchar(250),ItemId int,Customerid int )
insert into #temp2
--exec spCustomerSalesQtyWise 2009,0,0,1,'''','''','''',0
exec spCustomerSalesQtyWise  @intYear,@intShopid,@intDepId,@intCompanyId,@strBrand,@strItemCategoryid,@strCustomerIDs,@intEnableSalesDrilldown
--select * from #temp,#temp2 where isnull(#temp2.Customerid,0) <> #temp.tempcusid and
--#temp2.ItemId = @itemid
--select * from #temp left outer join #temp2 on  #temp.tempcusid <> isnull(#temp2.Customerid,0) where
--#temp2.ItemId = @itemid
select tempcusid,tempcusname from #temp
except
select Customerid,CustomerName from #temp2
where ItemId = @itemid
drop table #temp
drop table #temp2
--print @strsql
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReservation]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReservation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------
--Created on	: 19/08/2003
--Created by	: R Harikrishnan
--Comments	: For Manaam Reservation transaction report
---------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spReservation]
	@intCompanyID 		as int,
	@intShopID 		as int,
	@intReservationID 	as int
as
select
	rh.rhreservationno, rh.rhreservationdate,
	rh.rhcustomerid, rh.rhcustomerfirstname, rh.rhcustomerlastname, rh.rhcustomeraddress1,
	rh.rhcustomeraddress2, rh.rhcityid, rh.rhcountryid, rh.rhpassportno, rh.rhworkpermitvisano,
	rh.rhvisaexpirydate, rh.rharrivaldate, rh.rhdeparturedate,
	case 	when rh.rhreservationstatus=''C'' then ''Cancelled''
		when rh.rhreservationstatus=''P'' then ''Pending''
		when rh.rhreservationstatus=''D'' then ''Confirmed''
		else ''Others''
	end status, rh.rhrhreservationconfirmbit, rh.rhreservationconfirmdate,
	rh.rhcancellationcheck, rh.rhcancellationdate, rh.rhApartmentTypeID, rh.rhNoOFBeds,
	rh.rhBookingType, rh.rhCallAttendedBy, rh.rhExpRent, rh.rhStayType, rh.rhRemarks,
	ac.rcapartmentcategorydescription,sm.SperName,cust.CustomerName,coun.CountryName,
	city.cityName,rh.rhPPExpiryDate
from
	losReservationHeader rh(nolock)
	LEFT OUTER JOIN LosApartmentcategory ac
	on rh.rhCompanyID = ac.rccompanyid and rh.rhShopID=ac.rcshopid and
	rh.rhApartmentTypeID= ac.rcapartmentcategoryid
	LEFT OUTER JOIN aSalesPersonMaster sm
	on rh.rhCallAttendedBy=sm.Sperid
	LEFT OUTER JOIN aCity city(nolock)
	on rh.rhCityID=city.CityID and rh.rhCompanyID=city.companyID,
	aCustomerMaster cust(nolock),aCountryMaster coun(nolock)
where
	rh.rhCustomerID=cust.CustomerID and rh.rhCompanyID=cust.companyID and
	rh.rhcountryid=coun.CountryID and rh.rhCompanyID=coun.companyID and
	rh.rhshopID =@intShopID and rh.rhReservationID =@intReservationID and
	rh.rhcompanyid=@intCompanyID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPDChequeRegisterProcessingForPOS]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPDChequeRegisterProcessingForPOS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Coded by : Bijesh.B
-- Date     : 13-05-2011
-- Desc     : PDCheque Register Processing (Sonee)
-- exec spPDChequeRegisterProcessingForPOS 40,11
create PROC [dbo].[spPDChequeRegisterProcessingForPOS]
@PDTransId  as int,
@PDShopId   as int
AS
SELECT P.PDChequeid,P.PDChequeEntryDate,Acc.AccountDesc AS ''Debit Account'',
Ac.AccountDesc AS ''Credit Account'',P.PDChequeRemarks,
CASE WHEN P.PDChequePosted=1 then ''Yes'' else ''No'' end  AS POSTED
FROM ahqPDChequeprocessing P
LEFT JOIN Aaccountmaster Acc ON Acc.AccountID = P.PDChequeDebitAccid
LEFT JOIN Aaccountmaster Ac ON Ac.AccountID = P.PDChequeCreditAccid
WHERE
P.PDTransId = @PDTransId and p.PDChequeShopid = @PDShopId
ORDER BY P.PDChequeid' 
END
GO
/****** Object:  View [dbo].[vwVendorCategory]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorCategory]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwVendorCategory] as  select distinct VendorCategory ,companyid  from AVendorMaster where isnull(VendorCategory,'''')<>'''''
GO
/****** Object:  View [dbo].[vwaccountsdepwise]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccountsdepwise]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwaccountsdepwise    Script Date: 18/01/2003 9:45:34 PM ******/
--Created on 	: 29/10/02
--Create By	: Hariharan
CREATE view [dbo].[vwaccountsdepwise] as
select a.CompanyID, a.accountid, isnull(dadepartmentid ,0) daddepartmentid
from aaccountmaster a left outer join adeptaccounts da on
a.companyid = da.dacompanyid and a.accountid = da.daaccountid'
GO
/****** Object:  View [dbo].[vwaHQadminuserRightsRptDtls]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaHQadminuserRightsRptDtls]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By	: Hariharan
--Modified Date	: 04/02/2004
--created purpose: user rights report checking
-- THIS VIEW IS CHANGED TO LIST THE REPORTS RIGHT DETAILS
CREATE VIEW [dbo].[vwaHQadminuserRightsRptDtls] as
select ai.interfacename,ai.interfaceid,au.userid,au.username,
case when Patindex(''%N%'', functionrights)>0 then ''Y'' else ''N'' end  New,
case when Patindex(''%E%'', functionrights)>0 then ''Y'' else ''N''  end  Edit,
case when Patindex(''%D%'', functionrights)>0 then ''Y'' else ''N''  end  [Delete],
'' - '' Posting , '' - ''  Printing,
substring(ai.ModuleCode, 1 , 50) ModuleCode,deptid,am.DepartmentName,
case ai.modulecode when ''hqadm'' then ''HQ Admin'' end Modulename
from ausers au, auserrights ar, ainterface ai, aUserDeptDetails ad,
adepartmentmaster am where ar.interfaceid=ai.interfaceid  and ar.companyid=ai.companyid and au.userid=ar.userid
and ad.userid=ar.userid and ad.companyid=ar.companyid and ai.modulecode = ''hqadm'' and ad.deptid=am.DepartmentID
group by ai.interfaceid,deptid,ai.interfacename,au.userid,au.username,FunctionRights,
ai.ModuleCode,am.DepartmentName,ai.modulecode
Union all
select ai.interfacename,ai.interfaceid,au.userid,au.username,
'' - ''  New,'' - ''   Edit,'' - ''  [Delete],'' - '' Posting , '' - ''  Printing,
substring(ai.ModuleCode, 1, 50) ModuleCode,deptid,am.DepartmentName,
case ai.modulecode when ''sacc'' then ''Special Rights''
		   when ''accp'' then ''Power User Rights''
end Modulename
from ausers au, auserrights ar, ainterface ai, aUserDeptDetails ad,adepartmentmaster am
where ar.interfaceid=ai.interfaceid  and ar.companyid=ai.companyid and au.userid=ar.userid
and ad.userid=ar.userid and ad.deptid=am.DepartmentID and ad.companyid=ar.companyid and ai.ModuleCode in (''sacc'', ''accp'')
group by ai.interfaceid,deptid,ai.interfacename,au.userid,au.username,FunctionRights,
ai.ModuleCode,am.DepartmentName,ai.modulecode
Union ALl
select ai.interfacename,ai.interfaceid,au.userid,au.username,
case when Patindex(''%N%'', functionrights)>0 then ''Y'' else ''N'' end  New,
case when Patindex(''%E%'', functionrights)>0 then ''Y'' else ''N''  end  Edit,
case when Patindex(''%D%'', functionrights)>0 then ''Y'' else ''N''  end  [Delete],
case when Patindex(''%P%'', functionrights)>0 then ''Y'' else ''N''  end  [Print],
case when Patindex(''%U%'', functionrights)>0 then ''Y'' else ''N''  end  [Posting],
substring(ai.ModuleCode, 1, 50) ModuleCode,deptid,am.DepartmentName,
case ai.modulecode when ''p&C'' then ''Purchase And Costing - Transactions''
		   when ''acc'' then ''Accounts - Transactions''
		   when ''admin'' then ''Adminstration - Transactions''
		   when ''bgt'' then ''Budgeting - Transactions''
		   when ''pay'' then ''Payroll - Transactions''
end Modulename
from ausers au, auserrights ar, ainterface ai, aUserDeptDetails ad,adepartmentmaster am
where ar.interfaceid=ai.interfaceid  and ar.companyid=ai.companyid and au.userid=ar.userid
and ad.userid=ar.userid and ad.deptid=am.DepartmentID and ad.companyid=ar.companyid and ai.modulecode in (''p&C'', ''acc'',
''admin'', ''bgt'', ''pay'') group by ai.interfaceid,deptid,ai.interfacename,au.userid,au.username,
FunctionRights,ai.ModuleCode,am.DepartmentName,ai.modulecode
Union ALl
Select cd.RepDetailName +  '' - '' + ai.Reportname,ai.Reportid,au.userid,au.username,
''-'' New, ''-'' Edit, ''-'' [Delete], ''-'' [Print], ''-'' [Posting],
substring(rc.repCatName, 1, 50),deptid,am.DepartmentName, case rc.RepCatName when ''PANDC'' then ''Purchase And Costing - Reports''
when ''Accounts'' then ''Accounts - Reports'' when ''Payroll'' then ''Payroll - Reports''
when ''Budgetting'' then ''Budgeting - Reports'' when ''Admin'' then ''Admin'' when ''Administration'' then
''Administration - Reports'' end ModuleName
from ausers au, areportrights ar, areports ai, aUserDeptDetails ad,adepartmentmaster am , reportcategorydetail cd,
reportcategoryheader rc where ar.reportid = ai.reportid  and au.userid = ar.userid
and ad.userid = ar.userid and ad.deptid=am.DepartmentID and ad.companyid=ar.companyid
and ai.ReportCatId = cd.RepCatId and ai.ReportDetailId = cd.RepDetailID and rc.repCatId = cd.repCatId and rc.type =''R''
group by ai.reportid, deptid, cd.RepDetailName, ai.ReportName, au.userid, au.username,
am.DepartmentName, rc.RepCatName
Union ALl
Select cd.RepDetailName +  '' - '' + ai.Reportname,ai.Reportid,au.userid,au.username,
''-'' New, ''-'' Edit, ''-'' [Delete], ''-'' [Print], ''-'' [Posting],
substring(rc.repCatName, 1, 50),deptid,am.DepartmentName, case rc.RepCatName when ''PANDC'' then ''Purchase And Costing - Alerts''
when ''Accounts'' then ''Accounts - Alerts'' when ''Payroll'' then ''Payroll - Alerts''
when ''Budgetting'' then ''Budgeting - Alerts'' when ''Admin'' then ''Admin'' when ''Administration'' then
''Administration - Alerts'' end ModuleName
from ausers au, areportrights ar, areports ai, aUserDeptDetails ad,adepartmentmaster am , reportcategorydetail cd,
reportcategoryheader rc where ar.reportid = ai.reportid  and au.userid = ar.userid
and ad.userid = ar.userid and ad.deptid=am.DepartmentID and ad.companyid=ar.companyid
and ai.ReportCatId = cd.RepCatId and ai.ReportDetailId = cd.RepDetailID and rc.type =''A''
and rc.repCatId = cd.repCatId group by ai.reportid, deptid, cd.RepDetailName, ai.ReportName, au.userid, au.username,
am.DepartmentName, rc.RepCatName'
GO
/****** Object:  View [dbo].[vwHPAccountPayment]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAccountPayment]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHPAccountPayment] as
select h.*,ac.AccountDesc,c.hpCustName from  aHPPaymentHeader h,
aHPPaymentDetail d,losHPCustomerDetails c,aaccountMaster ac
where h.hphCompanyID=d.hpdCompanyID and h.hpHDepartmentID=d.hpdDepartmentID
and h.hphPaymentID=d.hpdPAymentID and c.HPCustID=h.hphCustomerID
and ac.AccountID=h.hphAccountID'
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumForAgeing]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSumForAgeing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--***************************************************************************************************
-- Created by  :  Shinu
-- Created on  : 15/07/2008
-- Purpose     : To Get Debtor Age For  0 - 15,16 - 30 ,31 - 60, 61 - 120,121 - 240,241 - 365
--***************************************************************************************************
-- Modified by : Jyothish SR
-- Modified on : 27/03/2012
-- Purpose     : Avoid Select * statement in vwinvoices and  vwsettlements
--***************************************************************************************************
--  spDebtorAgeSumForAgeing '''',''20080101'','''',0,0,0,'''',''''
--***************************************************************************************************
CREATE  PROCEDURE [dbo].[spDebtorAgeSumForAgeing] (@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 ,
Cmpexrate numeric(18,2)
)
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)
declare  @baseexrate numeric(18,9)
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 ,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,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 ,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,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 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
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,aCurrencyMaster.CurrencyID,#tmpInvoices.Cmpexrate 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,#tmpInvoices.Cmpexrate
having max(invamt) <> sum(isnull(settledamt,0))''
update  #tmpInvoices set  Cmpexrate=( select SellingRate from ExchangeRateDetail ,acustomermaster where
acustomermaster.CustomerID = #tmpInvoices.customerid and acustomermaster.CurrencyID=ExchangeRateDetail.CurrencyID)
set @baseexrate= (select SellingRate  from ExchangeRateDetail where CurrencyID=(select currencyid from aCompanyMaster))
update  #tmpInvoices set  Cmpexrate=@baseexrate/Cmpexrate
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 <= 120) then ''61 - 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetExchangeRate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExchangeRate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on 		: 07/06/2003
-- Created by           : Kishore
-- Comments             : This sp returns the exchange rate to convert
--                        one currency to another.
--                        The exchange rate is returned through @numExchangeRate
-------------------------------------------------------------------------------------
-- Modified on		: 21/07/2003
-- Modified by		: Kishore
-- Comments		: Increased the precision of exchange rate from (18, 3) to (18, 8)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spGetExchangeRate] (@intCompanyId as int, @intFromCurrencyId as Int,
					@intToCurrencyId as Int,
					@numExchangeRate as Numeric(18, 8) OUTPUT) AS
BEGIN
	DECLARE @numFromExRate AS Numeric(18, 8)
	DECLARE @numToExRate AS Numeric(18, 8)
	
	-- get from exchange rate for base currency
	SELECT @numFromExRate = SellingRate
	FROM ExchangeRateDetail
	WHERE CurrencyId = @intFromCurrencyId
	AND CompanyId = @intCompanyId
	
	-- get to exchange rate for base currency
	SELECT @numToExRate = SellingRate
	FROM ExchangeRateDetail
	WHERE CurrencyId = @intToCurrencyId
	AND CompanyId = @intCompanyId
	--get the exchange rate between ''to'' and ''from'' currencies	
	IF @numFromExRate <> 0
		Set @numExchangeRate = @numToExRate / @numFromExRate
	ELSE
		Set @numExchangeRate = 0
	
	RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetAllSubDepartments]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetAllSubDepartments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created  on 	: 05/02/2003
-- Created  by	: R Harikrishnan
-- Purpose 	: For getting all the sub department ids
------------------------------------------------------------------------
-- Modified on  : 13/12/2003
-- Modified by  : Kishore
-- Comments     : Changed the logic to take sub department above level 2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE procEDURE [dbo].[spGetAllSubDepartments]
	@intDeptID 		as int,
	@intCompanyID 		as int,
	@strSubDepartments	as varchar(500) OUTPUT AS
Begin
DECLARE @Count as int
DECLARE @TempDepId as int
DECLARE @strResult as Varchar(500)
SET NOCOUNT ON
-- ALTER temporary table
-- status field holds whether the department is processed
-- or not. i.e. sub depts are taken or not
CREATE table #SubDepts
(DeptId int PRIMARY KEY,
Status bit)
-- insert the immediate sub departments
INSERT INTO #SubDepts
SELECT DepartmentId, 1
FROM aDepartmentMaster
WHERE ParentDepId = @intDeptId
AND CompanyId = @intCompanyId
-- get the count of unprocessed departments
SELECT @Count = COUNT(*) FROM #SubDepts
WHERE Status <> 0
Set @strResult = @intDeptID
-- if unprocessed depts exist
WHILE (@Count <> 0)
Begin
-- get a department id from SubDepts where status is not zero
SELECT TOP 1 @TempDepId = DeptId
FROM #SubDepts
WHERE Status <> 0
-- add the department to string
Set @strResult = @strResult + '', '' + rTrim(lTrim((Cast(@TempDepId AS Varchar(3)))))
-- then insert sub departments of that dep id
INSERT INTO #SubDepts
SELECT DepartmentId, 1
FROM aDepartmentMaster
WHERE ParentDepId = @TempDepId
AND CompanyId = @intCompanyId
-- update the status of current dep id, as its sub departments are inserted
UPDATE #SubDepts
SET Status = 0
WHERE DeptId = @TempDepId
-- get the count of unprocessed departments
SELECT @Count = COUNT(*) FROM #SubDepts
WHERE Status <> 0
End
-- delete the temporary table
DROP TABLE #SubDepts
-- return the output string
Set @strSubDepartments = @strResult
SET NOCOUNT OFF
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum_EmailClient]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSum_EmailClient]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------
-- Modified by : Prasanth Joseph
-- Modified on : 03-07-2009
-- Comments : This Sp generated from SpDebtoragesum for sending Email accoring to the customer inv Age.
-----------------------------------------------------------------------------
-- spDebtorAgeSum_EmailClient '''',''20121010'',''810'',0,0,0,'''',''''
create PROCEDURE [dbo].[spDebtorAgeSum_EmailClient] (@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(7),
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))
/*
Create table #tmpDebtorAge (CustomerID int,
InvocieID int,
InvAmount int,
SettledAmt int,
BalanceAmt int,
Age int,
Due 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 @dtinvdate=convert(varchar,getdate(),112)
SET @SettleCustId = ''''
set @Invcustid = ''''
set @strShop = ''''
set @strCatCond=''''
set @strGroupCond=''''
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 *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0 from vwinvoices where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpInvoices
Select *,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 vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate + ''''''''
else
set @strquery = ''insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery = '' insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery = ''insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
select * into #tempCustomer from acustomermaster
delete from EmailList
set @strquery = ''insert into EmailList SELECT #tmpInvoices.customerid CustomerID,#tmpInvoices.DepartmentID,d.DepartmentName,#tmpInvoices.invoiceid,
max(invamt) invamt,isnull(sum(settledamt),0) settleam,max(invamt)-isnull(sum(settledamt),0) Balance,age,due,0,currencyname,symbol
,#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.Referenceno,#tmpInvoices.remarks
--into #temp_EmailList
from
#tmpInvoices #tmpInvoices LEFT OUTER JOIN adepartmentmaster d on  #tmpInvoices.departmentid=d.DepartmentID
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.customerid,#tmpInvoices.invoiceid,Age,due,currencyname,symbol,#tmpInvoices.DepartmentID,d.DepartmentName
,#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.Referenceno,#tmpInvoices.remarks
HAVING max(invamt) <> sum(isnull(settledamt,0))''
--print @strquery
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 EmailList
--insert into #tmpDebtorAge from exec sp_Executesql @st rquery
--select * from #tempCustomer
--drop table #temp_EmailList
drop table #tmpInvoices
drop table #tmpSettlements
end
set nocount off
set ansi_Warnings on' 
END
GO
/****** Object:  View [dbo].[vwdummyPosSalesForReport]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyPosSalesForReport]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Kishore
-- Created on  : 29/07/2003
-- Comments    : Taken from v2
--               This view is used in rptPosSales
--------------------------------------------------------------
-- Modified by : Kishore
-- Modified on : 14/07/2003
-- Comments    : Added posdFreeQuantity column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------
-- Modified by : Rajesh Kamalskshan
-- Modified on : 2/06/2007
-- Comments    : For Dummy Sales
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by : Shine Das
-- Modified on : 19/11/2011
-- Comments    : Added serial Number
-- Ref No 01
CREATE VIEW [dbo].[vwdummyPosSalesForReport] AS
SELECT  isnull(spername, '''') spername,
case when (posdDescription is null or posdDescription ='''') then
vw.ItemDescription
else posdDescription
end ItemDescription, poshBillId, poshBillNo, poshShopId, poshBillDate,
posdItemId, posdQuantity, posdPQuantity, posdUnitPrice,
posdActualUnitPrice, posdCostPrice,
poshRecAddUser, poshRecModifyUser, UnitCode, PackingTypeCode, poshCustomerName,
Symbol, posdPackingTypeId, u.UnitId, a.ItemCode,
UnitName, PackingTypeName, poshCancelledRemarks Remarks, posdFreeQuantity,
posdSerialNo,posdBillDetailID    -- Ref No 01
FROM LOsPosdummyHeader left outer join aSalesPersonMaster sp
ON sp.sperId = poshSalesPersonId LEFT OUTER JOIN aAccountMaster ac
ON ac.AccountId = poshCashAccId
LEFT OUTER JOIN aCurrencyMaster c
ON ac.CurrencyId = c.CurrencyId, LOsPosdummyDetail, aItem a, aPackingType p,
vwItemDescription vw, aUnit u
WHERE poshShopId = posdShopId and poshBillId = posdBillId
and posdPackingTypeId = p.PackingTypeId
and posdItemId = a.ItemId
and a.ItemId = vw.ItemId
and u.unitid = a.unitsid'
GO
/****** Object:  View [dbo].[vwcustomercategory]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomercategory]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcustomercategory    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwcustomercategory    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwcustomercategory    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwcustomercategory    Script Date: 20/11/2001 9:58:55 AM ******/
/****** Object:  View dbo.vwcustomercategory    Script Date: 17/11/2001 9:21:15 PM ******/
CREATE view [dbo].[vwcustomercategory] as
select distinct isnull(customercategory,'''') customercategory, companyid from acustomermaster'
GO
/****** Object:  StoredProcedure [dbo].[SendSMS]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SendSMS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Rajesh Kamalakshan
-- Create date: 06-06-2009
-- Description: For sending SMS to customers on Outstandings
-- =============================================
CREATE PROCEDURE [dbo].[SendSMS] --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 = 214
--select * from #MailList
--drop table #MailList
declare @customerid as int;
declare @amount as numeric(18,2)
declare @age as int
declare @CustomerName as varchar(100)
declare @ContactName1 as varchar(100)
declare @DuePeriod as int
declare @EmailID as varchar(500)
declare @currencysymbol as varchar(20)
declare @body1 varchar(5000)
declare @Message 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 @CopycEmail varchar(2000)
declare @departmentid int
declare @departmentname varchar(50)
declare @Profile as varchar(100)
declare @Divisionhead as varchar(150)
declare @CompanyName as varchar(250)
declare @CompanyTelephone as varchar(50)
declare @CompanyFax as varchar(50)
declare @Companyemail as varchar(50)
declare @CompanyAddress1 as varchar(250)
declare @CompanyAddress2 as varchar(250)
declare @CompanyAddress3 as varchar(250)
declare @XMLEmailList as xml
declare @CustomerStatement as varchar(max)
set @profile=''Fies Automated SMS Service''
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,@Subject1=contactPhone,@ContactName1=ContactName,@Address1=Address1,@Address2=Address2,@Address3=Address3,@DuePeriod=Dueperiod from dbo.aCustomerMaster where CustomerID=@customerid and CompanyID=@CompanyId
---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 @amount=0
select @departmentid=max(departmentid)from #Departments
------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 and departmentid =@departmentid group by symbol,DepartmentName
if @amount>0
begin
set @Signature='' Should you have any concerns related to releasing the payment, Please contact Visam on 7786594 or Mini on +919447079035. Fi-es MAGNOLIA ERP, Auto SMS Service.''
set @body1 = ''Dear ''+isnull(@ContactName1,'' '')+'', Hope you are keeping well. Kind reminder to make the payment for  ''+@currencysymbol +'' '' +cast(@amount as varchar(50)) +''.Wishing you a good day.''+@Signature
--  set @subject1=''+9607773451''
EXEC msdb.dbo.sp_send_dbmail @recipients=''sms@comcare.com'',
@subject = @subject1,
@body = @body1,
@body_format = ''TEXT'',
@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' 
END
GO
/****** Object:  StoredProcedure [dbo].[SendEmails]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SendEmails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchTransferIn]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchTransferIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Regin T.
-- Create date: 30-04-2010
-- Description:	Returns Transfer In transactions
-- =============================================
CREATE PROCEDURE [dbo].[SpMag_FetchTransferIn]
	@intCompanyId int,
	@intShopId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
SELECT
tihid,tihno,tihdate,shopname,tohno,
case tihcancel when 1 then ''Yes'' when 0 then ''No'' end,
case TIHPosted when 1 then ''Yes'' when 0 then ''No'' end,
case TIHTransFinished when 1 then ''Yes'' when 0 then ''No'' end,
tohdate from mestransferoutheader,ashops,LOstransferinheader
WHERE
LOstransferinheader.tihdespatchid=mestransferoutheader.tohid
and  LOstransferinheader.tihType=''TI'' and LOstransferinheader.tihshopid=1
and  LOstransferinheader.tihfromshopid = mestransferoutheader.tohshopid
and  LOstransferinheader.tihfromshopid=ashops.shopid
and  tihdate >=''20100415'' order by tihid END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningGodownstockondate]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningGodownstockondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--Modified by  : 18/05/04
--Comments  : added Costprice
--Last Modified on  : 23/03/2010
--Modified by  : jyothish S R
--Comments  : v4
--Comments  : Added stock of all godown
CREATE   procedure [dbo].[spOpeningGodownstockondate] ( @intItemId as int, @fromdate as varchar(10),
@intGodownID as int,@intdepartmentid as int =0,@intcompanyid as int=1 ,@outputopenstock as numeric(18,3)=0 output)as
declare
@Curstock as numeric(18,3),
@openingstock as numeric(18,3),
@transqty as numeric(18,3),
@dtFromDate as datetime,
@transcostprice as numeric(18,2),
@costprice as numeric(18,2),
@Itemctr as numeric(16,2),
@opencostprice as numeric(18,2),
@ToCurr as integer,
@invCurrid as integer,
@exrate as numeric(18,2)
set nocount on
begin
SET @Curstock = 0.0
SET @openingstock = 0.0
set @transqty = 0.0
set @transcostprice =0.0
set @costprice =0.0
set @Itemctr =0.0
set @opencostprice =0.00
set @dtFromDate = convert(datetime,@fromdate,101)
Select @openingstock = sum(isnull(gsopeningstock,0.0)) from moigodownstock where
gsitemid=@intItemid ---and gsgodownid=@intgodownid
select @invCurrid=b.currencyid from apackagesettings a,acurrencymaster b,
aaccountmaster c where accountid=inventoryid and a.companyid=b.companyid and
c.CurrencyID=b.currencyid
if @intdepartmentid =0
begin --Getting Company Curr
select @Tocurr= a.currencyid from acurrencymaster a,
acompanymaster b where a.companyid=b.companyid  and
a.CurrencyID=b.currencyid
end
else
begin ----Getting dep Curr
select  @Tocurr= a.currencyid from acurrencymaster a,
adepartmentmaster b where a.companyid=b.companyid  and
a.CurrencyID=b.depcurrencyid and departmentid=@intdepartmentid
end
exec spGetExchangeRate @intcompanyid,@invCurrid,@Tocurr, @ExRate output
select @itemctr=count(cditemid),@opencostprice=sum(cdNewItemCostPrice*@ExRate) from loacostingheader,
loacostingdetail where chcostingid=cdcostingid and chcancelled=0 and cdItemID=@intitemid
and chcostingid=0
if @itemctr=0
begin
select top 1 @opencostprice=cdOldItemCostPrice*@ExRate from loacostingheader,loacostingdetail
where chcostingid=cdcostingid and chcancelled=0 and
cdItemID=@intitemid and chcostingid<>0 order by chCostingDate asc
end
if @intdepartmentid =0
begin
if @intGodownID=0
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid  and godownid in( select GodownID  from agodown)
end
else
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid  and  godownid=@intgodownid
end
end
else
begin
if @intGodownID=0
begin
select  @transcostprice=isnull(sum(depcostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid  and godownid in( select GodownID  from agodown where DepartmentId=@intdepartmentid)
end
else
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid  and  godownid=@intgodownid
end
end
set @curstock= isnull(@openingstock,0.0) + isnull(@transqty,0.0)
set @costprice = isnull(@opencostprice * @openingstock,0.0)+isnull(@transcostprice,0.0)
if @curstock = 0
set @costprice = 0.0
if @outputopenstock =1
begin
set @outputopenstock = @curstock
end
--else
-- select @intItemid itemid,@curstock openstock,@costprice costprice
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spshopOpeningstockondate]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spshopOpeningstockondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Comments  : v3
--Modified by  : venkitesh 180504
--Comments  : For Adding openings costprice ,dep wise and compwise
--Last Modified on  : 23/03/2010
--Modified by  : jyothish S R
--Comments  : v4
--Comments  : Added stock of all shop
Create   procedure [dbo].[spshopOpeningstockondate] ( @intItemId as int, @fromdate as varchar(10),
@intShopid as int,@intdepartmentid as int =0,@intcompanyid as int=1 ,
@outputopenstock as numeric(18,3)=0 output)
as
Set ansi_warnings off
Begin
declare
@Curstock as numeric(18,3),
@openingstock as numeric(18,3),
@TransQty as numeric(18,3),
@dtFromDate as datetime,
@opencostprice as numeric(18,2),
@transcostprice as numeric(18,2),
@costprice as numeric(18,2),
@Itemctr as numeric(16,2),
@ToCurr as integer,
@invCurrid as integer,
@exrate as numeric(18,2),
@Totalstock as numeric(18,2),
@Godwonstock as numeric(18,2)
set nocount on
begin
SET @Curstock = 0.0
SET @openingstock = 0.0
SET @transqty = 0.0
set @opencostprice=0.0
set @transcostprice=0.0
set @dtFromDate = convert(datetime,@fromdate)
if @intdepartmentid =0  and @intShopid=0
begin
Select @openingstock = sum(isnull(openingstock,0.0)) from mosshopstock where
itemid=@intItemid --and shopid=@intShopid
end
else if @intdepartmentid <> 0  and @intShopid=0
begin
Select @openingstock = sum(isnull(openingstock,0.0)) from mosshopstock where
itemid=@intItemid  and shopid in ( select ShopID from ashops where DepartmentID=@intdepartmentid)
end
else
begin
Select @openingstock = sum(isnull(openingstock,0.0)) from mosshopstock where
itemid=@intItemid and shopid=@intShopid
end
select @invCurrid=b.currencyid from apackagesettings a,acurrencymaster b,
aaccountmaster c where accountid=inventoryid and a.companyid=b.companyid and
c.CurrencyID=b.currencyid
if @intdepartmentid =0
begin --Getting Company Curr
select @Tocurr= a.currencyid from acurrencymaster a,
acompanymaster b where a.companyid=b.companyid  and
a.CurrencyID=b.currencyid
end
else
begin ----Getting dep Curr
select  @Tocurr= a.currencyid from acurrencymaster a,
adepartmentmaster b where a.companyid=b.companyid  and
a.CurrencyID=b.depcurrencyid and departmentid=@intdepartmentid
end
exec spGetExchangeRate @intcompanyid,@invCurrid,@Tocurr, @ExRate output
select @itemctr=count(cditemid),@opencostprice=sum(cdNewItemCostPrice * @exrate ) from loacostingheader,
loacostingdetail where chcostingid=cdcostingid and chcancelled=0 and
cdItemID=@intitemid and chcostingid=0
if @itemctr=0
begin
select top 1 @opencostprice=cdOldItemCostPrice*@exrate from
loacostingheader,loacostingdetail where chcostingid=cdcostingid
and chcancelled=0 and cdItemID=@intitemid and chcostingid<>0
order by chCostingDate asc
end
if @intdepartmentid =0
begin
if @intShopid=0
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00) , @transqty = isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwshopbincardaudit where   itemid=@intItemId     and sdate < @dtFromDate  --and shopid=@intShopid
end
else
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00) , @transqty = isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwshopbincardaudit where   itemid=@intItemId     and sdate < @dtFromDate and shopid=@intShopid
end
end
else
begin
if @intShopid=0
begin
select  @transcostprice=isnull(sum(depcostprice * isnull(Transqty*mode,0.0)),0.00) , @transqty = isnull(sum(isnull(Transqty*mode,0.0)), 0.0) from
vwshopbincardaudit where shopid in (select ShopID  from ashops where DepartmentID = @intdepartmentid ) and itemid=@intItemId and sdate < @dtFromDate
end
else
begin
select  @transcostprice=isnull(sum(depcostprice * isnull(Transqty*mode,0.0)),0.00) , @transqty = isnull(sum(isnull(Transqty*mode,0.0)), 0.0) from
vwshopbincardaudit where shopid=@intShopid and itemid=@intItemId and sdate < @dtFromDate
end
end
set @curstock = isnull(@openingstock,0.0) + isnull(@transqty,0.0)
set @costprice = isnull(@opencostprice * @openingstock,0.0)+isnull(@transcostprice,0.0)
if @intShopid=0
begin
exec spOpeningGodownstockondate @intItemId,@fromdate,0,@intdepartmentid,@intcompanyid,@Totalstock output
end
set @curstock=@curstock+isnull(@Totalstock ,0)
if @curstock = 0
begin
set @costprice = 0.0
end
if @outputopenstock=1
set @outputopenstock=@curstock
else
select @intItemid itemid, @curstock openstock,@costprice costprice
end
End
Set ansi_warnings off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemorbrandsold]    Script Date: 10/06/2012 14:17: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].[spcustomeritemorbrandsold]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  proc [dbo].[spcustomeritemorbrandsold] @intshopid as int, @intcustomerid as int,
@intitemid as int, @strbrandname as varchar(250), @strfromdate as varchar(8),
@strtodate as varchar(8) as
begin
set nocount on
declare @strwherecondition as varchar(500),
@strsql as nvarchar(1000),
@strlinktable as varchar(250),
@strDepSymbol as varchar(50),
@intcount as int,
@inttransid as int,
@numopstock as numeric(18,3),
-- getting the opening stock , receipts/pur and transfer/sale and closing stock in a variable
@numopeningstock  as numeric(18,3),
@numrorp   as numeric(18,3),
@numtors   as numeric(18,3),
@numclosingstock  as numeric(18,3)
create table #item (
selitemid   int   null,
opstock  numeric(18,3) null,
receiptorpur numeric(18,3) null,
transferorsale numeric(18,3) null
)
create table #temp(
transid int null)
select @strdepsymbol = symbol from acurrencymaster c, ashops s, adepartmentmaster d
where c.currencyid = d.depcurrencyid and s.departmentid = d.departmentid and s.shopid = @intshopid
set @strwherecondition =''''
if @strfromdate =''''
set @strwherecondition = '' and vw.ihinvoicedate <= '''''' + @strtodate + ''''''''
else
set @strwherecondition = '' and vw.ihinvoicedate >= '''''' + @strfromdate +
'''''' and vw.ihinvoicedate <= '''''' + @strtodate + ''''''''
if @intitemid <> 0
begin
insert into #item (selitemid) values( @intitemid)
end
if @intcustomerid <> 0
set @strwherecondition = @strwherecondition + '' and vw.ihcustomerid = '' +
ltrim(rtrim(str(@intcustomerid)))
if @strbrandname <> ''''
begin
insert into #item (selitemid)
select itemid from aitem,
(select brandname from abrandmaster where brandname in ( @strbrandname )) b
where brand = brandname
end
insert into #temp
select selitemid from #item
select @intcount = count(*) from #temp
while @intcount <>0
begin
select @inttransid = max(transid) from #temp
set @numopstock =1
exec spshopopeningstockondate @inttransid, @strfromdate, @intshopid ,0,1,
@numopstock output
update #item set opstock = @numopstock where selitemid = @inttransid
if @strfromdate =''''
begin
update #item set receiptorpur = qty from (select sum(isnull(transqty,0.0)) qty
from vwshopbincardaudit vw where itemid = @inttransid and vw.shopid =
@intshopid and sdate = @strtodate and mode =1) as a where selitemid = @inttransid
update #item set transferorsale = qty from (select sum(isnull(transqty,0.0)) qty
from vwshopbincardaudit vw where itemid = @inttransid and vw.shopid =
@intshopid and sdate = @strtodate and mode =-1) as a where selitemid = @inttransid
end
else
begin
update #item set receiptorpur = qty from (select sum(isnull(transqty,0.0)) qty
from vwshopbincardaudit vw where itemid = @inttransid and vw.shopid =
@intshopid and sdate >= @strfromdate and sdate <=@strtodate and mode =1) as a
where selitemid = @inttransid
update #item set transferorsale = qty from (select sum(isnull(transqty,0.0)) qty
from vwshopbincardaudit vw where itemid = @inttransid and vw.shopid =
@intshopid and sdate >= @strfromdate and sdate <=@strtodate and mode =-1) as a
where selitemid = @inttransid
end
delete from #temp where transid = @inttransid
select @intcount = count(*) from #temp
end
select @numopeningstock = sum(isnull(opstock,0.0)), @numrorp = sum(isnull(receiptorpur,0.0)) ,
@numtors = sum(isnull(transferorsale,0.0)), @numclosingstock = sum(isnull(opstock,0.0)) +
sum(isnull(receiptorpur,0.0)) - sum(isnull(transferorsale,0.0)) from #item
set @strsql = N''select c.customername, sum(quantity) quantity, sum(depamount) depamount,
sum(amount) customeramt, cur.symbol customersymbol, '''''' + @strdepsymbol +
'''''' depsymbol, '' + ltrim(rtrim(str(@numopeningstock))) + '' opstock, '' + ltrim(rtrim(str(@numrorp))) +
'' receiptorpur, '' + ltrim(rtrim(str(@numtors))) + '' transorsale , '' + ltrim(rtrim(str(@numclosingstock)))
+ '' closingstock from acustomermaster c, acurrencymaster cur , vwCustomerSalesByitem vw,
#item i where cur.currencyid = c.currencyid and vw.iditemid = i.selitemid and c.customerid =
vw.ihcustomerid and vw.ihshopid = '' + ltrim(rtrim(str(@intshopid))) + @strwherecondition +
'' group by c.customername, cur.symbol''
--print @strsql
exec sp_executesql @strsql
set nocount off
drop table #temp
drop table #item
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spConvertequiamount]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertequiamount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spConvertequiamount 1, ''co'', 3, ''d'', ''2:1:-1:12.85:'',  100, 0
-------------------------------------------------------------------------------------------
--Created on  : 01/12/2002
--Created by : leo
--Comments : to do the currency conversion, this formula is tested
-------------------------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 11/12/2002
-- Comments     : Added the new parameter strSelectType. Pass '''' to this argument if you
--                do not want select statement at the end
-------------------------------------------------------------------------------------------
-- Modified by  : leo, R Harikrishnan
-- Modified on  : 21/01/2003, 24/09/2003
-- Comments     : Added one more type m for currency
--  : Changed the output parameter precision to 4
-------------------------------------------------------------------------------------------
--Modified on : Nidheesh P V
--Modified on :25/05/2101
--comments : added the case for companymaster(''co'')
-------------------------------------------------------------------------------------------
CREATE proc [dbo].[spConvertequiamount]
@intfromid  as int,
@strfromtype  as char(2),
@inttoid  as int,
@strtotype  as char(1),
@strexrates  as varchar(250),
@numAmount  as numeric(18,4),
@numequiamount  as numeric(18,4) = 1 output,
@strSelectType  as char(1) = ''S''
as
begin
set nocount on
declare @intcurid as int,
@numfromer as numeric(18,8),
@numtoer as numeric(18,8)
if @strfromtype =''c''
select @intcurid = currencyid from acustomermaster  where customerid = @intfromid
if @strfromtype =''d''
select @intcurid = depcurrencyid from adepartmentmaster where departmentid = @intfromid
if @strfromtype =''v''
select @intcurid = currencyid from avendormaster where vendorid = @intfromid
if @strfromtype =''a''
select @intcurid = currencyid from aaccountmaster where accountid = @intfromid
if @strfromtype =''m''
select @intcurid = @intfromid
if @strfromtype =''co''
select @intcurid = currencyid from acompanymaster  where CompanyID = @intfromid
exec spReturnExrate @intcurid, @strexrates, @numfromer output
if @strtotype =''c''
select @intcurid = currencyid from acustomermaster where customerid = @inttoid
if @strtotype =''d''
select @intcurid = depcurrencyid from adepartmentmaster where departmentid = @inttoid
if @strtotype =''v''
select @intcurid = currencyid from avendormaster where vendorid = @inttoid
if @strtotype =''a''
select @intcurid = currencyid from aaccountmaster where accountid = @inttoid
if @strtotype =''m''
select @intcurid = @inttoid
if @strfromtype =''co''
select @intcurid = currencyid from acompanymaster  where CompanyID = @inttoid
exec spReturnExrate @intcurid, @strexrates, @numtoer output
exec spconvertcurrency @numfromer, @numtoer, @numamount, @numequiamount output
if @strSelectType = ''S''
begin
select @numequiamount Equiamount
end
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownLocationItemMerge]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownLocationItemMerge]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------
-- Created By 	 : Kishore
-- Created Date  : 23/08/2003
-- Comments	 : Created for updation of location stock
--                 at locations (godowns and shops) after item merging
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateGodownLocationItemMerge] (
				    @intMergeId as int,
				    @intGodownId as int,
				    @intCompanyId as int) AS
begin
	Declare @numQuantitySum as Numeric(18, 8)
	Declare @intCount as int
	Declare @intItemId as int	
	Declare @bitHasLocation as bit
	Declare @intLocationId as int
	Declare @intCurItemId as int
	Declare @numStock as Numeric(18, 8)
	Declare @intArrivalDetailId as int
	Declare @intIssueDetailId as int
	
	Set NoCount On
	Set ansi_warnings off
	
	-- get location status
	SELECT @bitHasLocation = LocationArrangement FROM aGodown
		WHERE godownId = @intGodownId
	
	-- exit if the godown has no locations
	If @bitHasLocation = 0
	Begin
		Return
	End
	
	set @numQuantitySum = 0.0
	set @intCount = 0
	
	-- get the sum of quantity from loiMergeDetails
	SELECT @numQuantitySum = SUM(lgsdQty) FROM loiMergeDetails
		WHERE lgdId = @intMergeId
		AND lgdGodownId = @intGodownId
		AND lgdCompanyId = @intCompanyId
	-- get the item id from header and item cost
	SELECT @intItemId = lghItemId
		FROM loiMergeHeader LEFT OUTER JOIN aItem
		ON loiMergeHeader.lghItemId = aItem.ItemId
		WHERE lghId = @intMergeId
		AND lghGodownId = @intGodownId
		AND lghCompanyId = @intCompanyId
	
	Set @intArrivalDetailId = 1
	Set @intIssueDetailId = 1
	-- get the first location id to insert stock
	SELECT TOP 1 @intLocationId = lLocationId FROM loiLocation
		WHERE lGodownId = @intGodownId
			
	INSERT INTO loiLocationArrivalDetails
		(ladinterfaceid, ladgodownid, ladtransid, laddetailid,
		ladlocationid, laditemid, laditemqty, ladpackingtypeid,
		ladpakingqty, ladcancel, ladadjustment)
		VALUES
		(8008, @intGodownId, @intMergeId, @intArrivalDetailId,
		@intLocationId, @intItemId,
		@numQuantitySum, 1, @numQuantitySum, 0, 0)
		
	Set @intArrivalDetailId = @intArrivalDetailId + 1
	-- now make location stock of all details item to 0
	Declare curMergedItems Cursor For
		SELECT lgdItemId FROM loiMergeDetails
		WHERE lgdId = @intMergeId
		AND lgdGodownId = @intGodownId
		AND lgdCompanyId = @intCompanyId
	Open curMergedItems
	Fetch Next From CurMergedItems Into @intCurItemId
	While @@Fetch_status = 0	
	Begin
		-- get current location stock
	SELECT @NumStock = qty
	FROM
	(SELECT LocationId, GodownId,
		ItemId, SUM(qty) qty
	        FROM
		(SELECT ladLocationId LocationId,
		ladGodownId GodownId, ladItemId ItemId , SUM(ladItemQty) qty
	FROM loiLocationArrivalDetails
		WHERE ladGodownId = @intGodownId
	AND ladItemId =  @intCurItemId
		AND ladCancel = 0
		GROUP BY ladLocationId, ladGodownId, ladItemId
	UNION ALL
		SELECT lidLocationId, lidGodownId, lidItemId, - SUM(lidItemQty)
	        FROM loiLocationIssueDetails
	WHERE lidGodownId =  @intGodownId
	        AND lidItemId =  @intcurItemId
		AND lidCancel = 0
	        GROUP BY lidLocationId, lidGodownId, lidItemId) a
	        GROUP BY LocationId, GodownId, ItemId
	        HAVING SUM(qty) <> 0 ) b,
	        LOiLocation
	WHERE b.LocationId = LOiLocation.lLocationId
	        AND b.GodownId = loiLocation.lGodownId		
		AND b.ItemId = @intCurItemId  -- for extra safety
		
		If @numStock > 0
		Begin
			
			INSERT INTO loiLocationIssueDetails
			(lidinterfaceid, lidgodownid, lidTransactionId, liddetailid,
			lidlocationid, liditemid, liditemqty, lidpackingtypeid,
			lidpakingqty, lidcancel, lidadjustment)
			VALUES
			(8008, @intGodownId, @intMergeId, @intIssueDetailId,
			@intLocationId, @intCurItemId,
			ABS(@numStock), 1, @numStock, 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		Else
		Begin
			INSERT INTO loiLocationArrivalDetails
			(ladinterfaceid, ladgodownid, ladtransid, laddetailid,
			ladlocationid, laditemid, laditemqty, ladpackingtypeid,
			ladpakingqty, ladcancel, ladadjustment)
			VALUES
			(8008, @intGodownId, @intMergeId, @intArrivalDetailId,
			@intLocationId, @intItemId,
			ABS(@numStock), 1, @numQuantitySum, 0, 1)
			
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		
		Fetch Next From CurMergedItems Into @intCurItemId
	End
	Close CurMergedItems
	Deallocate CurMergedItems
	Set NoCount Off
	Set ansi_warnings on
End
--------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownItemMerge]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownItemMerge]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------
-- Created By 	 : Kishore
-- Created Date  : 23/08/2003
-- Comments	 : (V3)
--                 Updates the godown stock
--                 for the transaction Item merging
--Verified By	 : Hariharan R (15/02/2003)
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateGodownItemMerge] (@intMergeId as int,
				    @intGodownId as int, @intCompanyId as int,
				    @strType as char(1))  AS
begin
	Declare @numQuantitySum as Numeric(18, 8)
	Declare @numQuantity as Numeric(18, 8)
	Declare @intCount as int
	Declare @intItemId as int	
	Declare @numItemCost as Numeric(18, 8)
	
	set @numQuantitySum = 0.0
	set @numItemCost = 0.0
	set @intCount = 0
	
	-- get the sum of quantity from loiMergeDetails
	SELECT @numQuantitySum = SUM(lgsdQty) FROM loiMergeDetails
		WHERE lgdId = @intMergeId
		AND lgdGodownId = @intGodownId
		AND lgdCompanyId = @intCompanyId
	-- get the item id from header and item cost
	SELECT @intItemId = lghItemId, @numItemCost = ItemRate
		FROM loiMergeHeader LEFT OUTER JOIN aItem
		ON loiMergeHeader.lghItemId = aItem.ItemId
		WHERE lghId = @intMergeId
		AND lghGodownId = @intGodownId
		AND lghCompanyId = @intCompanyId
	-- check if item exists in the stock table
	SELECT @intCount = COUNT(*) FROM moiGodownStock
		WHERE gsItemId = @intItemId
		AND gsGodownId = @intGodownId
	
	-- if this item id does not exist in stock table
	If @intCount = 0 AND @numQuantitySum <> 0
	Begin
		-- insert to stock
		INSERT INTO moiGodownStock
			(gsGodownID, gsLocationID, gsStockDate,
			gsShipmentID, gsItemID, gsOpeningStock,
			gsStock, gsOpeningBadStock, gsBadStock,
			gsItemCost) VALUES
			(@intGodownId, 1, GetDate(), 1, @intItemId,
			0, @numQuantitySum, 0, 0, @numItemCost)	
	End
	Else
	
	Begin
		-- update to stock
		UPDATE moiGodownStock
			SET gsStock = gsStock + @numQuantitySum
			WHERE gsItemId = @intItemId
			AND gsGodownId = @intGodownId
	End	
	-- set the item stock of all items in details table to 0
	UPDATE moiGodownStock
		SET gsStock = 0
		WHERE gsGodownId = @intGodownId
		AND gsItemId IN (SELECT lgdItemId FROM loiMergeDetails
				 WHERE lgdId = @intMergeId
			         AND lgdGodownId = @intGodownId
				 AND lgdCompanyId = @intCompanyId)
End
-------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownStockMerging]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownStockMerging]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create PROCEDURE [dbo].[spUpdateGodownStockMerging] (@intMergeId as int, @intCompanyId as int,@intLocationId as int) AS
Begin
Declare @intTemp as int,@intId as int,@strPrefix as VarChar(50),@strMaxNo as VarChar(50),@intMgdId as int,
@intMgdItemId as int,@numMgdCostPrice as numeric(18, 8),@intMgdDetailId as int,@numGsStock as numeric(18, 8)
,@intItemCount as int,@intMergeItemId int --===========<Ref No1>
Set NoCount On
-- This select query is necessary for running remotely
Select 1 Dummy1, 0 Dummy2
set @intTemp = 0
set @intItemCount=0   --===========<Ref No1>
-- check if main item id or detail item id exists in unprocessed quantity
SELECT @intTemp = COUNT(*) FROM vwQuantityUnProcessed WHERE ItemId IN (
	SELECT mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
UNION ALL
SELECT mgdItemId FROM aHqMergingDetails WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId
) AND LocationId = @intLocationId AND LocationType = ''G''
--===========<Ref No1>
SELECT @intMergeItemId = mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
--===========<Ref No1>
-- item ids exist in unprocessed quantity
If (@intTemp > 0)
Begin
	  -- check if the record already exists in header
	  SELECT @intTemp = COUNT(*) FROM loiMergeHeader WHERE lghRefMergeID = @intMergeId AND
		lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId
	  -- record does not exist in header -- so just insert it
	  If (@intTemp <= 0)
		begin
		  -- generate next id
		  SELECT @intId = isnull(max(lghId), 0) + 1 FROM loiMergeHeader WHERE lghGodownId = @intLocationId
			AND lghCompanyId = @intCompanyId
		  -- get prefix
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId AND InterfaceId = 1010
			AND GodownId = @intLocationId
--set @StrPrefix = @strPrefix + ''%''
		  -- get max no
		  SELECT @strMaxNo = isnull(max(convert(int, right(lghNo,len(lghNo) - len(@strPrefix)))), 0)
		  FROM loiMergeHeader WHERE lghCompanyId = @intCompanyId AND len(lghNo) > len(@strPrefix)
			AND isnumeric(isnull(right(lghNo, len(lghNo) - len(@strPrefix)), 0)) = 1
			AND substring(lghNo, 1, len(@strPrefix)) = @strPrefix AND lghGodownId = @intLocationId
		  If (@strMaxNo = ''0'')
			Begin
			  set @strMaxNo = @strPrefix + ''1''
			end
		  else
			begin
			  set @strMaxNo = @strPrefix + convert(varchar, (convert(int, @strMaxNo) + 1))
			end
-- generate next no
INSERT INTO loiMergeHeader(lghId, lghCompanyId, lghGodownId, lghNo, lghDate,lghRefMergeId,lghItemId,
			lghTransFinished,lghCancelled, lghUpdatetime, lghQty, lghNoOfRec,rowguid)
		  (SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 0, 0, GetDate(),
		    isnull(gsStock, 0), 0,newid() FROM aHqMergingHeader h LEFT OUTER JOIN VwinquiryGodownStock s
			ON h.mghItemId = s.gsItemId AND @intLocationId = s.gsGodownId WHERE mghId = @intMergeId
			AND mghCompanyId = @intCompanyId)
		End
	  Else -- get the merging id to insert into details
		Begin
		  SELECT @intId = lghId, @intLocationId = lghGodownId FROM loiMergeHeader
		  WHERE lghRefMergeID = @intMergeId AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId
		End
	  End
	Else
	  Begin           -- if no items in unprocessed quantity
		-- check if the record already exists in header
		SELECT @intTemp = COUNT(*) FROM loiMergeHeader WHERE lghRefMergeID = @intMergeId
		  AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId
-- record does not exist in header -- so just insert it
		If (@intTemp <= 0)
		Begin
		  -- generate next id
		  SELECT @intId = isnull(max(lghId), 0) + 1 FROM loiMergeHeader
		  WHERE lghGodownId = @intLocationId AND lghCompanyId = @intCompanyId
		  -- get prefix
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId
			AND InterfaceId = 1010 AND GodownId = @intLocationId
--set @StrPrefix = @strPrefix + ''%''
		  -- get max no
		  SELECT @strMaxNo = isnull(max(convert(int, right(lghNo,len(lghNo) - len(@strPrefix)))), 0)
		  FROM loiMergeHeader WHERE lghCompanyId = @intCompanyId AND len(lghNo) > len(@strPrefix)
			AND isnumeric(isnull(right(lghNo,len(lghNo) - len(@strPrefix)), 0)) = 1
			AND substring(lghNo, 1, len(@strPrefix)) = @strPrefix AND lghGodownId = @intLocationId
		  If (@strMaxNo = ''0'')
			Begin
			  set @strMaxNo = @strPrefix + ''1''
			End
		  Else
			Begin
			  set @strMaxNo = @strPrefix + convert(varchar,(convert(int, @strMaxNo) + 1))
			End
			
		  -- generate next no
INSERT INTO loiMergeHeader (lghId, lghCompanyId, lghGodownId, lghNo, lghDate,lghRefMergeId, lghItemId,
			lghTransFinished,lghCancelled, lghUpdatetime, lghQty, lghNoOfRec,rowguid)
		  (SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 1, 0, GetDate(),
		    isnull(gsStock, 0), 0,newid() FROM aHqMergingHeader h LEFT OUTER JOIN VwinquiryGodownStock s
			ON h.mghItemId = s.gsItemId AND @intLocationId = s.gsGodownId WHERE mghId = @intMergeId
			AND mghCompanyId = @intCompanyId)
		End
	  Else -- if header exists, update trans finished
		Begin
		  SELECT @intId = lghId, @intLocationId = lghGodownId FROM loiMergeHeader
		  WHERE lghRefMergeId = @intMergeId AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId
		  UPDATE loiMergeHeader SET lghTransFinished = 1 WHERE lghRefMergeId = @intMergeId
			AND lghCompanyId = @intCompanyId
		End
-- delete records from details if they exist  -- bcos play it safe, after all, triggers are involved
	  DELETE FROM loiMergeDetails WHERE lgdId = @intId AND lgdCompanyId = @intCompanyId AND lgdGodownId = @intLocationId
	  -- open the cursor
	  Declare CurGdnDetails Cursor For SELECT mgdId, mgdItemId, mgdCostPrice,mgdDetailId, isnull(gsStock, 0)
	  FROM aHqMergingDetails LEFT OUTER JOIN VwinquiryGodownStock ON mgdItemId = gsItemId
		AND @intLocationId = gsGodownId WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId ORDER BY mgdDetailId
	  Open CurGdnDetails
Fetch Next From CurGdnDetails Into @intMgdId, @intMgdItemId, @numMgdCostPrice, @intMgdDetailId,@numGsStock
While @@Fetch_Status = 0
		  Begin
			INSERT INTO loiMergeDetails (lgdId, lgdCompanyId, lgdGodownId, lgdItemId,lgsdQty, lgdDetailId,rowguid)
			VALUES (@intId, @intCompanyId, @intLocationId,@intMgdItemId, @numGsStock, @intMgdDetailId,newid())
			--==========================================<<Ref No1>>
			if @numGsStock > 0
			  begin
				SELECT @intItemCount = COUNT(*) FROM aGodownDetail
				WHERE  GodownID = @intLocationId and ItemID=@intMergeItemId
				If (@intItemCount <= 0)  		
				  begin
					insert into aGodownDetail values(@intLocationId,@intMergeItemId,0,0,0,0,NEWID())
				  end	
			  end		
			--==========================================<<Ref No1>>
			Fetch Next From CurGdnDetails InTo @intMgdId, @intMgdItemId, @numMgdCostPrice,@intMgdDetailId,@numGsStock
		  End
close CurGdnDetails
	  Deallocate CurGdnDetails
-- update no. of records
	  UPDATE loiMergeHeader SET lghNoOfRec = (SELECT COUNT(*) FROM loiMergeDetails WHERE lgdId = @intId AND
	    lgdCompanyId = @intCompanyId AND lgdGodownId = @intLocationId) WHERE lghId = @intId AND
	    lghCompanyId = @intCompanyId  AND lghGodownId = @intLocationId
		-- now update stock
	  Execute spUpdateGodownItemMerge @intId, @intLocationId, @intCompanyId, ''f''
	
	  -- and then update location wise stock
	  Execute spUpdateGodownLocationItemMerge @intId, @intLocationId, @intCompanyId --, ''f''
	End
Set NoCount Off
End
		---------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopLocationItemMerge]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopLocationItemMerge]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------
-- Created By 	 : Kishore
-- Created Date  : 24/08/2003
-- Comments	 : Created for updation of location stock
--                 at shops after item merging
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateShopLocationItemMerge] (
				    @intMergeId as int,
				    @intShopId as int,
				    @intCompanyId as int) AS
begin
	Declare @numQuantitySum as Numeric(18, 8)
	Declare @intCount as int
	Declare @intItemId as int	
	Declare @bitHasLocation as bit
	Declare @intLocationId as int
	Declare @intCurItemId as int
	Declare @numStock as Numeric(18, 8)
	Declare @intArrivalDetailId as int
	Declare @intIssueDetailId as int
	
	Set NoCount On
	Set ansi_warnings off
	
	-- get location status
	SELECT @bitHasLocation = LocationArrangement
		FROM aShops
		WHERE ShopId = @intShopId
	
	-- exit if the Shop has no locations
	If @bitHasLocation = 0
	Begin
		Return
	End
	
	set @numQuantitySum = 0.0
	set @intCount = 0
	
	-- get the sum of quantity from losMergeDetails
	SELECT @numQuantitySum = SUM(lsdQty) FROM losMergeDetails
		WHERE lsdId = @intMergeId
		AND lsdShopId = @intShopId
		AND lsdCompanyId = @intCompanyId
	-- get the item id from header and item cost
	SELECT @intItemId = lshItemId
		FROM losMergeHeader LEFT OUTER JOIN aItem
		ON losMergeHeader.lshItemId = aItem.ItemId
		WHERE lshId = @intMergeId
		AND lshShopId = @intShopId
		AND lshCompanyId = @intCompanyId
	
	Set @intArrivalDetailId = 1
	Set @intIssueDetailId = 1
	-- get the first location id to insert stock
	SELECT TOP 1 @intLocationId = lLocationId FROM losLocation
		WHERE lShopId = @intShopId
			
	INSERT INTO losLocationArrivalDetails
		(ladinterfaceid, ladShopid, ladtransid, laddetailid,
		ladlocationid, laditemid, laditemqty, ladpackingtypeid,
		ladpakingqty, ladcancel, ladadjustment)
		VALUES
		(8008, @intShopId, @intMergeId, @intArrivalDetailId,
		@intLocationId, @intItemId,
		@numQuantitySum, 1, @numQuantitySum, 0, 0)
		
	Set @intArrivalDetailId = @intArrivalDetailId + 1
	-- now make location stock of all details item to 0
	Declare curMergedItems Cursor For
		SELECT lsdItemId FROM losMergeDetails
		WHERE lsdId = @intMergeId
		AND lsdShopId = @intShopId
		AND lsdCompanyId = @intCompanyId
	Open curMergedItems
	Fetch Next From CurMergedItems Into @intCurItemId
	While @@Fetch_status = 0	
	Begin
		-- get current location stock ------sp_help loiLocationArrivalDetails
	SELECT @NumStock = qty
	FROM
	(SELECT LocationId, ShopId,
		ItemId, SUM(qty) qty
	        FROM
		(SELECT ladLocationId LocationId,
		ladShopId ShopId, ladItemId ItemId , SUM(ladItemQty) qty
	FROM losLocationArrivalDetails
		WHERE ladShopId = @intShopId
	AND ladItemId =  @intCurItemId
		AND ladCancel = 0
		GROUP BY ladLocationId, ladShopId, ladItemId
	UNION ALL
		SELECT lidLocationId, lidShopId, lidItemId, - SUM(lidItemQty)
	        FROM losLocationIssueDetails
	WHERE lidShopId =  @intShopId
	        AND lidItemId =  @intcurItemId
		AND lidCancel = 0
	        GROUP BY lidLocationId, lidShopId, lidItemId) a
	        GROUP BY LocationId, ShopId, ItemId
	        HAVING SUM(qty) <> 0 ) b,
	        LOsLocation
	WHERE b.LocationId = LOsLocation.lLocationId
	        AND b.ShopId = losLocation.lShopId		
		AND b.ItemId = @intCurItemId  -- for extra safety
		
		If @numStock > 0
		Begin
			
			INSERT INTO losLocationIssueDetails
			(lidinterfaceid, lidShopid, lidTransId, liddetailid,
			lidlocationid, liditemid, liditemqty, lidpackingtypeid,
			lidpakingqty, lidcancel, lidadjustment)
			VALUES
			(8008, @intShopId, @intMergeId, @intIssueDetailId,
			@intLocationId, @intCurItemId,
			ABS(@numStock), 1, @numStock, 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		Else
		Begin
			INSERT INTO losLocationArrivalDetails
			(ladinterfaceid, ladShopid, ladtransid, laddetailid,
			ladlocationid, laditemid, laditemqty, ladpackingtypeid,
			ladpakingqty, ladcancel, ladadjustment)
			VALUES
			(8008, @intShopId, @intMergeId, @intArrivalDetailId,
			@intLocationId, @intItemId,
			ABS(@numStock), 1, @numQuantitySum, 0, 1)
			
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		
		Fetch Next From CurMergedItems Into @intCurItemId
	End
	Close CurMergedItems
	Deallocate CurMergedItems
	Set NoCount Off
	Set ansi_warnings on
End
-----------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopItemMerge]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopItemMerge]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------
-- Created By 	 : Kishore
-- Created Date  : 23/08/2003
-- Comments	 : (V3)
--                 Updates the shop stock
--                 for the transaction Item merging (taken from v2)
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateShopItemMerge] (@intMergeId as int,
				    @intShopId as int, @intCompanyId as int,
				    @strType as char(1))  AS
Begin
	Declare @numQuantitySum as Numeric(18, 8)
	Declare @numQuantity as Numeric(18, 8)
	Declare @intCount as int
	Declare @intItemId as int	
	Declare @numItemCost as Numeric(18, 8)
	set @numQuantity = 0.0
	set @intCount = 0	
	set @numItemCost = 0.0
	
	-- get the sum of quantity from losMergeDetails
	SELECT @numQuantitySum = SUM(lsdQty) FROM losMergeDetails
		WHERE lsdId = @intMergeId
		AND lsdShopId = @intShopId
		AND lsdCompanyId = @intCompanyId
	-- get the item id from header and item cost
	SELECT @intItemId = lshItemId, @numItemCost = ItemRate
		FROM losMergeHeader LEFT OUTER JOIN aItem
		ON losMergeHeader.lshItemId = aItem.ItemId
		WHERE lshId = @intMergeId
		AND lshShopId = @intShopId
		AND lshCompanyId = @intCompanyId
	-- check if item exists in the stock table
	SELECT @intCount = COUNT(*) FROM mosShopStock
		WHERE ItemId = @intItemId
		AND ShopId = @intShopId
	
	-- if this item id does not exist in stock table
	If @intCount = 0 AND @numQuantitySum <> 0
	Begin
		-- insert to stock
		INSERT INTO mosShopStock
			(ShopID, StockDate,
			ShipmentID, ItemID, OpeningStock,
			Stock, OpeningBadStock, BadStock,
			ItemCostPrice) VALUES
			(@intShopId, GetDate(), 1, @intItemId,
			0, @numQuantitySum, 0, 0, @numItemCost)	
	End
	Else
	
	Begin
		-- update to stock
		UPDATE mosShopStock SET Stock = Stock + @numQuantitySum
		WHERE ItemId = @intItemId AND ShopId = @intShopId
	End	
	-- set the item stock of all items in details table to 0
	UPDATE mosShopStock SET Stock = 0 WHERE ShopId = @intShopId
	AND ItemId IN (SELECT lsdItemId FROM losMergeDetails WHERE lsdId = @intMergeId
	AND lsdShopId = @intShopId AND lsdCompanyId = @intCompanyId)
End
---------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockMerging]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockMerging]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create PROCEDURE [dbo].[spUpdateShopStockMerging] (@intMergeId as int, @intCompanyId as int,@intLocationId as int) AS
Begin
Declare @intTemp as int,@intId as int,@strPrefix as VarChar(50),@strMaxNo as VarChar(50),@intMgdId as int,
@intMgdItemId as int,@numMgdCostPrice as numeric(18, 8),@intMgdDetailId as int,@numGsStock as numeric(18, 8)
,@intItemCount as int,@intMergeItemId int --===========<Ref No1>
		
Set NoCount On
set @intTemp = 0
set @intItemCount=0   --===========<Ref No1>
-- select 2 cols. It is neccessary for running remotely
select 1, 0
-- check if main item id or detail item id exists in unprocessed quantity
SELECT @intTemp = COUNT(*) FROM vwQuantityUnProcessed WHERE ItemId IN (
	SELECT mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
UNION ALL
SELECT mgdItemId FROM aHqMergingDetails WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId
) AND LocationId = @intLocationId AND LocationType = ''S''
--===========<Ref No1>
SELECT @intMergeItemId = mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
--===========<Ref No1>
-- item ids exist in unprocessed quantity
If (@intTemp > 0)
Begin
	  set @intTemp = 0
-- check if the record already exists in header
	  SELECT @intTemp = COUNT(*) FROM losMergeHeader WHERE lshRefMergeID = @intMergeId
		AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
-- record does not exist in header so just insert it
	  If (@intTemp <= 0)
		begin
		  -- generate next id
		  SELECT @intId = isnull(max(lshId), 0) + 1 FROM losMergeHeader WHERE lshShopId = @intLocationId
			AND lshCompanyId = @intCompanyId
		
		  -- get prefix
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId
			AND InterfaceId = 1910 AND ShopId = @intLocationId
		  -- get max no
		  SELECT @strMaxNo = isnull(max(convert(int, right(lshNo,len(lshNo) - len(@strPrefix)))), 0)
		  FROM losMergeHeader WHERE lshCompanyId = @intCompanyId AND len(lshNo) > len(@strPrefix)
			AND substring(lshNo, 1, len(@strPrefix)) = @strPrefix AND lshShopId = @intLocationId
			AND isnumeric(isnull(right(lshNo, len(lshNo) - len(@strPrefix)), 0)) = 1
		  If (@strMaxNo = ''0'')
			Begin
			  set @strMaxNo = @strPrefix + ''1''
			end
		  else
			begin
			  set @strMaxNo = @strPrefix + convert(varchar, (convert(int, @strMaxNo) + 1))
			end
-- generate next no
INSERT INTO losMergeHeader(lshId, lshCompanyId, lshShopId, lshNo, lshDate,lshRefMergeId, lshItemId,
			lshTransFinished,lshCancelled, lshUpdatetime, lshQty, lshNoOfRec,rowguid)
		  (
			SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 0, 0, GetDate(),
			  isnull(Stock, 0), 0 ,newID()
			FROM aHqMergingHeader h LEFT OUTER JOIN vwInquiryShopStock s ON h.mghItemId = s.ItemId
			  AND @intLocationId = s.ShopId
			WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
		  )
		End
	  Else -- get the merging id to insert into details
		Begin
		  SELECT @intId = lshId, @intLocationId = lshShopId FROM losMergeHeader
		  WHERE lshRefMergeID = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
		End
	End
Else
	Begin           -- if no items in unprocessed quantity
		-- check if the record already exists in header
	  SELECT @intTemp = COUNT(*) FROM losMergeHeader
	  WHERE lshRefMergeID = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
-- record does not exist in header  -- so just insert it
	  If (@intTemp <= 0)
		Begin
		-- generate next id
		  SELECT @intId = isnull(max(lshId), 0) + 1 FROM losMergeHeader
		  WHERE lshShopId = @intLocationId AND lshCompanyId = @intCompanyId
		
		-- get prefix
		  SELECT @strPrefix = Prefix FROM aPrefix
		  WHERE CompanyId = @intCompanyId AND InterfaceId = 1910 AND ShopId = @intLocationId
		-- get max no
		SELECT @strMaxNo = isnull(max(convert(int, right(lshNo,len(lshNo) - len(@strPrefix)))), 0)
		FROM losMergeHeader
		WHERE lshCompanyId = @intCompanyId AND len(lshNo) > len(@strPrefix) AND isnumeric(isnull(right(lshNo,
		  len(lshNo) - len(@strPrefix)), 0)) = 1 AND substring(lshNo, 1, len(@strPrefix)) = @strPrefix
		  AND lshShopId = @intLocationId
If (@strMaxNo = ''0'')
		  Begin
			set @strMaxNo = @strPrefix + ''1''
		  End
		Else
		  Begin
			set @strMaxNo = @strPrefix + convert(varchar,(convert(int, @strMaxNo) + 1))
		  End
-- generate next no
INSERT INTO losMergeHeader(lshId,lshCompanyId,lshShopId,lshNo,lshDate,lshRefMergeId,lshItemId,
		  lshTransFinished,lshCancelled, lshUpdatetime, lshQty, lshNoOfRec,rowguid)
		(SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 1, 0, GetDate(),
		  isnull(Stock, 0), 0 ,newID() FROM aHqMergingHeader h
		  LEFT OUTER JOIN vwinquiryShopStock s ON h.mghItemId = s.ItemId AND @intLocationId = s.ShopId
		WHERE mghId = @intMergeId  AND mghCompanyId = @intCompanyId)
	  End
Else -- if header exists, update trans finished
Begin
		SELECT @intId = lshId, @intLocationId = lshShopId FROM losMergeHeader
		WHERE lshRefMergeId = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
		
		UPDATE losMergeHeader SET lshTransFinished = 1 WHERE lshRefMergeId = @intMergeId
		AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
	  End
-- delete records from details if they exist bcos play it safe, after all, triggers are involved
	DELETE FROM losMergeDetails WHERE lsdId = @intId AND lsdCompanyId = @intCompanyId AND lsdShopId = @intLocationId
	-- open the cursor
	Declare CurShopDetails Cursor For
	  SELECT mgdId, mgdItemId, mgdCostPrice,mgdDetailId, isnull(Stock, 0)
	  FROM aHqMergingDetails LEFT OUTER JOIN vwinquiryShopStock ON mgdItemId = ItemId AND @intLocationId = ShopId
	  WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId ORDER BY mgdDetailId
	Open CurShopDetails
Fetch Next From CurShopDetails Into  @intMgdId, @intMgdItemId, @numMgdCostPrice, @intMgdDetailId,@numGsStock
	  While @@Fetch_Status = 0
		Begin
		  INSERT INTO losMergeDetails (lsdId, lsdCompanyId, lsdShopId, lsdItemId,lsdQty, lsdDetailId,rowguid)
		  VALUES (@intId, @intCompanyId, @intLocationId,@intMgdItemId, @numGsStock, @intMgdDetailId,newID())
		  --==========================================<<Ref No1>>
		  if @numGsStock > 0
		  begin
		    SELECT @intItemCount = COUNT(*) FROM aShopItemDetail
			WHERE  ShopId = @intLocationId and ItemID=@intMergeItemId
			If (@intItemCount <= 0)  		
			begin
				insert into aShopItemDetail values(@intLocationId,@intMergeItemId,0,0,0,null,0,0,NEWID())
			end
		  end		
		  --==========================================<<Ref No1>>
		  Fetch Next From CurShopDetails InTo @intMgdId,@intMgdItemId,@numMgdCostPrice,@intMgdDetailId,@numGsStock
		End
close CurShopDetails
	Deallocate CurShopDetails
	-- update no. of records
	UPDATE losMergeHeader SET lshNoOfRec = (SELECT COUNT(*) FROM losMergeDetails
WHERE lsdId = @intId AND lsdCompanyId = @intCompanyId AND lsdShopId = @intLocationId)
WHERE lshId = @intId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId
	-- now updat the stock
	Execute spUpdateShopItemMerge @intId, @intLocationId, @intCompanyId, ''f''
	-- now updat the location stock
	Execute spUpdateShopLocationItemMerge @intId, @intLocationId, @intCompanyId--, ''f''
End
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLocationMerging]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLocationMerging]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------
-- Created by  : Kishore
-- Created on  : 23/08/2003
-- Comments    : For updating merging details in locations
--               Called from PosMain and InventoryMain at startup (taken from v2)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spLocationMerging] (@intLocationId as int, @strLocationType as VarChar) AS
Begin
	Declare @intDetailsInHeader as int
	Declare @intActualDetails as int
	Declare @intMergeId as int
	Declare @intCompanyId as int
	Declare @intTransFinished as int	
	-- if it is not the local server in hq	
	If @@ServerName <> (SELECT MainServerName FROM aPackageSettings)
	Begin	
		If @strLocationType = ''G''
		Begin
			Declare curLocationDetails Cursor For
				SELECT lghRefMergeId FROM loiMergeHeader
				WHERE lghTransFinished = 0
				AND lghCancelled = 0
				AND lghGodownId = @intLocationId
			Open curLocationDetails
			Fetch Next From curLocationDetails Into @intMergeId	
			While @@Fetch_Status = 0
			Begin
				Execute spUpdateGodownStockMerging @intMergeId,
							@intCompanyId, @intLocationId
					
				Fetch Next From curLocationDetails Into @intMergeId										
			End
		End
		Else	-- if it is shop
		Begin
			Declare curLocationDetails Cursor For
				SELECT lshRefMergeId FROM losMergeHeader
				WHERE lshTransFinished = 0
				AND lshCancelled = 0
				AND lshShopId = @intLocationId
			Open curLocationDetails
			Fetch Next From curLocationDetails Into @intMergeId				
			While @@Fetch_Status = 0
			Begin
				Execute spUpdateShopStockMerging @intMergeId,
						@intCompanyId, @intLocationId
				Fetch Next From curLocationDetails Into @intMergeId										
			End
		End
		Close curLocationDetails
		Deallocate curLocationDetails
	End
End
--------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Crm_Report_Quotation]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_Crm_Report_Quotation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Regin
-- Create date: 09-04-2010
-- Description: To report CRM Quotation
-- Last Modified By : MANUNADH.U on 15-09-2010
-- =============================================
-- Modified By Regin On 21-10-2010
-- Modification: Added additional fields
-- brand, ModelNo, Attribute1, Attribute2, OriginCountryName, ItemImage1
-- =============================================
-- Modified By manu On 02-11-2010
-- Modification: Added ItemImage from the table crmItem
-- =============================================   sp_Crm_Report_Quotation  1,2
create PROCEDURE [dbo].[sp_Crm_Report_Quotation] -- 1,3
	@intCompanyId int,
	@intQuotationId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
select
	Quotationid,BillAccountId,CustomerName,BillAddress,BillCity,BillPostalCode,BillState,BillCountry,QuotationNo
	,PurchaseOrederNo,OrginalPoDate,ValidUntil,SlOrder,qd.ItemId,i.ItemCode,qd.ItemDescription --i.ItemDescription
	,qd.Qty,Price,PackingTypeName,q.CreateDate	,i.brand,i.ModelNo,i.Attribute1,i.Attribute2,CountryName OriginCountryName
	,case when qd.IsCrmItem=1 then ci.ItemImage else ii.ItemImage1 end [ItemImage]
	,cu.Symbol CurrencySymbol
from crmQuotation q
	left outer join crmQuotationDetails qd  on q.QutotationId = qd.Quotationid
	left outer join dbo.aCustomerMaster c on q.BillAccountId=c.CustomerId
	left outer join aItem i on qd.ItemId=i.ItemId
	left outer join aPackingType p on qd.PackingtypeId=p.PackingTypeID
	left outer join aCountryMaster co on i.OrginCountryID=co.CountryID
	left outer join aItemImage ii on i.ItemId=ii.ItemId
	left outer join crmItem ci on qd.ItemDescription=ci.ItemDescription
left outer join aCurrencyMaster cu on q.CurrencyId=cu.CurrencyID
where
	q.CompanyId=@intCompanyId   and Quotationid=@intQuotationId
END' 
END
GO
/****** Object:  View [dbo].[currencyexchangerate]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[currencyexchangerate]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.currencyexchangerate    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 17/11/2001 9:21:14 PM ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.currencyexchangerate    Script Date: 09/03/2001 02:32:25 ******/
CREATE view [dbo].[currencyexchangerate] as
select eh.companyid, exchangedate, currencyid, buyingrate, sellingrate, averagerate from exchangerate eh, exchangeratedetail ed where
eh.exchangeid = ed.exchangeid and eh.companyid = ed.companyid'
GO
/****** Object:  View [dbo].[vwLeadtime]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLeadtime]'))
EXEC dbo.sp_executesql @statement = N'
-- Comments : For Lead Time Report
--      : Venkitesh 15/07/2004
--      : Modified By Aneesh 15-12-2004
CREATE VIEW [dbo].[vwLeadtime] as
select Top 100 Percent a.Ltimeid,a.LtimeCompanyid,b.LtimeNoofDays,b.LtimeDetailNo,
a.LtimeDate,c.Ldivisionid,c.LdivisionName,
d.Lstageid,d.LstageName,e.ItemID,e.ItemDescription,
a.LtimeSupplierId,a.LtimeDepartmentid,
a.LtimeRemarks,a.LtimePreparedBy,isnull(VendorName,'''')vendorname, Ltimestageid
from ltimedetail b,  leadtimedivision c,leadtimestage d, ltimeheader a
left outer join aitem e on  a.LtimeItemid=itemid   left outer join avendormaster on
vendorid =LtimeSupplierId and CompanyID=a.LtimeCompanyid
where   a.ltimeid=b.ltimeid and
LtimeDivisionId=c.Ldivisionid and
Ltimestageid=Lstageid and
c.LDivisionCompanyid=a.LtimeCompanyid and
d.LStageCompanyid=a.LtimeCompanyid
Order By b.LtimeDetailNo'
GO
/****** Object:  StoredProcedure [dbo].[spULshopTrOut]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopTrOut]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on  : 17/07/2002
-- Created by : leo
--------------------------------------
-- Modified on      : 15/04/2003
-- Modified by      : leo
-- Comment          : added the tohtype filter to fetch only transfer outs
--------------------------------------
-- Modified on      : 13/01/2011
-- Modified by      : Nidheesh P V
-- Comment          : added @strzerorate
--------------------------------------
CREATE proc [dbo].[spULshopTrOut] @intCompanyID as int, @intshopid as int as
begin
Declare @intJournalID as int
Declare @intJournalDetailID as int
Declare @intFinancialID as int
Declare @dttDate as datetime
Declare @strtNo as varchar(50)
Declare @inttid as int
Declare @strRemarks as varchar(250)
Declare @numtotalValue as numeric(18,2)
Declare @intinventoryaccid as int
declare @intcomcurid as int
declare @inttodepid as int
declare @dtutime as datetime
declare @intFailcount as int
declare @intstocktransferaccid  as int
declare @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)
/* 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 @intInventoryaccid = inventoryid, @intstocktransferaccid =
stocktransfercontrolacc,@strzerorate = substring(isnull(futurevc,''''),1,1)
from apackagesettings
where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
Declare trincur cursor for
SELECT ToHID, ToHDate, ToHNO, ToHremarks, tohdepartmentid todep, updatetime,
tohConExRate, tohDepExRate, tohExchangeRates
FROM mestransferoutheader tinh
WHERE  ToHcancelled =0 and ToHPosted =0 and ToHShopid = @intshopid and ToHTransFinished = 1
and tohtype =''TO''
open trincur
fetch next FROM trincur into @inttid , @dttdate, @strtno, @strremarks, @inttodepid,
@dtutime, @numConExRate, @numDepExRate, @strExRates
while @@Fetch_status = 0
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 @dttdate 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 mestransferoutdetail , aitem where
todid= @inttid and todshopid = @intshopid and toditemid = itemid
and (todcostprice=null or todcostprice=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  -- item rate=0 check hari 011213
begin
-- to update the item rate to the gadcostprice
update mestransferoutdetail  set todcostprice = itemrate from
aitem where (todcostprice=null or todcostprice=0) and todid= @inttid
and todshopid = @intshopid and toditemid = itemid
SELECT @numTotalValue = sum(TODissuedGoodQty * ToDCostprice)
FROM mestransferoutdetail   WHERE TodShopid  = @intshopid and
TodID = @inttid group by TodShopid, TodID
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dttDate, @strtNo,
@strremarks, @intFinancialID,''strout'', @intcomCurID,@dttdate, @dtutime)
set @intJournalDetailID = 1
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intInventoryaccid,
@numTotalValue * @numConExRate,
@numtotalvalue,
@numtotalvalue * @numDepExRate,
@inttoDepID )
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTotalValue,
@numAaccAmt output
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intstocktransferaccid,
@numTotalValue * @numConExRate,
@numaAccAmt,
@numtotalvalue * @numDepExRate,
@inttoDepId)
/* mark the record as postED */
update mestransferoutheader set ToHPosted = 1 WHERE tohshopid =
@intshopid and ToHID = @inttid
set @intJournalID = @intJournalID + 1
end -- item rate=0 check hari 011213
fetch next FROM trincur into @inttid, @dttdate, @strtno, @strremarks,
@inttodepid, @dtutime, @numConExRate, @numDepExRate, @strExRates
end
Close trincur
Deallocate trincur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlShopTrIn]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopTrIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on : 15/04/2003
-- Modified by	    : leo
-- comments	    : inclued the type TIHType
CREATE proc [dbo].[spUlShopTrIn] @intCompanyID as int, @intshopid as int as
begin
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dttDate as datetime
	Declare @strtNo as varchar(50)
	Declare @inttid as int
	Declare @strRemarks as varchar(250)
	Declare @numtotalValue as numeric(18,2)
	Declare @intinventoryaccid as int
	declare @intcomcurid as int
	declare @inttodepid as int
	declare @dtutime as datetime
	declare @intFailcount as int
	declare @intstocktransferaccid  as int
	declare @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)
	/*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 @intInventoryaccid = inventoryid, @intstocktransferaccid =
		stocktransfercontrolacc,@strzerorate = substring(isnull(futurevc,''''),1,1)
		from apackagesettings where companyid = @intcompanyid
	set @intJournalID = @intJournalID + 1
	
	Declare trincur cursor for
		SELECT TIHID, TIHDate, TIHNO, TIHremarks, tihdepartmentid todep, updatetime,
		tihConExRate, tihDepExRate, tihExchangeRates
		FROM LOSTransferinheader tinh
		WHERE  TIHcancel =0 and TIHPosted =0 and TIHShopid = @intshopid
		and TIHTransFinished = 1 and TIHType = ''TI''
	open trincur
	fetch next FROM trincur into @inttid , @dttdate, @strtno, @strremarks, @inttodepid,
		@dtutime, @numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0
	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 @dttdate 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 lostransferindetail, aitem where
			tidid= @inttid and tidshopid = @intshopid and tiditemid = itemid
			and (tidcostprice=null or tidcostprice=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 	-- item rate=0 check hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update lostransferindetail set tidcostprice = itemrate from
				aitem where (tidcostprice=null or tidcostprice=0) and tidid= @inttid
				and tidshopid = @intshopid and tiditemid = itemid
			SELECT @numTotalValue = sum(TIDrecievedgoodqty * TIDCostprice)
				FROM LOSTransferindetail WHERE TIdShopid  = @intshopid and
				TIdID = @inttid group by TIdShopid, TIdID
			insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
				referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
				(@intJournalID, @intCompanyID, @dttDate, @strtNo,
				@strremarks, @intFinancialID,''strin'', @intcomCurID,@dttdate, @dtutime)
			set @intJournalDetailID = 1		
			/* debiting the inventory account with the full */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,
				DepAmount, departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intInventoryaccid, @numTotalValue * @numConExRate,
				@numtotalvalue,
				@numTotalValue * @numDepExRate, @inttoDepID )		
			set @intJournalDetailID = @intJournalDetailID + 1		
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intStockTransferAccId
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numTotalValue,
					@numAaccAmt output
			/* debiting the inventory account with the full */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,
				DepAmount, departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@intstocktransferaccid , @numTotalValue * @numConExRate,
				@numaAccAmt,
				@numTotalValue * @numDepExRate, @inttoDepID)			
			/* mark the record as postED */
			update LOSTransferinheader  set TIHPosted = 1 WHERE tihshopid = @intshopid
				and TIHID = @inttid
			set @intJournalID = @intJournalID + 1
		end -- item rate=0 check hari 011213
		fetch next FROM trincur into @inttid, @dttdate, @strtno, @strremarks,
			@inttodepid, @dtutime, @numConExRate, @numDepExRate, @strExRates
	end
	Close trincur
	Deallocate trincur	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpGroupLevelOrdering]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpGroupLevelOrdering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
--SpGroupLevelOrdering 1,1
--Created By   : dheena , Hariharan, Hariharan
--Created Date : 24/05/2004, 27/05/2004, 31/05/2004
--Purpose      : Groupwise display, corrected depid wise filteration
-- modified : venkitesh 28/05/2004
--Purpose      : Added accountid , Given condition for removing unnecessary groups
-----------------------------------------------------------------------------------
Ref No   : 01
Altered By  : Shine Das
Referer Task No : M_022 from ''Magnolia Issue Tracking System'' ExcelSheet
Purpose   : In this SP there was a conditions written to filter active accounts only.
But in BalanceSheet it is not required. So it commented.
-----------------------------------------------------------------------------------
*/
CREATE Procedure [dbo].[SpGroupLevelOrdering]( @intCompanyID as int,
@intDepartmentId as int=0) as
Begin
Declare
@intGroupID as int,
@intMaxGroupID as int,
@intRowCount as int,
@intCount as int,
@IntHcount as int,
@intMaxGid as int,
@IntScount as int,
@intS1Count as int
set nocount on
CREATE TABLE #Temp1(T1GID int)
CREATE TABLE #Temp2(T2GID int,T2PGId int)
CREATE TABLE #Result (GroupID  int,OrderID int,OrderNo  int identity(1,1))
CREATE TABLE #SubResult (GroupID  int,OrderID int,OrderNo  int identity(1,1))
CREATE TABLE #Stack(GroupID int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
--header Only insert
Insert into #temp1
Select
Groupid from
(Select
GroupDesc, Case AccountType
When ''A'' then 1 when ''L'' then 2 when ''I'' then 3
when ''E'' then 4 end TypeOrder, LevelCode, ParentGroupId,
GroupId,AccountType
from
aGroupMaster
where parentgroupid is null and levelcode=1)
GroupMaster order by TypeOrder, Levelcode, GroupId
Insert into #temp2
SELECT groupid,Parentgroupid FROM aGroupMaster
Select @intcount=Count(*) from #temp1
--Check Headergroupid wise
Select @IntHcount=count(*) from #temp1
While @IntHcount >0
Begin
Select Top 1 @intGroupid=T1Gid from #temp1
Insert into #Result(GroupID,OrderID) values(@intGroupid,@intGroupid)
select @IntScount=count(*) from #temp2
Where T2PGid=@intGroupid
While @IntScount>0
Begin
select @intMaxGid=Max(T2Gid) from #temp2
Where T2PGid=@intGroupid
Select @intS1Count=count(*) from #temp2
Where T2PGid=@intMaxGid
If @intS1Count =0
Begin
Insert into #SubResult(GroupID,OrderID)values(@intMaxGid,@intGroupid)
Delete from #temp2 where T2GId=@intMaxGid
End
Else
Begin
While @intS1Count>0
Begin
select @intMaxGid=Max(T2Gid) from #temp2
Where T2PGid=@intMaxGid
if (select count(*) from #temp2  Where T2PGid=@intMaxGid)=0
Begin
Insert into #SubResult(GroupID,OrderID)values(@intMaxGid,@intGroupid)
Delete from #temp2 where t2gid=@intMaxGid
End
Select @intS1Count=count(*) from #temp2
Where T2PGid=@intMaxGid
End
End
--Delete from #temp2 where T2GId=@intGroupid
select @IntScount=count(*) from #temp2
Where T2PGid=@intGroupid
End
insert into #Result(GroupID,OrderID)
select GroupID,OrderID from #SubResult order by orderno desc
delete from #SubResult
Delete from #temp1 where T1GID=@intGroupid
Select @IntHcount=count(*) from #temp1
End
if @intDepartmentId=0
Begin
insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
select
a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,b.parentGroupid
,a.orderno,b.levelcode,'''' depId,'''' DepName, 0, c.AccountId, AccountType
from
#result a , aGroupmaster b left outer join aaccountmaster c on
----b.groupid=c.groupid and c.active=1  and b.CompanyID=c.CompanyID  --- Ref No : 01
b.groupid=c.groupid and b.CompanyID=c.CompanyID
where a.groupid=b.groupid
and  b.CompanyID=@intcompanyid
Group by a.groupid,c.AccountId, c.AccountCode,c.AccountDesc,b.groupdesc,
b.parentGroupid,a.orderno,b.levelcode, c.AccountId, AccountType
order by a.orderno asc
End
Else
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, c.AccountId, AccType)
select
a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,b.parentGroupid
,a.orderno,b.levelcode,d.departmentid depId,d.DepartmentName DepName, 0, c.AccountId, AccountType
from
#result a , aGroupmaster b left outer join aaccountmaster c on
--b.groupid=c.groupid and c.active=1 and b.CompanyID=c.CompanyID    --- Ref No : 01
b.groupid=c.groupid and b.CompanyID=c.CompanyID
left Outer join (Select * from
aDeptAccounts where daCompanyId = @intCompanyId and
daDepartmentid = @intDepartmentId) aDeptAccounts on
c.AccountID=daAccountID and
c.CompanyID=daCompanyID
left Outer join adepartmentmaster d on
daCompanyId=d.CompanyID and daDepartmentID = d.DepartmentID
and daDepartmentID  = @intDepartmentId
where a.groupid=b.groupid and  b.CompanyID=@intcompanyid
and (daDepartmentID = @intDepartmentid or AccountDesc is null)
Group by a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,
b.parentGroupid,a.orderno,b.levelcode ,d.departmentid,d.DepartmentName,
c.AccountId, AccountType
order by a.orderno asc
End
drop table #result
drop table #Stack
drop table #temp1
drop table #temp2
Drop table #SubResult
set @intGroupId = 0
set @IntHcount = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @intGroupId = GroupId From #FilteredResult where Checked = 0
Order by OrderNo Desc
While @intGroupId <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #FilteredResult where
((AccountDesc is not Null and Groupid= @intGroupId)
or ParentGroupid = @intGroupId)
if @intCount = 0
Delete from #FilteredResult where GroupId = @intGroupId
else
Update #FilteredResult set Checked = 1 where Groupid = @intGroupId
Set @intGroupId  = 0
set @IntHcount = @IntHcount + 1
Select top 1 @intGroupId = GroupId From #FilteredResult where Checked = 0
Order by OrderNo Desc
End
Select * from #FilteredResult
Drop Table #FilteredResult
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGodownExpiryStock]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownExpiryStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on  : 19/01/2003
-- Modified by       : Kishore
-- Comments          : Added fields item code, godown name, expiry date so that this sp
--                     can be used in rptGodownExpiry report. (17/12/2003)
--                   : Added UnitCode
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spGodownExpiryStock]
	@intGodownId 		as int = 0,
	@dtExpiryDate	        as varchar(10) = '''', -- from date
	@intItemID 		as int = 0,
@OpeningStockYesNo 	as bit,
@NegativeStockYesNo 	as bit,
@dtExpiryDateTo         as Varchar(10) = '''',
@strBrand               as Varchar(100) = '''',
@strCategoryIds         as Varchar(100) = ''''
AS  -- to date
Begin
Declare @strGodownName as Varchar(250)
declare @strSql as nvarchar(4000)
SELECT @strGodownName = GodownName FROM aGodown
WHERE GodownId = @intGodownId
set @strSql=N''select
		eadGodownID, eaditemid, sum(quantity) quantity,
		itemDescription,CategoryNameDescription, itemrate,
s.ItemCode, '' + Char(39) + @strGodownName + Char(39) + '' GodownName,
s.ExpiryDate, Min(UnitCode) UnitCode,part_code
	from
		(select
			ea.eadGodownID, ea.eaditemid, sum(ea.eaditemqty) quantity,
			case 	when coalesce(cl.ColorName,"") + coalesce(sz.SizeName,"")="" then it.ItemDescription
				when coalesce(cl.ColorName,"") ="" then it.ItemDescription + " - " + cl.ColorName
				when coalesce(sz.SizeName,"") ="" then it.ItemDescription + " - " + sz.SizeName
				else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
			end 	ItemDescription,itc.CategoryNameDescription,
			sz.SizeName, cl.ColorName, it.itemrate, it.ItemCode,
eadexpirydate ExpiryDate, Min(u.UnitCode) UnitCode,part_code
		from
			loiExpiryarrivaldetails ea, aItem it, aColor cl,
aSize sz, aItemCategory itc, aUnit u
		where
			ea.eaditemid = it.ItemID and it.ItemCategoryID = itc.ItemCategoryID and
			it.ColorId *= cl.ColorID and it.SizeID *= sz.SizeID and
			ea.eadcancel = 0
and it.UnitsId = u.UnitId''
		if @intGodownId <> 0
			set @strSql = @strSql + N'' and ea.eadGodownID='' + convert(varchar(10),@intGodownId)
		if @OpeningStockYesNO = 1
			set @strSql = @strSql + N'' and ea.eadInterfaceID = 555''
		if @dtExpiryDate <> ''''
			set @strSql = @strSql + " and ea.eadExpiryDate >= ''" + @dtExpiryDate + "''"
if @dtExpiryDateTo <> ''''
set @strSql = @strSql + " and ea.eadExpiryDate <= ''" + @dtExpiryDateTo + "''"
		if @intItemID <> 0
			set @strSql = @strSql+ N'' and ea.eaditemid = '' + convert(varchar(10), @intItemID)
	set @strSql = @strSql + N'' group by
		ea.eadGodownID, ea.eaditemid, it.ItemDescription,
		itc.CategoryNameDescription, sz.SizeName, cl.ColorName,
it.itemrate, it.ItemCode, eadexpirydate,part_code
union all ''
	set @strSql = @strSql+ N''select
		ei.eidGodownID, ei.eiditemid, -sum(ei.eiditemqty) quantity,
		case 	when coalesce(cl.ColorName,"") + coalesce(sz.SizeName,"")="" then it.ItemDescription
			when coalesce(cl.ColorName,"") ="" then it.ItemDescription + " - " + cl.ColorName
			when coalesce(sz.SizeName,"") ="" then it.ItemDescription + " - " + sz.SizeName
			else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
		end 	ItemDescription, itc.CategoryNameDescription,
		sz.SizeName, cl.ColorName, it.itemrate, it.ItemCode,
eidExpiryDate, Min(UnitCode) UnitCode,part_code
		from
			loiExpiryIssuedetails ei, aItem it, aColor cl,
aSize sz, aItemCategory itc, aUnit u
		where
			ei.eiditemid = it.ItemID
and it.ItemCategoryID = itc.ItemCategoryID
and it.ColorId *= cl.ColorID
and it.SizeID *= sz.SizeID
and ei.eidcancel = 0
and it.UnitsId = u.UnitId''
	if @intGodownId <> 0
		set @strSql = @strSql+ N'' and ei.eidGodownID='' + convert(varchar(10),@intGodownId)
	if @OpeningStockYesNO = 1
		set @strSql = @strSql+ N'' and ei.eidinterfaceid=555''
	if @dtExpiryDate <> 0
		set @strSql = @strSql+ " and ei.eidExpiryDate >= ''" + @dtExpiryDate + "''"
if @dtExpiryDateTo <> ''''
set @strSql = @strSql+ " and ei.eidExpiryDate <= ''" + @dtExpiryDateTo + "''"
	if @intItemID <> 0
		set @strSql = @strSql+ N'' and ei.eiditemid='' + convert(varchar(10),@intItemID)
set @strSql = @strSql+ N'' group by
	ei.eidGodownID, ei.eiditemid, it.ItemDescription,
	itc.CategoryNameDescription, sz.SizeName, cl.ColorName,it.itemrate, it.ItemCode, eidExpiryDate,part_code ) s
	group by eadGodownID, eaditemid, itemDescription,
	CategoryNameDescription, SizeName, ColorName, itemrate, s.ItemCode, s.ExpiryDate,s.part_code''
if @NegativeStockYesNo = 1
Begin
	    set @strSql = @strSql+ N'' having sum(quantity) < 0''
End
Else
Begin
Set @strSql = @strSql + N'' having sum(quantity) <> 0''
End
--print @strSql
exec sp_executesql @strSql
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReverseOldCostPrice]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseOldCostPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  on 	: 05/08/2003
--Created  by 	: R Harikrishnan
--Comments	: To Reverty all the updated cost prices in a detail table according to the
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--		: Header table column name
-----------------------------------------------------------------------------------------
CREATE Procedure [dbo].[spReverseOldCostPrice]
	@intCompanyID 		as int,			--The companyID (mandatory)
	@strTableName 		as varchar(250), 	--The name of the table(Mandatory)
	@strDetailTableName 	as varchar(250), 	--The name of the Detail table(Mandatory)
	@strWherecondition	as varchar(250),	--The where condition (Optional)
	@strCostPriceColName 	as varchar(250),	--The consolidation exchange rate
							--column name of the strTablename
	@strPKColName1	 	as varchar(250),	--The first primary column name of the
							--strTablename (shopID,companyID,GodownID)
							--(Mandatory)
	@strPKColName2	 	as varchar(250),	--The second primary column name of the
							--strTablename (Mandatory)
	@strPKColName3	 	as varchar(250),	--The third primary column name of the
							--strTablename (Optional)
	@strCustIDColName 	as varchar(250),	--The customerID column name of
							--strTablename (Optional)
	@strAccIDColName 	as varchar(250),	--The AcountID column name of
							--strTablename (Optional)
	@strAccIDValue	 	as varchar(250),	--The account value of the transaction
							--strTablename (InventoryID)(Optional)
	@strPKType 		as char(1)		--''S'' for ShopID
							--''G'' for GodownID
					  		--''C'' for CompanyID
as
begin
	--	Commented for testing purpose
	--	set @intCompanyID=1
	--	set @strTableName=''losPosHeader h, losPosDetail d''
	--	set @strDetailTableName=''losPosDetail''
	--	set @strWherecondition=''where h.poshShopID=d.posdShopID and h.poshBillID=d.posdBillID and h.poshBillID=1 ''
	--	set @strCostPriceColName=''posdcostprice''
	--	set @strPKColName1=''posdShopID''
	--	set @strPKColName2=''posdBillID''
	--	set @strPKColName3=null
	--	set @strCustIDColName=null
	--	set @strAccIDColName=''poshCashAccID''
	--	set @strAccIDValue=224
	--	set @strPKType=''S''
	if isnull(@strCustIDColName,'''')='''' and isnull(@strAccIDColName,'''')=''''
	begin
		Select ''Pass either a customerid column name or an accountID column name''	
		return 0
	end
	
	if isnull(convert(int,@strAccIDValue),0)=0
	begin
		Select ''Pass the Inventory currency''	
		return 0
	end
	if isnull(@strTableName,'''')=''''
	begin
		Select ''Pass the table name''	
		return 0
	end
	if isnull(@strDetailTableName,'''')=''''
	begin
		Select ''Pass the detail table name''	
		return 0
	end
	if isnull(@strWherecondition,'''')=''''
	begin
		Select ''Pass the detail where condition.''	
		return 0
	end
	if not exists (Select 1 from sysobjects where name =''CostPriceUpdations'' and type=''U'')
		begin
			CREATE table CostPriceUpdations
			(
				pkCol1Value	int not null,
				pkCol2Value	int not null,
				pkCol3Value	int null,
				DetailTableName varchar(250) not null
			)
			
		end
	CREATE table #TempExRates
	(
		PkCol1		int not null,
		PkCol2		int not null,
		PkCol3		int null,
		CostPrice	numeric(20,4) null,
		CustomerID	int null,
		AccountID	int null
	)
	declare @strSql 		as nVarchar(2000),
		@intCount		as int,
		@intPK1			as int,
		@intPK2			as int,
		@intPK3			as int,
		@intLoopCount		as int,
		@intCustomerID 		as int,
		@intAccountID 		as int,
		@numCostPrice		as numeric(18,4),
		@intAccCurrID		as int,
		@intCusCurrID		as int,
		@intInvCurrID		as int,
		@strType		as char(1),
		@numInvExRate		as numeric(18,8),
		@strUpdWhereCondition	as varchar(1000)
	set @strSql= ''select '' + @strPKColName1 + '','' + @strPKColName2 + '','' +
		isnull(@strPKColName3,''Null'') + '','' + isnull(@strCostPriceColName,0) + '','' +
		isnull(@strCustIDColName,''Null'') + '','' +
		isnull(@strAccIDColName,''Null'') +
		'' from '' + @strTableName + '' '' + isnull(@strWherecondition,'''')
	--inserting the details into the temporary table
	insert into #TempExRates
		exec sp_executesql @strSql
	--For Inventory Account Currency ID
	if @strAccIDValue is not null
	begin
		select
			@intInvCurrID=currencyID
		from
			aAccountMaster
		where
			companyID=@intCompanyID and AccountID=convert(int,@strAccIDValue)
	end	
	--Getting the total count
	select
		@intCount=count(a.pkCol2)
	from	
		(select
			distinct PkCol1,pkCol2,pkCol3
		from
			#TempExRates) a
	--Setting the count to the total count	
	set @intLoopCount=@intCount
	while @intLoopCount<>0
	begin
		select top 1
			@intPK1=PkCol1,@intPK2=PkCol2,@intPK3=PkCol3,@intCustomerID=CustomerID,
			@intAccountID=AccountID,@numCostPrice=CostPrice
		from
			#TempExRates order by PkCol1,PkCol2,PkCol3
		--exec spUpdateOldExchangeRates1 @intGodownID,@intShopID@intDepartmentID,
		--@intCompanyID,@intCustomerID,@intVendorID,@intAccountID,
		--@intTransID,@strTableName,@strConExRateColName,@strDepExRateColName,
		--@strExRatesColName,@strPKColName1,@strPKColName2,@strPKColName3,
		--@strPKColName3Value,@strPKType
		--For Customer Currency ID
		if @intCustomerID is not null
		begin
			set @intAccountID=null
			select
				@intCusCurrID=currencyID
			from
				aCustomerMaster
			where
				companyID=@intCompanyID and CustomerID=@intCustomerID
			--Getting the exchange rate
			exec spGetExchangeRate @intCompanyID,@intCusCurrID, @intInvCurrID,
			    @numInvExRate output
		end
		--For Account Currency ID
		if @intAccountID is not null
		begin
			select
				@intAccCurrID=currencyID
			from
				aAccountMaster
			where
				companyID=@intCompanyID and AccountID=@intAccountID
			--Getting the exchange rate
			exec spGetExchangeRate @intCompanyID, @intAccCurrID, @intInvCurrID,
			    @numInvExRate output
		end
		select
			@strUpdWhereCondition= @strPKColName1 + ''='' +
			convert(varchar(10),isnull(@intPK1,0)) + '' and '' +
			@strPKColName2 + ''='' + convert(varchar(10),isnull(@intPK2,0))
		--If @strPKColName3 is not null (ie. there is a third column in the primary key)
		--then concatinating it with the where condition
		if isnull(@strPKColName3,'''')<>''''
			set @strUpdWhereCondition=@strUpdWhereCondition + @strPKColName3 + ''='' +
				convert(varchar(10),isnull(@intPK3,0))
		
		--Checking whether already the record is updated or not
		if exists (select 1 from CostPriceUpdations where PkCol1Value=@intPK1 and
			PkCol2Value=@intPK2 and isnull(PkCol3Value,0)=isnull(@intPK3,0) and
			DetailTableName=@strDetailTableName)
		begin
			--Making the update statement based on the paramenters passed
			set @strSql=''update '' + @strDetailTableName + '' set '' +
				@strCostPriceColName +''='' + @strCostPriceColName + '' * '' +  convert(varchar(25),@numInvExRate) +
				'' where '' + @strUpdWhereCondition
			exec sp_ExecuteSQl  @strSql
			delete from
				CostPriceUpdations
			where
				PkCol1Value=@intPK1 and PkCol2Value=@intPK2 and
				isnull(PkCol3Value,0)=isnull(@intPK3,0)
		end
		--Delete the row after updation
		delete from #TempExRates where
			PkCol1=@intPK1 and PkCol2=@intPK2 and isnull(PkCol3,0)=isnull(@intPK3,0)
	
		set @intLoopCount=@intLoopCount-1
	end
	drop table #TempExRates
end' 
END
GO
/****** Object:  View [dbo].[vwshopbincardauditwithopening]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopbincardauditwithopening]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopbincardauditwithopening    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on 	: 13/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshopbincardauditwithopening] as
select ShopID, ItemID, null sdate , ''opening'' transno, 0 transid, isnull(OpeningStock,0) transqty,
''opening'' type,  1 mode, stockdate updatetime from mosshopstock
union all
select shopid, itemid, sdate, Transno, TransID, Transqty, Type, mode,
updatetime from vwShopBinCardAudit'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersContra]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersContra]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- last modified : 03/12/2002
-- modified by	 : leo
-- Comments	 : the concept of new exchange rate is included
CREATE proc [dbo].[spUpdateLEDgersContra] @intCompanyID as int, @intContraID as int as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@intDepartmentID as int,
	@dtContraDate as datetime,
	@intFROMBankID as int,
	@intToBankID as int,
	@intChargeID as int,
	@strContraNo as varchar(50),
	@strRemarks as varchar(300),
	@strContraType as varchar(10),
	@numAmount as numeric(18,2),
	@numChargeAmount as numeric(18,2),
	@dtutime as datetime,
	@intcurrencyid as int,
	@numconsrate as numeric(18,9),
	@numdeprate as numeric(18,9),
	@strexrates as varchar(250),
	@numresamount as numeric(18,2)
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID
	set @intJournalID = @intJournalID + 1
	SELECT @intContraID = ContraID, @strContrano = Contrano, @dtContraDate = ContraDate,
	@strContratype = Contratype, @intFROMbankID = FROMAccountID, @inttobankID =toAccountID,
	@intchargeID = chargeAccountID, @numAmount = ContraAmount, @numChargeAmount =
	ContrachargeAmount, @strremarks = remarks, @intFinancialID = financialID,
	@intDepartmentID = departmentID, @numconsrate = ExchangeRate, @dtutime = updatetime,
	@numdeprate = depexrate, @strexrates = exchangerates
	FROM Contra WHERE cancellED =0 and
	postED =0 and CompanyID = @intCompanyID and contraid = @intContraID
	
	SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID
	= @intCompanyID and AccountID = @inttobankid
	insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
	referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime) values
	(@intJournalID, @intCompanyID, @dtContraDate, @strContraNo,
	@strRemarks, @intFinancialID,''C'', @intcurrencyid, @dtcontradate, @dtutime)
	set @intJournalDetailID = 1
	
	exec spConvertequiamount @inttobankid, ''a'', @intfrombankID,
	''a'', @strexrates, @numamount, @numresamount output
	
	insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
	AccountID, Amount, actualAmount,departmentID, depamount)
	values (@intJournalID, 	@intjournalDetailID, @intCompanyID, 1, @intFROMbankID,
	@numamount * @numconsrate, @numresamount, @intDepartmentID,
	@numamount * @numdeprate)
	set @intJournalDetailID = @intJournalDetailID +1
			
	insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
	AccountID, Amount, actualAmount,departmentID, depamount)
	values (@intJournalID, 	@intjournalDetailID, @intCompanyID, 0, @inttobankID,
	@numamount * @numconsrate , @numamount, @intDepartmentID,
	@numamount * @numdeprate)
			
	set @intJournalDetailID = @intJournalDetailID +1	
	/* mark the record as postED */
	update Contra set postED =1 WHERE CompanyID = @intCompanyID and ContraID = @intContraID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReceipts]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPReceipts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- Created Date  : 28/11/2007
-- Created by  : Shinu
-- Comments  : For HP Receipts Posting
---------------------------------------------------------------------------------------
--	:Modified By :Nidheesh P V
--	:Modified on	:29/06/2010
--	Comments : To change the ledger posting for HP receipts(At first the transaction was saved
--	in account amount. After doing partila settlement in hp receipts the transaction amount
--	is saved as the Cust. Equi.Amount. So make proper changes in the posting also.
---------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateLEDgersHPReceipts] @intCompanyID as int, @intReceiptID as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@intDepartmentID as int,
@dtReceiptDate as datetime,
@intBankID as int,
@intCustomerAccID as int,
@intCustomerID as int,
@strReceiptNo as varchar(50),
@strRemarks as varchar(300),
@numAmount as numeric(18,2),
@dtutime as datetime,
@intcurrencyid as int,
@numBankrate as numeric(18,9),
@numdeprate as numeric(18,9),
@numCusrate as numeric(18,9),
@numComrate as numeric(18,9),
@numresamount as numeric(18,2),
@intCreditAcc as int,
@numCreditExRate as numeric(18,2),
@numCreditAmount as numeric(18,2)
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
SELECT  @intCustomerAccID =DebtorAcc
FROM    ahpaccountssettings
WHERE  companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
SELECT @intReceiptID = hprhReceiptID, @strReceiptno =hprhReceiptNo, @dtReceiptDate = hprhReceiptDate,
@intbankID = hprhAccountID, @numAmount = hprhAmount, @strremarks = hprhremarks,
@intFinancialID = hprhfinancialID,
@intDepartmentID = hprhdepartmentID, @dtutime = hprhupdatedtime,
@numbankrate = hprhBankExRate,@numdeprate = hprhDepExRate,@numcusrate = hprhCusExRate,
@numcomrate= hprhComExRate,@intCreditAcc=isnull(HprhCreditAccid,0),
@numCreditExRate=hprhCreditExRate,@numCreditAmount=hprhCreditAmount
FROM ahpReceiptheader WHERE hprhcancel =0 and
hprhpostED =0 and hprhCompanyID = @intCompanyID and hprhReceiptID = @intReceiptID
SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID
= @intCompanyID and AccountID = @intbankid
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime) values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strReceiptno,
@strRemarks, @intFinancialID,''HPR'', @intcurrencyid, @dtReceiptDate, @dtutime)
set @intJournalDetailID = 1
insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID,  @intjournalDetailID, @intCompanyID, 0, @intbankID,
(@numamount/@numcusrate) * @numcomrate, (@numamount/@numcusrate) * @numbankrate, @intDepartmentID,
(@numamount/@numcusrate)* @numdeprate)
--(@numamount/@numbankrate) * @numcomrate, @numamount, @intDepartmentID,
--(@numamount/@numbankrate)* @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
if @intCreditAcc<>0
begin
insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID,  @intjournalDetailID, @intCompanyID, 1, @intCreditAcc,
(@numCreditAmount/@numCreditExRate) * @numcomrate , @numCreditAmount, @intDepartmentID,
(@numCreditAmount/@numCreditExRate)* @numdeprate)
--(@numCreditAmount/@numCreditExRate) * @numcomrate , @numCreditAmount, @intDepartmentID,
--(@numCreditAmount/@numCreditExRate)* @numdeprate)
set @numamount=((@numamount / @numcusrate)-(@numCreditAmount / @numCreditExRate))*@numbankrate
--set @numamount=((@numamount / @numbankrate)-(@numCreditAmount / @numCreditExRate))*@numbankrate
end
set @intJournalDetailID = @intJournalDetailID +1
insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID,  @intjournalDetailID, @intCompanyID, 1, @intCustomerAccID,
(@numamount/@numbankrate) * @numcomrate , @numamount, @intDepartmentID,
(@numamount/@numbankrate)* @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
/* mark the record as postED */
update ahpReceiptheader set hprhpostED =1 WHERE hprhCompanyID = @intCompanyID and hprhReceiptID = @intReceiptID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPPayments]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPPayments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created Date  : 03/12/2002
-- Created by	 : Shinu
-- Comments	 : For HP Payments Posting
CREATE  proc [dbo].[spUpdateLEDgersHPPayments] @intCompanyID as int, @intPaymentID as int as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@intDepartmentID as int,
	@dtPaymentDate as datetime,
	@intBankID as int,	
	@intCustomerAccID as int,	
	@intCustomerID as int,
	@strPaymentNo as varchar(50),
	@strRemarks as varchar(300),	
	@numAmount as numeric(18,2),	
	@dtutime as datetime,
	@intcurrencyid as int,
	@numBankrate as numeric(18,9),
	@numdeprate as numeric(18,9),
	@numCusrate as numeric(18,9),
	@numComrate as numeric(18,9),
	@numresamount as numeric(18,2)
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID
	SELECT  @intCustomerAccID =DebtorAcc
	FROM    ahpaccountssettings
	WHERE 	companyid = @intcompanyid
	set @intJournalID = @intJournalID + 1
	SELECT @intPaymentID = hphPaymentID, @strPaymentno =hphPaymentNo, @dtPaymentDate = hphPaymentDate,
	@intbankID = hphAccountID, @numAmount = hphPaymentAmount, @strremarks = hphremarks,
	@intFinancialID = hphfinancialID,
	@intDepartmentID = hphdepartmentID, @dtutime = hphupdatetime,
	@numbankrate = hphBankExchangeRate,@numdeprate = hphDepExchangeRate,@numcusrate = hphCusExchangeRate,
	@numcomrate= hphComExchangeRate
	FROM ahppaymentheader WHERE hphcancel =0 and
	hphpostED =0 and hphCompanyID = @intCompanyID and hphPaymentID = @intPaymentID
	
	SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID
	= @intCompanyID and AccountID = @intbankid
	insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
	referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime) values
	(@intJournalID, @intCompanyID, @dtPaymentDate, @strPaymentno,
	@strRemarks, @intFinancialID,''HPP'', @intcurrencyid, @dtPaymentDate, @dtutime)
	set @intJournalDetailID = 1
	
	insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
	AccountID, Amount, actualAmount,departmentID, depamount)
	values (@intJournalID, 	@intjournalDetailID, @intCompanyID, 1, @intbankID,
	(@numamount/@numbankrate) * @numcomrate, @numamount, @intDepartmentID,
	(@numamount/@numbankrate) * @numdeprate)
	set @intJournalDetailID = @intJournalDetailID +1
			
	insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
	AccountID, Amount, actualAmount,departmentID, depamount)
	values (@intJournalID, 	@intjournalDetailID, @intCompanyID, 0, @intCustomerAccID,
	(@numamount/@numbankrate) * @numcomrate , @numamount, @intDepartmentID,
	(@numamount/@numbankrate) * @numdeprate)
			
	set @intJournalDetailID = @intJournalDetailID +1	
	/* mark the record as postED */
	update ahppaymentheader set hphpostED =1 WHERE hphCompanyID = @intCompanyID and hphPaymentID = @intPaymentID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPInterest]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPInterest]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--spUpdateLEDgersHPInterest 1,2,1 ,''20070101''
-----------------------------------------------------
--exec spUpdateLEDgersHPInterest 1,2,1
-- Created Date  : 28/11/2007
-- Created by  : Prasanth
-- Comments  : For HP Processing Interest Posting
------------------------------------------------------
CREATE proc [dbo].[spUpdateLEDgersHPInterest] @intCompanyID as int, @intProcessingID as int, @intDetailID as int,@duedate as varchar(15)
as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@intDepartmentID as int,
@dtIntDate as datetime,
@dtChqDate as datetime,
@intCustomerAccID as int,
@intCustomerID as int,
@strProcessingNo as varchar(50),
@strRemarks as varchar(300),
@numAmount as numeric(18,2),
@dtutime as datetime,
@intcurrencyid as int,
@intSuspenseAccID as int,
@intInterestAccId as int
set nocount on
select
@intcurrencyid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
Select
@intSuspenseAccID=SuspenseAcc ,@intInterestAccId=InterestAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo + ''-''+ cast(hpdDetailID as nvarchar),
@dtChqDate=hpdChequeDate,@numAmount=hpdinterest,
@strremarks=hphRemarks,@intFinancialID=hphFinancialID,
@intDepartmentID=hphDepartmentID,@dtutime=hphUpdateTime
FROM ahpprocessingdetail left outer join ahpprocessingheader
on hpdprocessingID=hphProcessingID and hpdDepartmentID=hphDepartmentID and hpdCompanyID=hphCompanyID
WHERE hpdProcessingID=@intProcessingID and hpdDetailID=@intDetailID  --and hpdRental<=hpdSettlementAmount and hpdChequeStatus<>''B''
set @dtIntDate= convert(datetime,@duedate,101)
--set @dtDueDate=convert(datetime,@dtDueDate,101)
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime) values
(@intJournalID, @intCompanyID, @dtIntDate, @strProcessingNo,
@strRemarks, @intFinancialID,''HPRI'', @intcurrencyid, @dtChqDate, @dtutime)
set @intJournalDetailID = 1
if @intSuspenseAccID<>0
begin
/* Debeting the Interest Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intSuspenseAccID, @numAmount,
@numAmount,@intDepartmentID, @numAmount, 1)
set @intJournalDetailId = @intJournalDetailId +1
/* Crediting the  Interest Amount (Earned Finacial Income Earned */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intInterestAccId, @numAmount,
@numAmount,@intDepartmentID, @numAmount, 1)
/* mark the record as postED */
update ahpprocessingDetail set hpdPosted =1 WHERE hpdDetailID = @intDetailID and
hpdProcessingID= @intProcessingID
end
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPFeePayment]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPFeePayment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spUpdateLEDgersHPFeePayment] @intCompanyID as int, @intHPFID as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intRowCount as int,
@intFinancialID as int,
@dtPDate as datetime,
@strPNo as varchar(50),
@strRemarks as varchar(250),
@intDepartmentID as int,
@numAmount as numeric(18,2),
@intPDID as int,
@intPAccountID as int,
@numPAmount as numeric(18,2),
@intPDAccountID as int,
@numPDAmount as numeric(18,2),
@dtutime as datetime,
@intacccurrencyid as int,
@intcurrencyid as int,
@numAccExRate as numeric(18,9),
@numDepExRate as numeric(18,9),
@numComExRate as numeric(18,9),
@numPDAccExRate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,2)
set nocount on
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
SELECT @strPNo = hphPaymentNo, @dtPDate = hphPaymentDate,
@strremarks = hphRemarks, @intFinancialID = hphFinancialID, @dtutime = HpHUpdateTime,
@numAccExRate = hphExRate,@numComExRate = hphComExRate, @numDepExRate = hphDepExRate,
@intdepartmentid = hphdepartmentid,@numPAmount=hphAmount,@intPAccountID=hphAccountID
FROM aHPFeePaymentHeader WHERE hphcancel =0 and hphpostED =0 and
hphCompanyID = @intCompanyID and hphPaymentid = @intHPFID
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into moajournalheader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, convert(smalldatetime,@dtPDate), @strPNo,  @strRemarks,
@intFinancialID, ''HPFP'', @intcurrencyID, @dtPdate, @dtutime)
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 1, @intPAccountID,
(@numPAmount/@numAccExRate)*@numComExRate, @numPAmount, @intDepartmentID,
(@numPAmount/@numAccExRate)*@numDepExRate)
set @intJournalDetailID = @intJournalDetailID + 1
Declare DetailCur cursor for
SELECT hpdDetailID, hpdDebitAccountID, hpdAmount,hpdExRate  FROM
aHpFeePaymentDetail d, aaccountmaster a WHERE a.companyid = d.hpdcompanyid and
a.accountid = d.hpdDebitAccountid and a.CompanyID = @intCompanyID and hpdPaymentID = @intHPFID
open DetailCur
fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
while @@Fetch_status =0
begin
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 0, @intPDAccountID,
(@numPDAmount/@numPDAccExRate)*@numComExRate, @numPDAmount, @intDepartmentID,
(@numPDAmount/@numPDAccExRate)*@numDepExRate)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update aHPFeePaymentHeader set hphpostED =1 WHERE hphCompanyID = @intCompanyID and
hphPaymentID = @intHPFID
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersForex]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersForex]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- spUpdateLEDgersForex 1,7
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--------------------------------------------------------------------
-- Created on    : 03/12/2002
-- Created by   : leo
-- Comments   : the concept of new exchange rate is included
--------------------------------------------------------------------
-- Modified on   : 22/01/03
-- Modified by      : leo
--------------------------------------------------------------------
-- Modified on   : 26/07/03
-- Modified by      : R Harikrishnan
-- Comments  : Posting corrected
--------------------------------------------------------------------
-- Modified on   : 26/07/2011
-- Modified by   : Nidheesh P V
-- Comments  : Posting corrected
-- Reference : RefNo:1
--------------------------------------------------------------------
CREATE proc [dbo].[spUpdateLEDgersForex]
@intCompanyID as int, @intforexID as int
as
begin
--For testing purpose commented by R Harikrishnan
--begin tran
--set @intCompanyID =1
--set @intForexID=9
Declare @intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@intDepartmentID as int,
@dtforexDate as datetime,
@strtype as char(1),
@intsalesorpurcaccID as int,
@intotheraccID as int,
@intgainorlossaccID as int,
@strforexNo as varchar(50),
@strRemarks as varchar(300),
@numsalesorpurcamt as numeric(18,2),
@numotherAmount as numeric(18,2),
@numgainorlossAmount as numeric(18,2),
@dtutime as datetime,
@intcurrencyid as int,
@numconsrate as numeric(18,9),
@numdeprate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,2),
@numconsamount as numeric(18,2),
@numdepamount as numeric(18,2),
--RefNo:1---
@numExchComAmount as numeric(18,2) ,
@numExchAmount as numeric(18,2),
@numExchActualAmount as numeric(18,2) ,
@numExchDepAmount as numeric(18,2),
@intComcurrencyid as int
---RefNo:1----
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
select
@strforexno =forexno, @dtforexdate = forexdate, @strtype = type,
@intsalesorpurcaccID = salesorpurchaseaccid, @intotheraccid = otheraccid,
@intgainorlossaccid = isnull(forexgainlossaccid,0), @numsalesorpurcamt = salesorpurchaseamt,
@numotheramount = otheramount, @numgainorlossAmount = forexgainlossamt,
@strremarks = case when (chequeno is null or chequeno ='''') then remarks else
chequeno + '';'' + remarks end, @intfinancialid = financialid, @intdepartmentid =
departmentid, @numconsrate = exchangerate, @numdeprate = depexrate,
@strexrates = exchangerates
from
forex
WHERE
cancellED =0 and postED =0 and CompanyID = @intCompanyID and
forexid = @intforexID
SELECT
@intcurrencyid = CurrencyID
FROM
aAccountMaster
WHERE
CompanyID = @intCompanyID and AccountID = @intsalesorpurcaccid
---RefNo:1-----
SELECT
@intComcurrencyid = CurrencyID
FROM
aCompanyMaster
WHERE
CompanyID = @intCompanyID
----RefNo:1-----
insert into moaJournalHeader
(JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyID, @dtforexDate, @strforexNo,
@strRemarks, @intFinancialID,''For'', @intcurrencyid, @dtforexdate, @dtutime)
set @intJournalDetailID = 1
if @strtype =''s''
begin -- sales
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intsalesorpurcaccid, @numsalesorpurcamt * @numconsrate,
@numsalesorpurcamt, @intDepartmentID, @numsalesorpurcamt  * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
--------RefNo:1------------------
-- exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
--''m'', @strexrates, @numotheramount, @numconsamount output
exec spConvertequiamount @intotheraccid, ''a'', @intComcurrencyid,
''m'', @strexrates, @numotheramount, @numconsamount output,''''
-------RefNo:1-----------------------
exec spConvertequiamount @intotheraccid, ''a'', @intdepartmentid,
''d'', @strexrates, @numotheramount, @numdepamount output,''''
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intotheraccid,
@numconsamount, @numotheramount, @intDepartmentID, @numdepamount)
set @intJournalDetailID = @intJournalDetailID +1
--------RefNo:1---------
--To post exchange difference amount it is better to post the amount difference.
--If we post by exchnage conversion it will show some decimal difference due to rounding so it will affect TB.
--So used new approach.
exec spConvertequiamount @intsalesorpurcaccid, ''a'', @intotheraccid,
''a'', @strexrates, @numsalesorpurcamt, @numExchAmount output,''''
set @numExchComAmount=abs((@numsalesorpurcamt * @numconsrate)-@numconsamount)
set @numExchActualAmount=abs((@numExchAmount-@numotheramount))
set @numExchDepAmount=abs((@numsalesorpurcamt * @numdeprate)-@numdepamount)
--------RefNo:1------------
if @intgainorlossaccid > 0
begin -- there is a gain or loss
if @numgainorlossAmount > 0 -- gain
begin
-----------RefNo:1---------------------------
--exec spConvertequiamount @intComcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into moajournaldetails
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intgainorlossaccid, @numExchComAmount,
@numresamount, @intDepartmentID, @numExchDepAmount)
-------------RefNo:1--------------------------
set @intJournalDetailID = @intJournalDetailID +1
end
else -- loss
begin
set @numgainorlossAmount = abs(@numgainorlossAmount)
------------RefNo:1--------------------------
--exec spConvertequiamount @intComcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into moajournaldetails
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intgainorlossaccid, @numExchComAmount,
@numresamount, @intDepartmentID, @numExchDepAmount)
-------------RefNo:1------------------------
set @intJournalDetailID = @intJournalDetailID +1
end
end
end
else --purchase
begin
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intsalesorpurcaccid, @numsalesorpurcamt * @numconsrate,
@numsalesorpurcamt, @intDepartmentID, @numsalesorpurcamt  * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
-------------RefNo:1------------------
--exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
--''m'', @strexrates, @numotheramount, @numconsamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intComcurrencyid,
''m'', @strexrates, @numotheramount, @numconsamount output,''''
----------RefNo:1-----------------
exec spConvertequiamount @intotheraccid, ''a'', @intdepartmentid,
''d'', @strexrates, @numotheramount, @numdepamount output,''''
----------RefNo:1----------------
--insert into moajournaldetails
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
-- Amount, actualAmount,departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intotheraccid,
-- @numconsamount * @numconsrate, @numotheramount, @intDepartmentID,
-- @numdepamount * @numdeprate)
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intotheraccid,
@numconsamount , @numotheramount, @intDepartmentID,
@numdepamount )
---------------RefNo:1--------------
-------RefNo:1---------
--To post exchange difference amount it is better to post the amount difference.
--If we post by exchnage conversion it will show some decimal difference due to rounding so it will affect TB.
--So used new approach.
exec spConvertequiamount @intsalesorpurcaccid, ''a'', @intotheraccid,
''a'', @strexrates, @numsalesorpurcamt, @numExchAmount output,''''
set @numExchComAmount=abs((@numsalesorpurcamt * @numconsrate)-@numconsamount)
set @numExchActualAmount=abs((@numExchAmount-@numotheramount))
set @numExchDepAmount=abs((@numsalesorpurcamt * @numdeprate)-@numdepamount)
----------RefNo:1-----------
set @intJournalDetailID = @intJournalDetailID +1
if @intgainorlossaccid > 0
begin -- there is a gain or loss
if @numgainorlossAmount > 0 -- gain
begin
-----------RefNo:1-----------------
--exec spConvertequiamount @intComcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into moajournaldetails
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intgainorlossaccid, @numExchComAmount,
abs(@numresamount), @intDepartmentID, @numExchDepAmount)
--------RefNo:1---------------------
set @intJournalDetailID = @intJournalDetailID +1
end
else -- loss
begin
set @numgainorlossAmount = abs(@numgainorlossAmount)
-------RefNo:1------------------
--exec spConvertequiamount @intComcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into moajournaldetails
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into moajournaldetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intgainorlossaccid, @numExchComAmount,
abs(@numresamount), @intDepartmentID, @numExchDepAmount)
----------RefNo:1------------------
set @intJournalDetailID = @intJournalDetailID + 1
end
end
end
/* mark the record as postED */
update forex set postED =1 WHERE CompanyID = @intCompanyID and forexID = @intforexID
--rollback tran
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersDepreciation]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersDepreciation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLEDgersDepreciation    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateLEDgersDepreciation    Script Date: 14/09/2002 12:48:15 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateLEDgersDepreciation    Script Date: 31/07/2002 2:00:36 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateLEDgersDepreciation    Script Date: 20/11/2001 9:59:14 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateLEDgersDepreciation    Script Date: 17/11/2001 9:22:24 PM ******/
CREATE proc [dbo].[spUpdateLEDgersDepreciation] @intCompanyID as int as
begin
	Declare @intDepID as int
	Declare @intDepAccountID as int
	Declare @strDepNo as varchar(50)
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFixEDAssetID as int
	Declare @dtDepDate as datetime
	Declare @strRemarks as varchar(200)
	Declare @intDepartmentID as int
	Declare @numAmount as numeric(18,2)
	Declare @intFinancialID as int
	Declare @intcomcurID as int
	declare @dtutime as datetime
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID
	select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid	
	set @intJournalID = @intJournalID + 1	
	begin tran	
	Declare DepCur cursor for
	SELECT DepreciationID, Depreciationno, Depreciationdate, AccountID, deprAccountID,
	Amount, remarks, departmentID, financialID, updatetime FROM Depreciation WHERE
	postED =0 and CompanyID = @intCompanyID
	open depcur
	fetch next FROM  depcur into @intDepID, @strdepno, @dtdepDate, @intFixEDAssetID,
	@intdepAccountID,@numAmount, @strRemarks, @intDepartmentID, @intFinancialID, @dtutime
	while @@Fetch_status = 0
	begin
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate, referenceno, remarks,financialID,Type,CurrencyId, Cancel, Realised, chequedate,updatetime)
		values (@intJournalID, @intCompanyID, @dtdepDate, @strdepno, @strRemarks, @intFinancialID,''D'',@intcomcurid,0,0,@dtdepdate,@dtutime)
		set @intJournalDetailID = 1
		
		/* inserting the details*/
		insert into moajournaldetails (JournalID, journaldetailID, CompanyID, JournalCrEDit,
		AccountID, Amount,actualAmount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intFixEDAssetID, @numAmount, @numAmount)
		set @intJournalDetailID = @intJournalDetailID +1
		
		insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, AccountID, Amount, actualAmount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intdepAccountID, @numAmount, @numAmount)
		
		update Depreciation set postED =1 WHERE DepreciationID  = @intdepID and CompanyID = @intCompanyID
		
		set @intJournalID = @intJournalID + 1				
		fetch next FROM  depcur into @intDepID, @strdepno, @dtdepDate, @intFixEDAssetID, @intdepAccountID,
		@numAmount, @strRemarks, @intDepartmentID, @intFinancialID,@dtutime
	end
	Close depcur
	Deallocate depcur
	
	commit tran
end' 
END
GO
/****** Object:  View [dbo].[vwTransferInOutRequest]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferInOutRequest]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwTransferInOutRequest] As
select TIHShopID,ShopName tihShopName,tihID,TihNo,tihDate,tihRemarks,
		tohID,tohShopID,tohShopname,tohNo,tohtoShopID,tohDate,tohRemarks,
		srhShopID,srhShopName,srhRequestID,srhRequestNo,srhRequestDate,srhRemarks
From LOSTransferinheader
Left OUter Join aShops ON TIHShopID=ShopID
Left Outer Join
	(select tohID,tohShopID,tohShopname,tohNo,tohtoShopID,tohDate,tohRemarks,
			srhShopID,srhShopName,srhRequestID,srhRequestNo,srhRequestDate,srhRemarks from
	(Select tohID,tohShopID,ShopName tohShopname,tohNo,tohtoShopID,tohDate,tohRemarks,tohRequestID From mesTransferOutHeader
	Left Outer Join aShops On tohShopID=ShopID where tohCancelled=0 and tohType=''TO'')TransferOut
	Left Outer Join
	(Select srhShopID,ShopName srhShopName,srhRequestID,srhRequestNo,srhRequestDate,srhRemarks From mesRequesttoShopHeader
	Left Outer Join aShops ON srhShopID=ShopID where srhCancelled=0 and srhType=''r'')Request
	ON srhShopID=tohtoShopID and srhRequestID=tohRequestID ) TransferOutRequest
ON tohShopID=TIHFromShopID and tihDespatchID=tohID
where tihCancel=0'
GO
/****** Object:  View [dbo].[Vwjournalswithcontrolaccs]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Vwjournalswithcontrolaccs]'))
EXEC dbo.sp_executesql @statement = N'
--Modififed by 	: Hariharan
--Modified Date	: 17/07/2004
--removed childjournalid condition as it was not selecting remaining entries if
--any one of the department is used the journal for reference
--		: allowed the repopoulation of journal to another dep
CREATE VIEW [dbo].[Vwjournalswithcontrolaccs] as
select h.journalno, h.journaltransid, h.JournalTransDate, h.Remarks,
dep.departmentname,
maindepid, h.companyid, d.accountid, d.amount, d.journaltranscredit cr, accountdesc
from journaltransdetails d, journaltransheader h , adepcontrolaccounts ca,
adepartmentmaster dep, aaccountmaster a where h.companyid = d.companyid
and h.journaltransid = d.journaltransid and ca.companyid = d.companyid and
ca.controlaccid = d.accountid and h.cancelled =0 and d.accountid = a.accountid
--and h.parentjournalid is null
and h.departmentid = dep.departmentid and h.departmentid<>maindepid
and ca.maindepid not in (select departmentid from
Journaltransheader where parentjournalid = h.Journaltransid and cancelled = 0)'
GO
/****** Object:  View [dbo].[vwJournalPostAmount]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalPostAmount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 20/11/2001 9:58:58 AM ******/
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 17/11/2001 9:21:21 PM ******/
/****** Object:  View dbo.vwJournalPostAmount    Script Date: 16/06/2001 15:36:31 ******/
CREATE view [dbo].[vwJournalPostAmount]
as
select sum(Amount) as amount, jd.JournalTransID as JournalTransID ,
jd.companyid as companyid from JournalTransdetails jd ,journaltransheader jh
where jd.JournalTransID=jh.JournalTransID and jd.companyid=jh.companyid
and jh.posted=0 and jh.cancelled=0 and jd.JournalTransCredit=0 group by jd.companyid,
jd.JournalTransID'
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_ASHOP]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FETCH_ASHOP]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATE BY : VINOTHMURUGAN V
--DATE  : 11/08/2010
--PURPOSE : FETCH ITEM ITEM
--CLIENT : KOODDOOO
CREATE PROCEDURE [dbo].[SP_FETCH_ASHOP] --(@SHOPID as int)
AS
BEGIN
SELECT SHOPID,SHOPNAME from ASHOPS --ORDER BY SHOPNAME  --where SHOPID=@SHOPID
UNION ALL
SELECT ''0'',''ALL''
ORDER BY SHOPNAME
END
--SELECT * FROM ASHOPS' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_BudgetUtilization]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_BudgetUtilization]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sp_BudgetUtilization    Script Date: 18/01/2003 9:45:44 PM ******/
CREATE procedure [dbo].[sp_BudgetUtilization]
	@intBudgetAllocationID as int,
	@intcompanyid as int,
	@ToDatePassed as varchar(50)
	
	As
	
	set nocount on
	-- Declarations
	declare @maxdetailid as int,
	@BudgetHeadID as int,
	 	@AccountID as int,
	 	@DepartmentID as int,
		@NewAmount as numeric(18,2),
@Amt as numeric(18,2),
		@intCount as int,
		@dtfromdate as datetime,
		@dttodate as datetime,
		@DetailCount as int,
		@MaxDetailIDforSecond as int
	
	-- Create Temporary Table
	create table #temp1 (
	DetailID int,
		BudgetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	create table #temp2 (	DetailID int,
				AccountID int,
		             	DepartmentID int)
	
	create table #temp3 (
	DetailID int,
		BudgetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	-- Select The Allocated Details from the Budget Allocation Details
	insert  into #temp1
	select badDetailID,badBudgetHeadID,badFromDate,badToDate ,0.0
	from BudgetAllocationDetail D , BudgetAllocationHeader H
	where badCompanyId=@intcompanyid and
	D.badBudgetAllocID=H.bahBudgetAllocID And
	H.bahCompanyID=D.badCompanyID and
	H.bahCancelled=0 And
	badBudgetAllocID= @intBudgetAllocationID order by badDetailID
set @amt=0
	select @intcount=count(*) from #temp1
	while @intcount <>0
		begin
	-- Select the Max DetailID from the Temp1
		select @maxdetailid= max(DetailID) from #temp1
		-- Select BudgetHeadID,fromDate,Todate from the Temp1 Table
	Select @BudgetHeadID=BudgetHeadID, @dtfromdate = fromdate,
		@dttodate = todate from #temp1 where DetailID= @maxDetailID     		
		
		-- Change the ToDate with Respect to Actual As On Date
		--if @dttodate > @ToDatePassed
			-- @dttodate = @ToDatePassed
		-- Delete Data from the Temp2 table if some data exists
		delete from #temp2
		--To Insert into The Temp2 from the BudgetAccounts Link for the BudgetHead
		Insert #temp2
		Select bacdetailid, bacAccountID,bacDepartmentID from BudgetAccountsLink where
		bacCompanyId=@intcompanyid and bacBudgetID = @BudgetHeadID
		select @DetailCount=count(*) from #temp2   -- Select the Check Count
	 	while @DetailCount <>0
		 begin
		  -- Select the Max DetailID from the Second Table to Check for the Amount
		  select @MaxDetailIDforSecond= max(DetailID) from #temp2
		  select @AccountID = AccountId from #temp2 where detailID=@MaxDetailIDforSecond
		  select @DepartmentID=isnull(DepartmentID,0) from #temp2 where detailID=@MaxDetailIDforSecond
		--PRINT @AccountID
		--PRINT CONVERT(vARCHAR(12),@dtfromdate) +  " - " + CONVERT(VARCHAR(12), @dtTOdate)
		  -- Select Amount from the Journal Header and Journal Details
		  if @DepartmentID > 0
			select @NewAmount = isnull(Sum(isnull(Amount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moaJournaldetails.DepartmentID=@DepartmentID And
			moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
		  else
			Select @NewAmount = isnull(Sum(isnull(Amount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
PRINT @NewAmount
		  -- Delete MaxID from the TempTable2 to take the Next Max DetailID
		  delete from #temp2 where DetailID= @MaxDetailIDforSecond
		  -- Set the Count from the Temp2
		  select  @DetailCount=count(*) from #temp2
set @amt = @amt + @newamount
		end
--Select * from #temp1 where detailid = @maxdetailid
-- PRINT @amt
		  -- To Insert into Temp3 Table with the Selected Values	
		  Insert into #temp3
		  Select * from #temp1 where detailid = @maxdetailid
		  -- to Update the Temp Table with the New Amount	
	               update #TEMP3 set Amount = isnull(amount,0.0) + @amt where detailid = @maxdetailid
set @amt=0
		-- MaxDetailID row from temp1 to get the next max DetailID row
	  	delete from #temp1 where detailID = @maxdetailid
		-- To get the Row Count from the Temp1 Table
		select @intcount=count(*) from #temp1
	       end
	
	drop table #temp2
	--To Select the resultant rows from the temp3 table
	select  distinct(BudgetHeadID),DetailID,FromDate,ToDate,Amount from #temp3
	set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spgetshopstockasondate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgetshopstockasondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spgetshopstockasondate    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.spgetshopstockasondate    Script Date: 03/10/2002 5:07:00 PM ******/
/****** Object:  Stored Procedure dbo.spgetshopstockasondate    Script Date: 14/09/2002 12:48:19 AM ******/
/****** Object:  Stored Procedure dbo.spgetshopstockasondate    Script Date: 31/07/2002 2:00:40 PM ******/
CREATE proc [dbo].[spgetshopstockasondate] @strdate as varchar(11),@intshopid int as
begin
	declare @openingstock as numeric(18,3),@itemid int,
	@curstock as numeric(18,3)
	
	create table #temp (
	itemid int,
	shopid int,
	stockdate datetime,
	openingstock numeric(18,3),
	closingstock numeric(18,3)
	)
	set nocount on
	declare cur_stock cursor for
	select distinct itemid from mosshopstock where shopid=@intshopid --and gsitemid=8195
	open cur_stock
	fetch next from cur_stock into @itemid
	while @@fetch_status=0
	begin
		set @openingstock=1
		exec spshopopeningstockondate @itemid , @strdate , @intshopid , @openingstock output
		select @curstock=isnull(sum(isnull(transqty,0)*mode),0) from vwshopbincardaudit
		where sDate=@strdate and shopid=@intshopid and itemid=@itemid
		--print @curstockr
		insert into #temp values(@itemid,@intshopid,@strdate,@openingstock,
		@openingstock+@curstock)
		fetch next from cur_stock into @itemid
	end
	close cur_stock
	deallocate cur_stock
	select * from #temp
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spproductwiseservices]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spproductwiseservices]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spproductwiseservices] ( @fromdate as varchar(12), @todate as varchar(12)) as
declare @dtfromdate as datetime
declare @dttodate as datetime
set @dtfromdate = convert(datetime, @fromdate,101 )
set @dttodate =  convert(datetime, @todate,101 )
--view created for taking the total quantity of items serviced
--product wise
/*select count(sercallbkhitemid) nooftimes, serbookhshopid, serbookhcompanyid,
v.itemdescription completedescription, a.itemdescription itemname,
a.itemcode, a.part_Code, a.modelno, a.brand, sercallbkhcategid  serbookhcategid from
losservicebookingheader bh , ashops s, aitem a, vwitemdescription v,
losserviceheader sh ,loscallbookingheader los,losserviceinvheader li where
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid and
los.sercallbkhitemid = a.itemid and a.itemid = v.itemid and bh.serbookhshopid = s.shopid
and bh.serbookhinvoiced=1 and los.sercallbkhcancelled=0 and
sh.serinvhbookingid = bh.serbookhid
and sh.serinvhshopid = bh.serbookhshopid and sh.serinvhcompanyid = bh.serbookhcompanyid
and li.serinvhjobcardid=sh.serinvhid and sh.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=sh.serinvhcompanyid
and serinvhdate >= @dtfromdate and serinvhdate <= @dttodate
group by sercallbkhitemid,serbookhshopid, serbookhcompanyid, v.itemdescription,
a.itemdescription, a.itemcode, a.part_Code, a.modelno, a.brand, los.sercallbkhcategid*/
select count(los.serinvhitemid) nooftimes,los.serinvhshopid serbookhshopid,
los.serinvhcompanyid serbookhcompanyid,
v.itemdescription completedescription, a.itemdescription itemname,
a.itemcode, a.part_Code, a.modelno, a.brand
from losserviceinvheader los left outer join
aitem a on    los.serinvhitemid = a.itemid
, vwitemdescription v,ashops s where a.itemid = v.itemid and
los.serinvhshopid=s.shopid and serinvhdate >= @dtfromdate and serinvhdate <= @dttodate
group by los.serinvhshopid,los.serinvhcompanyid,
v.itemdescription, a.itemdescription,
a.itemcode, a.part_Code, a.modelno, a.brand' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostingTransactionwise]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingTransactionwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By :- Benzigar S D
-- Created On :- 21/01/2012
-- Comment    :- For Transaction/Account wise posting report
-- exec spPostingTransactionwise  1,19,28,''20080101'',''20080110''
---------------------------------------------------------------
create PROC [dbo].[spPostingTransactionwise] (@intCompanyID as int,
@intAccID as int,
@intdepid as int,
@dtfromdate as varchar(10),
@dttodate as varchar(10)) AS
begin
if  @intdepid=0
begin
select h.JournalID,JournalDate,ReferenceNo,DepartmentID,JournalCredit,TYPE,d.accountid,Amount,ActualAmount,depamount,AccountDesc,
case TYPE when ''pos'' then ''Point Of Sale''
when ''EXC'' then ''Goods Exchange''
when ''SBI'' then ''Service Booking Invoice''
when ''A'' then ''Adjustment Entry''
when ''gdntogdn'' then ''Despatch To Godown''
when ''AI'' then ''Accounts Service Invoice''
when ''ssv'' then ''Stock Verification - Shop''
when ''POSGRN'' then ''Goods Return''
when ''SAI'' then ''Shop Accounts Service Invoice''
when ''SPI'' then ''Special Invoice''
when ''spmt'' then ''Shop Payments''
when ''lp'' then ''Local Purchase''
when ''sga'' then ''Goods Arrival Shop''
when ''strin'' then ''Transfer In''
when ''strout'' then ''Transfer Out''
when ''sdtog'' then ''Despatch To Godown''
when ''RE'' then ''Reexport''
when ''scon'' then ''Shop Inhouse Consumption''
when ''sconret'' then ''Inhouse Consumption Return''
when ''sswo'' then ''Stock Write Off Shop''
when ''posrec'' then ''Recovery Shop''
when ''SB'' then ''Service Booking Advance''
when ''BC'' then ''Service Booking Cancellation''
when ''sintsale'' then ''Inter Department Sales''
when ''sintpur'' then ''Inter Department Purchase''
when ''POSDCN'' then ''Shop Debit/Credit Note''
when ''sdep'' then ''Agreement''
when ''UTB'' then ''Utility Bill Details''
when ''RBI'' then ''Room Billing''
when ''CHOR'' then ''Check Out Returns''
when ''HPI'' then ''HP Invoices''
when ''HPSR'' then ''HP Shop Receipts''
when ''HPSDP'' then ''HP Shop Down Payment''
when ''HPSRES'' then ''HP Resale''
when ''HPSRPOS'' then ''HP Repossession''
when ''sret'' then ''Shop Purchase Return''
when ''fbBill'' then ''Food and Beverages Bill''
when ''iga'' then ''Goods Arrival Inventory''
when ''invdts'' then ''Goods Dispatch to Shop''
when ''iswo'' then ''Stock Write off Inventory''
when ''isv'' then ''Stock Verification Inventory''
when ''isrec'' then ''Recovery Inventory''
when ''ispd'' then ''Special Despatch''
when ''gdntogdn'' then ''Godown to Godown Transfer''
when ''invascnv'' then ''Asset Transfer''
when ''invret'' then ''Inventory Purchase Return''
when ''BP'' then ''Business Promotion''
when ''WC'' then ''Warenty Claim''
when ''B'' then ''Bills''
when ''IDB'' then ''Inter Division Bills''
when ''P'' then ''Payments''
when ''J'' then ''Journal''
when ''DCN'' then ''Debit/Credit Note - Accounts''
when ''C'' then ''Contra''
when ''HPP'' then ''HP Payments''
when ''HQPCP'' then ''HQ Petty Cash Payment''
when ''HPFP'' then ''HP Fee Payment''
when ''HPR'' then ''HP Receipts''
when ''HPRI'' then ''HP Interest''
when ''R'' then ''Receipts''
when ''PACB'' then ''Purchase Bill''
when ''PO'' then ''Purchase Order''
when ''pcret'' then ''Purchase Return''
when ''For'' then ''Forex''
when ''COST'' then ''Costing''
when ''ASDP'' then ''Asset Depreciation''
when ''ASTR'' then ''Asset Transfer''
when ''ASD'' then ''Asset Disposal''
when ''AST'' then ''Asset Register''
when ''PAY'' then ''Payroll''
when ''hqswo'' then ''HQ Stock Writeoff''
when ''HPRPAS'' then ''HP Re-Processing''
when ''IJ'' then ''Inter Division Journal''
when ''PDCHECK'' then ''Post Dated Check''
when ''SCI'' then ''Credit Invoice'' end as TransactionName
from moajournalheader h,moajournaldetails d, aAccountMaster a where Cancel=0 AND h.JournalID=d.JournalID and JournalDate>=@dtfromdate and
JournalDate<=@dttodate and d.accountid=@intAccID and d.AccountID=a.AccountID
order by JournalDate
end
else
begin
select h.JournalID,JournalDate,ReferenceNo,DepartmentID,JournalCredit,TYPE,d.accountid,Amount,ActualAmount,depamount,AccountDesc,
case TYPE when ''pos'' then ''Point Of Sale''
when ''EXC'' then ''Goods Exchange''
when ''SBI'' then ''Service Booking Invoice''
when ''A'' then ''Adjustment Entry''
when ''gdntogdn'' then ''Despatch To Godown''
when ''AI'' then ''Accounts Service Invoice''
when ''ssv'' then ''Stock Verification - Shop''
when ''POSGRN'' then ''Goods Return''
when ''SAI'' then ''Shop Accounts Service Invoice''
when ''SPI'' then ''Special Invoice''
when ''spmt'' then ''Shop Payments''
when ''lp'' then ''Local Purchase''
when ''sga'' then ''Goods Arrival Shop''
when ''strin'' then ''Transfer In''
when ''strout'' then ''Transfer Out''
when ''sdtog'' then ''Despatch To Godown''
when ''RE'' then ''Reexport''
when ''scon'' then ''Shop Inhouse Consumption''
when ''sconret'' then ''Inhouse Consumption Return''
when ''sswo'' then ''Stock Write Off Shop''
when ''posrec'' then ''Recovery Shop''
when ''SB'' then ''Service Booking Advance''
when ''BC'' then ''Service Booking Cancellation''
when ''sintsale'' then ''Inter Department Sales''
when ''sintpur'' then ''Inter Department Purchase''
when ''POSDCN'' then ''Shop Debit/Credit Note''
when ''sdep'' then ''Agreement''
when ''UTB'' then ''Utility Bill Details''
when ''RBI'' then ''Room Billing''
when ''CHOR'' then ''Check Out Returns''
when ''HPI'' then ''HP Invoices''
when ''HPSR'' then ''HP Shop Receipts''
when ''HPSDP'' then ''HP Shop Down Payment''
when ''HPSRES'' then ''HP Resale''
when ''HPSRPOS'' then ''HP Repossession''
when ''sret'' then ''Shop Purchase Return''
when ''fbBill'' then ''Food and Beverages Bill''
when ''iga'' then ''Goods Arrival Inventory''
when ''invdts'' then ''Goods Dispatch to Shop''
when ''iswo'' then ''Stock Write off Inventory''
when ''isv'' then ''Stock Verification Inventory''
when ''isrec'' then ''Recovery Inventory''
when ''ispd'' then ''Special Despatch''
when ''gdntogdn'' then ''Godown to Godown Transfer''
when ''invascnv'' then ''Asset Transfer''
when ''invret'' then ''Inventory Purchase Return''
when ''BP'' then ''Business Promotion''
when ''WC'' then ''Warenty Claim''
when ''B'' then ''Bills''
when ''IDB'' then ''Inter Division Bills''
when ''P'' then ''Payments''
when ''J'' then ''Journal''
when ''DCN'' then ''Debit/Credit Note - Accounts''
when ''C'' then ''Contra''
when ''HPP'' then ''HP Payments''
when ''HQPCP'' then ''HQ Petty Cash Payment''
when ''HPFP'' then ''HP Fee Payment''
when ''HPR'' then ''HP Receipts''
when ''HPRI'' then ''HP Interest''
when ''R'' then ''Receipts''
when ''PACB'' then ''Purchase Bill''
when ''PO'' then ''Purchase Order''
when ''pcret'' then ''Purchase Return''
when ''For'' then ''Forex''
when ''COST'' then ''Costing''
when ''ASDP'' then ''Asset Depreciation''
when ''ASTR'' then ''Asset Transfer''
when ''ASD'' then ''Asset Disposal''
when ''AST'' then ''Asset Register''
when ''PAY'' then ''Payroll''
when ''hqswo'' then ''HQ Stock Writeoff''
when ''HPRPAS'' then ''HP Re-Processing''
when ''IJ'' then ''Inter Division Journal''
when ''PDCHECK'' then ''Post Dated Check''
when ''SCI'' then ''Credit Invoice'' end as TransactionName
from moajournalheader h,moajournaldetails d, aAccountMaster a where Cancel=0 AND h.JournalID=d.JournalID and JournalDate>=@dtfromdate and
JournalDate<=@dttodate and d.accountid=@intAccID and DepartmentID=@intdepid and d.AccountID=a.AccountID
order by JournalDate
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPLCarryForwardAmt]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLCarryForwardAmt]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on 		: 07/12/2002
-- Modified by 		: leo
---------------------------------------------------
-- Modified on		: 11/06/2003
-- Modified by          : Kishore
-- Comments             : Removed the cursor and temporary table, which found unnecessary
--                        (On comparison with v2)
-----------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spPLCarryForwardAmt] (@strToDate as varchar(10), @intCompanyID as int,
		@bitreturn as bit = 1, @numprofitamt as numeric(18,2) = 0.0 output,
		@intdepid as int = 0,
		@bitcons as bit) as
Begin
	set nocount on
	Declare @AcCode as varchar(50),
	@AcID as integer,
	@AccDesc as varchar(100),
	@strParentGroupName varchar(50),
	@intParentGroupID int,
	@AcType as varchar(1),
	@dblDebit as numeric(18,2),
	@dblCrEDit as numeric(18,2),
	@AccountOBCr as numeric(18,2),
	@AccountOBDr as numeric(18,2),
	@GroupDesc as varchar(50),
	@GroupID as integer,
	@CompanyName as varchar(100),
	@dtFROMDate as datetime,
	@dtToDate as datetime,
	@intfinmonth as varchar(5),
	@intfinyear as varchar(5),
	@numdebitamt as numeric(18,2),
	@numcreditamt as numeric(18,2),
	@intplrowcount as int
	-- getting the start date of the fin year
	select @intfinmonth = startmonth, @intfinyear = startyear
	from afinancialyear f, acompanymaster c
	where f.companyid = c.companyid
	and f.financialid = c.financialid
	and c.companyid = @intcompanyid
	set @dtFROMDate = convert(datetime, ''01/'' + @intfinmonth + ''/'' + @intfinyear )
	SELECT @dtToDate = convert(datetime, @strToDate)
	set @numdebitamt = 0.0
	set @numcreditamt = 0.0
	set @accountobdr = 0.0
	set @accountobcr = 0.0
	if @intdepid = 0
		SELECT @dblDebit = case when @bitcons =1 then Sum(isnull(Amount,0))
			else Sum(isnull(depAmount,0)) end
			FROM moaJournalDetails JD, moaJournalHeader JH,
			acompanymaster c
			WHERE c.companyid = jh.companyid
			and c.financialid = jh.financialid
			and JD.JournalID = JH.JournalID
			AND JH.CompanyID = @intCompanyID
			AND JD.CompanyID = @intCompanyID
			AND (JH.JournalDate >= @dtFROMDate
			AND JH.JournalDate <= @dtToDate)
			AND JD.JournalCrEDit = 0
			and jh.cancel = 0
			AND JD.AccountID = @AcID
			Group By JD.AccountID
	else
		SELECT @dblDebit = case when @bitcons =1 then
			Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
			FROM moaJournalDetails JD, moaJournalHeader JH,
			acompanymaster c
			WHERE c.companyid = jh.companyid 	
			and c.financialid = jh.financialid
			and JD.JournalID = JH.JournalID
			AND JH.CompanyID = @intCompanyID
			AND JD.CompanyID = @intCompanyID
			AND (JH.JournalDate >= @dtFROMDate
			AND JH.JournalDate <= @dtToDate)
			AND JD.JournalCrEDit = 0
			and jh.cancel = 0
			AND JD.AccountID = @AcID
			and jd.departmentid = @intdepid
			Group By JD.AccountID
	
	if @intdepid = 0
		SELECT @dblCrEDit = case when @bitcons =1
			then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
			FROM moaJournalDetails JD, moaJournalHeader JH,
			acompanymaster c
			WHERE c.companyid = jh.companyid
			and c.financialid = jh.financialid
			and JD.JournalID = JH.JournalID
			AND JH.CompanyID = jd.companyid
			AND JD.CompanyID = @intCompanyID
			AND (JH.JournalDate >= @dtFROMDate
			AND JH.JournalDate <= @dtToDate)
			AND JD.JournalCrEDit = 1
			AND jh.cancel = 0
			and JD.AccountID = @AcID
			Group by JD.AccountID
	else
		SELECT @dblCrEDit = case when @bitcons =1 then Sum(isnull(Amount,0))
			else Sum(isnull(depAmount,0)) end
			FROM moaJournalDetails JD, moaJournalHeader JH,
			acompanymaster c
			WHERE c.companyid = jh.companyid
			and c.financialid = jh.financialid
			and JD.JournalID = JH.JournalID
			AND JH.CompanyID = jd.companyid
			AND JD.CompanyID = @intCompanyID
			AND (JH.JournalDate >= @dtFROMDate
			AND JH.JournalDate <= @dtToDate)
			AND JD.JournalCrEDit = 1 			AND jh.cancel = 0
			and JD.AccountID = @AcID
			and jd.departmentid = @intdepid
			Group by JD.AccountID
	
	SELECT @numDebitAmt = isnull(sum(DebitAmt),0), @numCreditAmt  = isnull(sum(CreditAmt),0)
	FROM #PLFWD
	set @numdebitamt = @numdebitamt + isnull(@accountobdr,0)
	set @numcreditamt = @numcreditamt + isnull(@accountobcr,0)
	set @numprofitamt = (@numcreditamt - @numdebitamt)
	if @bitreturn = 1
	begin
		select (@numcreditamt - @numdebitamt) profitamt
		return (@numcreditamt - @numdebitamt)
	end
	set nocount on
End' 
END
GO
/****** Object:  View [dbo].[vwTransferOutShopToShop]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOutShopToShop]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 14/04/03
-- Modified by  : Lawrence.J ''For tohtype = ''TO''
-- Comments  : v3
------------------------------------------------------------------------------------------
-- Modified on  : 11/06/2003, 03/12/2003, 31/12/2003
-- Modified by  : Kishore, HARIHARAN, Kishore
-- Comments         : Removed the view vwshopitemshipmentdetailpu and
--                        used the query instead of it (see query with alias name vs)
--                        On comparison with v2
--                      : Added ComapnyExchangeRate, DepartmentExchangeRate columns (31/12/2003)
------------------------------------------------------------------------------------------
-- RefNo-1
-- Modified by : MANUNADH.U
-- Modified On : 08.08.2011
-- Purpose     : To show the selling price in the Transferout preview report from mesTransferoutdetail
---------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwTransferOutShopToShop] AS
select todShopId, todItemId, sum(TODissuedGoodQty) as TransferQty,
max(todcostprice) todCostPrice, Code, ItemDescription, s.ShopName, tohNo, tohDate,
tohDoneby DoneBy, fs.ShopName TransferTo, max(sellingprice) SellingPrice,
max(wholesaleprice) WholeSalePrice,
max(discountprice) DiscountPrice, max(isnull(srhrequestno,'''')) srhRequestNo, tohRemarks,
sum(isnull(TODrequestedGoodqty,0)) ReqQty, tohId, tohdepartmentid,
Min(tohConExRate) CompanyExchangeRate, Min(tohdepexrate) DepartmentExchangeRate
,todSellingPrice --RefNo-1
from mesTransferoutheader left outer join mesrequesttoshopheader
on tohrequestid = srhrequestid
and tohtoshopid =  srhshopid, mesTransferoutdetail
left outer join (select ItemId, ShopId, Min(PackingTypeId) PackingTypeId,
Min(SellingPrice) SellingPrice, Min(wholesaleprice) WholeSalePrice,
max(discountprice) DiscountPrice
from losShopItemShipmentDetail
Group By ItemId, ShopId) vs
on todshopid = vs.shopid and toditemid = vs.itemid,
vwitemdescription vw, ashops s, ashops fs
where tohShopId = todShopid
and toDID = toHID
and tohCancelled = 0
and toditemid = vw.itemid
and tohType = ''TO''
and todshopid = s.shopid
and fs.shopid = tohtoshopid
group by todShopid, tohid, TOHno , todItemid, vw.itemdescription,
itemdescription, Code, s.shopname,
tohdate, tohdoneby, fs.shopname, tohremarks, tohdepartmentid ,
todSellingPrice --RefNo-1'
GO
/****** Object:  View [dbo].[vwTransferInShop]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferInShop]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 12/12/02
-- Modified by  : leo
-- Comments  : v3
-- Altered By  : Lawrence.J For Tihtype = ''ti''
----------------------------------------------------------------
-- Modified on  : 11/06/2003, 04/12/2003, 31/12/2003
-- Modified by          : Kishore, Hariharan R
-- Comments             : Selling price view removed and linked
--                        directly to losShopItemShipmentDetail
--                        (On comparison with v2)
--                      : Added ComapnyExchangeRate, DepartmentExchangeRate columns (31/12/2003)
----------------------------------------------------------------
-- RefNo-1
-- Modified by : MANUNADH.U
-- Modified On : 08.08.2011
-- Purpose     : To show the selling price in the TransferIn preview report from mesTransferoutdetail
---------------------------------------------------------------------------------
-- RefNo-2
-- Modified by : Shine Das
-- Modified On : 15.10.2011
-- Purpose     : Quantity fields where showing incorrect. Old view is commented and placed
-- below the current view .
---------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwTransferInShop] AS
select tidshopid,tiditemid,TIhDate,TIDrecievedgoodqty as transferqty,max(tidcostprice)tidcostprice,
	Code, itemdescription, s.shopname, tihno,tihDoneby Doneby, fs.shopname fromshopname,
	max(sellingprice) sellingprice,max(wholesaleprice) wholesaleprice,max(discountprice) discountprice,
	tohno, tihremarks, TIDtransfergoodqty despqty, tihid, tihdepartmentid,
	Min(tohConExRate) CompanyExchangeRate, Min(tohdepexrate) DepartmentExchangeRate
	,sum(todSellingPrice) todSellingPrice   -- RefNo-2  RefNo-1
from mestransferoutheader, LOSTransferinheader, LOSTransferindetail
	left outer join
	(
		select ItemId,ShopId,Min(PackingTypeId) PackingTypeId,Min(SellingPrice) SellingPrice,
			Min(wholesaleprice) WholeSalePrice,max(discountprice) DiscountPrice
		from losShopItemShipmentDetail Group By ItemId, ShopId
	) vs on tidshopid = vs.shopid and tiditemid = vs.itemid,
	vwitemdescription vw, ashops s, ashops fs,
	mesTransferoutdetail --RefNo-1
where TihShopId=tidShopid and TIDID=TIHID and tihcancel=0 and tiditemid = vw.itemid and
	tidshopid = s.shopid and TIHfromshopID= fs.shopid and tohid = tihdespatchid and
	tohshopid = tihfromshopid and Tihtype=''TI''
	AND tohShopId = todShopid and toDID = toHID  --RefNo-1
group by tidShopid, TIHDate,tidItemid,TIDrecievedgoodqty,  vw.itemdescription, vw.code,itemdescription, Code, s.shopname,
	tihno, tihdate, tihdoneby, fs.shopname,tohno, tihremarks, TIDtransfergoodqty, tihid, tihdepartmentid
	--,todSellingPrice --  RefNo-2 RefNo-1
-- RefNo-2 Commented Below
/*
select tidshopid,tiditemid,TIhDate,TIDrecievedgoodqty as transferqty,max(tidcostprice)tidcostprice,
	Code, itemdescription, s.shopname, tihno,tihDoneby Doneby, fs.shopname fromshopname,
	max(sellingprice) sellingprice,max(wholesaleprice) wholesaleprice,max(discountprice) discountprice,
	tohno, tihremarks,sum(TIDtransfergoodqty) despqty, tihid, tihdepartmentid,
	Min(tohConExRate) CompanyExchangeRate, Min(tohdepexrate) DepartmentExchangeRate
	,todSellingPrice    --RefNo-1
from mestransferoutheader, LOSTransferinheader, LOSTransferindetail
	left outer join
	(
		select ItemId,ShopId,Min(PackingTypeId) PackingTypeId,Min(SellingPrice) SellingPrice,
			Min(wholesaleprice) WholeSalePrice,max(discountprice) DiscountPrice
		from losShopItemShipmentDetail Group By ItemId, ShopId
	) vs on tidshopid = vs.shopid and tiditemid = vs.itemid,
	vwitemdescription vw, ashops s, ashops fs,
	mesTransferoutdetail --RefNo-1
where TihShopId=tidShopid and TIDID=TIHID and tihcancel=0 and tiditemid = vw.itemid and
	tidshopid = s.shopid and TIHfromshopID= fs.shopid and tohid = tihdespatchid and
	tohshopid = tihfromshopid and Tihtype=''TI''
	AND tohShopId = todShopid and toDID = toHID  --RefNo-1
group by tidShopid, TIHDate,tidItemid,TIDrecievedgoodqty,  vw.itemdescription, vw.code,itemdescription, Code, s.shopname,
	tihno, tihdate, tihdoneby, fs.shopname,tohno, tihremarks, tihid, tihdepartmentid
	,todSellingPrice --RefNo-1
*/'
GO
/****** Object:  View [dbo].[vwGlobalAccounts]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGlobalAccounts]'))
EXEC dbo.sp_executesql @statement = N'
--Created By 	: Hariharan
--Created Dat	: 03/01/2004
CREATE view [dbo].[vwGlobalAccounts] as
Select companyid, HQSalesAccID Accountid from apackagesettings
union all
Select companyid, HQPurchaseAccID from apackagesettings
Union all
Select companyid, customsaccid from apackagesettings
union all
Select companyid, GoodsInTransitID from apackagesettings
union all
Select companyid, compprofitshareacc from apackagesettings
union all
Select companyid, stocktransfercontrolacc from apackagesettings
union all
Select companyid, profittransfercontrolacc from apackagesettings
union all
Select companyid, Returnadjustmentaccid from apackagesettings
union all
Select companyid, PurchaseRtnAccID from apackagesettings
union all
Select companyid, POGITAccountid from apackagesettings
union all
Select companyid, costofsalesid from apackagesettings
union all
Select companyid, AssetConversionAccid from apackagesettings
union all
Select companyid, interdepsalescntrlaccid  from apackagesettings
union all
select companyid, futureint from apackagesettings'
GO
/****** Object:  View [dbo].[vwGodownExchangerateDetails]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExchangerateDetails]'))
EXEC dbo.sp_executesql @statement = N'
--Created By   : Benzigar S D
--Created On   : 26/01/2009
--Comment      : To Get Company & Department Exchange Rates
--------------------------------------------------------------------------
CREATE view [dbo].[vwGodownExchangerateDetails] as
SELECT GODOWNID,GODOWNNAME,G.DEPARTMENTID,DEPARTMENTNAME,DEPCURRENCYID,
	EX.SELLINGRATE DEPEXRATE,C.COMPANYID,EXC.SELLINGRATE COMPEXRATE,
	EXC.SELLINGRATE /EX.SELLINGRATE CEXRATE,EX.SELLINGRATE/EXC.SELLINGRATE DEXRATE
FROM AGODOWN G
INNER JOIN ADEPARTMENTMASTER D ON G.DEPARTMENTID=D.DEPARTMENTID
INNER JOIN EXCHANGERATEDETAIL EX ON EX.CURRENCYID=D.DEPCURRENCYID
INNER JOIN ACOMPANYMASTER C ON C.COMPANYID=D.COMPANYID
INNER JOIN EXCHANGERATEDETAIL EXC ON EXC.CURRENCYID=c.CURRENCYID'
GO
/****** Object:  StoredProcedure [dbo].[spPosMasterFetch]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPosMasterFetch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------
---Created By  : Prasanth Joseph
---Created on  : 22-12-2008
---Created For : Make Master fetch faster
------------------------------------------------------------
CREATE proc [dbo].[spPosMasterFetch]
@dtRetriveDate as datetime,
@intShopid as int,
@intCounterID as int
as
if @intCounterID=0
begin
select poshbillid,poshbillno,poshbilldate+isnull(poshbilltime,'''') Posdate,poshcustomername,
cast(Cast(poshBillAmount as decimal(18,2)) as varchar(20)) posAmount,case poshcancelled  when 1 then ''Yes'' when 0 then ''No'' end cancelled,
case poshposted when 1 then ''Yes'' when 0 then ''No'' end Posted
from losposHeader where poshbilldate>@dtRetriveDate
and poshshopid=@intShopid and poshbillid>0 order by poshbillID
end
else
begin
select poshbillid,poshbillno,poshbilldate+isnull(poshbilltime,''''),poshcustomername,
cast(Cast(poshBillAmount as decimal(18,2)) as varchar(20)),case poshcancelled  when 1 then ''Yes'' when 0 then ''No'' end,
case poshposted when 1 then ''Yes'' when 0 then ''No'' end Posted
from losposHeader where poshbilldate>@dtRetriveDate
and poshshopid=@intShopid and poshbillid>0 and poshcounterid=@intCounterID  order by poshbillID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPOPaymentStatus]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPOPaymentStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This stored procedure is going to be useed to generate PO Payment Status Report
-- This report model is given by Sonee
--------------------------------------------------------------------------------
-- Depends On: spCreditorAgeSumAllBills
--------------------------------------------------------------------------------
-- Coded By: Regin T.
-- Coded On: 05-05-2009
--------------------------------------------------------------------------------
-- spPOPaymentStatus '''','''',''2,3'','''','''',1
--------------------------------------------------------------------------------
CREATE proc [dbo].[spPOPaymentStatus]
@strStartDate   as varchar(12)='''',
@strEndDate     as varchar(12)='''',
@strDeptIDs     as varchar(250)='''',  --Department IDs (Comma Separated)
@strVendorIDs   as varchar(250)='''',  --Vendor IDs
@strCountryIDs  as varchar(250)=''''  --Country IDs
as
begin  -- Procedure Begins Here
set ansi_Warnings off
set nocount on
declare
@strSql            as nvarchar(4000),
@strPackageDate    as varchar(12),
@strStartDateCond  as varchar(100),
@strEndDateCond    as varchar(100),
@strDeptCond       as varchar(500),
@strVendorCond     as varchar(500),
@strCountryCond    as varchar(500)
-- SETTING CONDITIONS BASED ON INPUT ARGUMENTS
if @strStartDate = ''''
set @strStartDateCond = ''''
else
set @strStartDateCond = '' and p.pohPODate >= '''''' + @strStartDate + ''''''''
if @strEndDate = ''''
set @strEndDateCond = ''''
else
set @strEndDateCond = '' and p.pohPODate <= '''''' + @strEndDate + ''''''''
if @strDeptIDs = ''''
set @strDeptCond = ''''
else
set @strDeptCond = '' and d.DepartmentID in ('' + @strDeptIDs + '')''
if @strVendorIDs = ''''
set @strVendorCond = ''''
else
set @strVendorCond = '' and v.VendorID in ('' + @strVendorIDs + '')''
if @strCountryIDs = ''''
set @strCountryCond = ''''
else
set @strCountryCond = '' and n.CountryID in ('' + @strCountryIDs + '')''
select @strPackageDate= convert(varchar,PackageDate,112) from aPackageSettings
-- The Stored Procedure spCreditorAgeSum is used to get most of the details needed.
-- Below temporary table is used to store the results of spCreditorAgeSumAllBills
create table #t1(
BillAmount     numeric(18,2),
PaidAmount     numeric(18,2),
VendorID       int,
ShopID         int,
DepartmentID   int,
BillID         int,
Type           varchar(50),
Due            varchar(50),
BillNo         varchar(50),
BillDate       datetime,
Remarks        varchar(250),
ReferenceNO    varchar(50),
CurrencyName   varchar(50),
VendorName     varchar(250),
Symbol         varchar(50),
CreditorAccID  int,
AccountDesc    varchar(205)
)
-- GETTING BILL DETAILS
insert into #t1
EXEC adminv2.dbo.spCreditorAgeSumAllBills
@strStartDate,   -- Passing StartDate
@strPackageDate, -- Since EndDate should not be limited, PackageDate is passed.
@strVendorIDs,   -- Passing Vendor IDs
0                -- Since DeptID should be a number, 0 is passed to get all dept bills.
-- RESULT
set @strSql = N''
SELECT
p.pohPOID POID, p.pohPONo PONo, p.pohPODate PODate,
p.pohValue POAmount, d.DepartmentID, d.DepartmentName,
v.VendorID, v.VendorName,
c.CurrencyID, c.CurrencyName, c.Symbol CurrencySymbol,
n.CountryID, n.CountryName,
t.BillID, t.BillNo, t.BillDate, t.BillAmount, t.PaidAmount
FROM
loPurchaseOrderHeader p
left outer join lospPurchaseBillHeader b on pbhCancelled=0 and pbhCompanyID=1 and p.pohPOID = b.pbhPOID
left outer join #t1 t on b.pbhBillID = t.BillID and p.pohDepartmentid=t.DepartmentID
and t.Type=''''fpb'''' and isnull(t.ShopID,0)=0 /*To remove Local Purchase Bills*/
left outer join aVendorMaster v on p.pohVendorID=v.VendorID
left outer join aCurrencyMaster c on v.CurrencyID=c.CurrencyID
left outer join aCountryMaster n on v.CountryID=n.CountryID
left outer join aDepartmentMaster d on p.pohDepartmentid=d.DepartmentID
WHERE
p.pohPOID <> 0 and p.pohcancel=0 and left(p.pohtype,1)=''''P''''
and t.BillID is not null /*To display only billed PO*/''
+ @strStartDateCond
+ @strEndDateCond
+ @strDeptCond
+ @strVendorCond
+ @strCountryCond + ''
ORDER BY
d.DepartmentName, p.pohPOID''
--    print @strSql
exec sp_executesql @strSql
drop table #t1
set ansi_Warnings on
set nocount off
end  -- Procedure Ends Here' 
END
GO
/****** Object:  View [dbo].[vwcustomerwiseservices]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerwiseservices]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
----------------------------------------------------------------
CREATE view [dbo].[vwcustomerwiseservices]
as
select count(sercallbkhcustomerid) nooftimes, serbookhshopid, serbookhcompanyid,
c.customername, customercardno from losservicebookingheader bh , loscallbookingheader los, ashops s,
acustomermaster c  where los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid and
los.sercallbkhcustomerid = c.customerid and bh.serbookhshopid = s.shopid
and bh.serbookhinvoiced=1 and los.serCallBkhcancelled=0 group by serbookhshopid,
serbookhcompanyid,sercallbkhcustomerid ,serbookhcompanyid, c.customername, customercardno'
GO
/****** Object:  View [dbo].[vwcurrexrateagainstInventorycurr]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrexrateagainstInventorycurr]'))
EXEC dbo.sp_executesql @statement = N'
-- created by   : R Harikrishnan
-- created date : 04/03/2003
-- for getting currency exchangerate with respect to Inventory currency
CREATE view [dbo].[vwcurrexrateagainstInventorycurr]
as
select
	bed.CompanyID,bed.currencyid, crd.currencyname, case when acc.currencyid=bed.currencyid
	then 1 else bed.sellingrate/ed.sellingrate end cmpexrate ,cr.currencyName InvCurr,
	cr.Symbol InvSymbol,crd.symbol VenSymbol
from
	acurrencymaster cr, exchangeratedetail ed, aPackageSettings s,
	exchangeratedetail bed, aAccountMaster acc,acurrencymaster crd
where
	s.companyID=acc.CompanyID and s.InventoryID = acc.AccountID and
	acc.CompanyID = cr.CompanyID and acc.CurrencyID=cr.CurrencyID and
	ed.currencyid = cr.currencyid and ed.companyid = cr.companyid and
	bed.CompanyID = s.CompanyID and
	bed.companyID = crd.companyID and bed.currencyId=crd.currencyID'
GO
/****** Object:  View [dbo].[vwcurrexrateagainstcompcurr]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrexrateagainstcompcurr]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcurrexrateagainstcompcurr    Script Date: 18/01/2003 9:45:34 PM ******/
--created by   : hariharan
--created date : 06/11/2002
--for getting currency exchangerate with respect to company currency
CREATE view [dbo].[vwcurrexrateagainstcompcurr]
as
select cr.CompanyID,cr.currencyid, cr.currencyname, case when c.currencyid=ed.currencyid
then 1 when s.cashgroupid = ed.currencyid then 12.85
else bed.sellingrate/ed.sellingrate end cmpexrate from acurrencymaster cr,
exchangeratedetail ed, asettings s, exchangeratedetail bed, acompanymaster c where
ed.currencyid = cr.currencyid and s.companyid = cr.companyid and ed.companyid=s.companyid
and bed.currencyid = s.cashgroupid'
GO
/****** Object:  View [dbo].[vwDiscountSales]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountSales]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Created By 	: Shinu
--Created On 	: 15-03-2006
--Purpose    	: For Discount Sales Detailed and Summary Reports Reports
--Modified BY	:
--Modifies On	:
--Purpose	:
-----------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDiscountSales] AS
SELECT     LPH.poshCompanyID,LPH.poshBillID,LPH.poshShopID,LPH.poshBillDate, LPH.poshBillNo, AC.ContactID,AC.Name, AC.CardNo,
	   LPH.poshBillAmount+LPH.poshDiscountAmt as TotalAmount,LPH.poshDiscountAmt,LPH.poshBillAmount
FROM       LOsPosHeader LPH
INNER JOIN aContact AC ON LPH.poshCompanyID = AC.CompanyID AND LPH.ContactCardNo = AC.CardNo'
GO
/****** Object:  StoredProcedure [dbo].[spLCRegisterAllDetails]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegisterAllDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY: NIDHEESH PV
--CREATED ON: 19/10/2010
--COMMENTS: TO GET ALL DETAILS OF LC REGISTER
--spLCRegisterAllDetails 1,0,''20070101'',''20101001'',''S'',1
CREATE proc [dbo].[spLCRegisterAllDetails]
@intCompanyID as int,
@intDepartmentID as int,
@strFromDate as varchar(12),
@strToDate as varchar(12),
@strType as char(1)=''D'',
--If passing ''D'' date Range will be considered (both From Date & To Date)
--If passing ''N'' date Range will not be considered (As on date is taken, only To Date is considered)
--If passing ''S'' date Range will not be considered (both From Date & To Date will not be considered/for a single transaction)
@intLcID as int
as
begin
set nocount on
select
LcCompanyID,LcDepartmentID,LcID,LcNo,LcCancel,
LcVendorID,case when LcVendorID is null then LcVendorName else VendorName end VendorName,DepartmentName,
LcBankName,LcShipmentDetails,LcEstDate,LcDueDate,
LcAmount,LcMargin,LcBalance,LcVendorCurrId,Vcurr.Symbol[VCurr]
from aLCRegisterDetails Lcd
left outer join avendormaster v on vendorid=LcVendorID  and CompanyID=LcCompanyID
left outer join adepartmentmaster d  on departmentid=LcDepartmentID and d.CompanyID=LcCompanyID
left outer join acurrencymaster Vcurr on Vcurr.CurrencyID=Lcd.LcVendorCurrId and Vcurr.CompanyID=LcCompanyID
where LcCancel=0 and LcCompanyID=@intCompanyID and (LcDepartmentID=@intDepartmentID or @intDepartmentID=0) and (LcID=@intLcID or @intLcID=0)
and ((LcDate>=@strFromDate and LcDate<=@strToDate and @strType=''D'') or (LcDate<=@strToDate and @strType=''N'') or (@strType=''S''))
and LcVendorCurrId is not null
set nocount off
end
-----------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_TargetAchievement]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_TargetAchievement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sp_TargetAchievement    Script Date: 18/01/2003 9:45:44 PM ******/
-- Version	: MV3
--Done By	: Nishad
--Done on	: 13.11.02
--Purpose	: This Sp Calculates the Acual usage of Amounts
--		  Allocated for the Budget Period
CREATE Procedure [dbo].[sp_TargetAchievement]
	@intTargetFixationID as int,
	@intcompanyid as int,
	@ToDatePassed as varchar(50)
	
	As
	
	set nocount on
	-- Declarations
	declare @maxdetailid as int,
	@TargetHeadID as int,
	 	@AccountID as int,
	 	@DepartmentID as int,
		@NewAmount as numeric(18,2),
		@intCount as int,
		@dtfromdate as datetime,
		@dttodate as datetime,
		@DetailCount as int,
@amt as numeric(18,2),
		@MaxDetailIDforSecond as int
	set @amt=0
	-- Create Temporary Table
	create table #temp1 (
	DetailID int,
		TargetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	create table #temp2 (	DetailID int,
				AccountID int,
		             	DepartmentID int)
	
	create table #temp3 (
	DetailID int,
		TargetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2))
	-- Select The Allocated Details from the Budget Allocation Details
	insert into #temp1
	select tfdDetailID,tfdTargetID,tfdFromDate,tfdToDate ,0.0
	from TargetFixationDetail
	where tfdCompanyId=@intcompanyid and
	tfdFixationID= @intTargetFixationID order by tfdDetailID
	select @intcount=count(*) from #temp1
	
	while @intcount <>0
		begin
	-- Select the Max DetailID from the Temp1
		select @maxdetailid= max(DetailID) from #temp1
		-- Select BudgetHeadID,fromDate,Todate from the Temp1 Table
	Select @TargetHeadID=TargetHeadID, @dtfromdate = fromdate,
		@dttodate = todate from #temp1 where DetailID= @maxDetailID     		
		
		-- Change the ToDate with Respect to Actual As On Date
		--if @dttodate > @ToDatePassed
			-- @dttodate = @ToDatePassed
		-- Delete Data from the Temp2 table if some data exists
		delete from #temp2
		--To Insert into The Temp2 from the BudgetAccounts Link for the BudgetHead
		Insert #temp2
		Select tacdetailid, tacAccountID,tacDepartmentID from TargetAccountsLink where
		tacCompanyId=@intcompanyid and tacTargetID = @TargetHeadID
		
		select @DetailCount=count(*) from #temp2   -- Select the Check Count
	 	while @DetailCount <>0
		 begin
		  -- Select the Max DetailID from the Second Table to Check for the Amount
		  select @MaxDetailIDforSecond= max(DetailID) from #temp2
		  select @AccountID=AccountId from #temp2 where detailID=@MaxDetailIDforSecond
		  select @DepartmentID=isnull(DepartmentID,0) from #temp2 where detailID=@MaxDetailIDforSecond
		
		--Print 	@dtFromDAte
		--print	@dtToDate
		--print	@AccountID
		--print	@DepartmentID
		  -- Select Amount from the Journal Header and Journal Details
		  if @DepartmentID > 0
			select @NewAmount = isnull(Sum(isnull(Amount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moaJournaldetails.DepartmentID=@DepartmentID And
			moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
		  else
			Select @NewAmount = isnull(Sum(isnull(Amount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
		  -- To Insert into Temp3 Table with the Selected Values			
		  --Insert into #temp3
		 -- Select * from #temp1 where detailid = @maxdetailid
		  -- to Update the Temp Table with the New Amount	
		  --update #temp3 set Amount = isnull(amount,0.0) + @NewAmount where detailid = @maxdetailid
	
		  -- Delete MaxID from the TempTable2 to take the Next Max DetailID
		  delete from #temp2 where DetailID= @MaxDetailIDforSecond
		  -- Set the Count from the Temp2
		  select  @DetailCount=count(*) from #temp2
set @amt=@amt+@newamount
		end
		Insert into #temp3
		  Select * from #temp1 where detailid = @maxdetailid
		  -- to Update the Temp Table with the New Amount	
		  update #temp3 set Amount = isnull(amount,0.0) + @amt where detailid = @maxdetailid
		-- MaxDetailID row from temp1 to get the next max DetailID row
	  	delete from #temp1 where detailID = @maxdetailid
		-- To get the Row Count from the Temp1 Table
		select @intcount=count(*) from #temp1
	       end
	drop table #temp2
	--To Select the resultant rows from the temp3 table
	select  DetailID,TargetHeadID,FromDate,ToDate,Amount from #temp3
	set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAssets]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssets]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 20/11/2001 9:59:12 AM ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 17/11/2001 9:22:19 PM ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 16/06/2001 15:36:35 ******/
/****** Object:  Stored Procedure dbo.spAssets    Script Date: 09/03/2001 02:32:29 ******/
CREATE proc [dbo].[spAssets] @intCompanyID as int as
begin
	Declare @strFAGroupID as varchar(50)
	Declare	@intFAGroupID as int
	Declare @strSql as nvarchar(1500)
	SELECT @intFAGroupID = FixedAssetGroupID
	FROM aSettings
	WHERE CompanyID = @intCompanyID
	exec spLeafNode @intCompanyID, @intFAGroupID, @strFAGroupID output
	set @strSql = N''(
	SELECT Acc.AccountID as AccID, max(Acc.AccountDesc) as AccDes, 0 as PurAmt,
		sum(isnull(Amount,0)) as DepToDate,
		sum(isnull(Acc.OpeningCreditBalance,0)) as OpenCredit,
		sum(isnull(Acc.OpeningDebitBalance,0)) as OpenDebit, GM.CompanyID
	FROM moaJournalDetails JD, aAccountMaster Acc, aGroupMaster GM
	WHERE GM.CompanyID = Acc.CompanyID and Acc.CompanyID = JD.CompanyID and
		JD.AccountID = Acc.AccountID and GM.GroupID = Acc.GroupID and
		JD.JournalCredit = 1 and GM.GroupID in ( '' + @strFAGroupID + '')
	GROUP BY Acc.AccountID, GM.CompanyID)
	union all (
	SELECT acc.AccountID as AccID, max(acc.AccountDesc) as AccDes,
		sum(isnull(Amount,0)) as PurAmt, 0 as DepToDate ,
		sum(isnull(Acc.OpeningCreditBalance,0)) as OpenCredit,
		sum(isnull(Acc.OpeningDebitBalance,0)) as OpenDebit, GM.CompanyID
	FROM moaJournalDetails JD, aAccountMaster Acc, aGroupMaster GM
	WHERE GM.CompanyID = Acc.CompanyID and Acc.CompanyID = JD.CompanyID and
		JD.AccountID = Acc.AccountID and GM.GroupID = Acc.GroupID and
		JD.JournalCredit = 0 and GM.GroupID in ( '' + @strFAGroupID + '')
	GROUP BY Acc.AccountID, GM.CompanyID)''
	exec sp_executesql @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetExpiryEmailCompanySettings]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailCompanySettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInterdivisionalBalance]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInterdivisionalBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spInterdivisionalBalance 1,''20100930'',2
--CREATED BY : NIDHEESH PV
--CREATED ON : 03/09/2010
--COMMENTS : To get interdepartment balance
create proc [dbo].[spInterdivisionalBalance] @IntComId as int,@dtasonDate as varchar(12),@displayCurrID as int
as
begin
set nocount on
declare @dblExchangerate as numeric(18,6)
declare @IntCompanyCurrency as int
select @IntCompanyCurrency=CurrencyID from acompanymaster where CompanyID=@IntComId
EXEC spGetExchangeRate @IntComId,@IntCompanyCurrency,@displayCurrID, @dblExchangerate output
---@IntCompanyCurrency--Company CurrencyId & @displayCurrID--CurrecyId in which the amount is shown in report
;with cteJourSum(maindepid,otherdepid,accountid,journalcredit,amount)
as
(
select de.maindepid,de.otherdepid,d.accountid,journalcredit,
case when journalcredit=0 then sum(amount) else -sum(amount) end amount
from moajournalheader h inner join moajournaldetails d on h.journalid=d.journalid and d.companyid=h.CompanyID and cancel=0
inner join adepcontrolaccounts de on d.accountid=de.controlaccid and de.companyid=h.CompanyID where  JournalDate<=@dtasonDate and de.companyid=@IntComId
group by de.maindepid,de.otherdepid,d.accountid,journalcredit
)
,cteJourTotalSum(maindepid,otherdepid,accountid,amount)
as
(
select maindepid,otherdepid,accountid,sum(amount)amount from cteJourSum
group by maindepid,otherdepid,accountid
)
--select * from cteJourTotalSum
,cteOutput(MainDept,OtherDept,maindepid,otherdepid,accountid,AmountinComCurrency,AmountinDisCurrency,AccountDesc,ComCurrecny,DisCurrecy)
as
(
select md.departmentname[MainDept],od.departmentname[OtherDept],maindepid,otherdepid,cte2.accountid,
amount[ComCurrency],convert(numeric(18,2),amount*@dblExchangerate)[DisplayCurrency],AccountDesc,ComCur.Symbol,DisCur.Symbol from cteJourTotalSum cte2
inner join adepartmentmaster md on cte2.maindepid=md.departmentid
inner join adepartmentmaster od on cte2.otherdepid=od.departmentid
inner join aaccountmaster a on cte2.accountid=a.accountid
inner join acurrencymaster ComCur on ComCur.CurrencyID=@IntCompanyCurrency
inner join acurrencymaster DisCur on DisCur.CurrencyID=@displayCurrID
)
select * from cteOutput order by  MainDept
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetAccExrate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetAccExrate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
EXEC GetAccExrate 229,1,0
CREATED BY : SHINE
ON : 03-07-2010
Comment : For Calculating exchange rates for accounts
*/
CREATE PROCEDURE [dbo].[spGetAccExrate] @accid as int, @fromCurrencyid as int, @AccExRate as numeric(18,8) output as
begin
Declare @fromCurr as numeric(18,8)
Declare @ToCurr as numeric(18,8)
Declare @accCurrid as int
select @accCurrid=currencyid from aaccountmaster where accountid = @accid
select @fromCurr=sellingrate from currencyexchangerate where currencyid=@fromCurrencyid
select @ToCurr=sellingrate from currencyexchangerate where currencyid=@accCurrid
SET @AccExRate=@ToCurr/@fromCurr
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULshopinterdepsale]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopinterdepsale]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/*
EXEC spULshopinterdepsale 1,12
Created  on  : 15/04/2003
Created  by : leo
------------------------------------------------------------
Last ModIFied by : R Harikrishnan, Hariharan R
Last modIFied on : 06/06/2003,19/06/2003, 26/09/20003
Comments   : The Zero value check includeded
: AND Currency conversion corrected
: The Item rate conversion to ''to
: Shop Currency'' added
VerIFied by      : Hariharan
VerIFied Date     : 03/05/2004 (verIFied FROM Client DB)
------------------------------------------------------------
ModIFied By : Nidheesh P V
ModIFied on :18/06/2010
comments : At first in spConvertequiamount there was no case for
getting companycurrencyid. The type passed to  spConvertequiamount
was ''c''.But in the spConvertequiamount this type referred the customercurrency.
I added this case as type ''co'' AND passed the type in spULshopinterdepsale
WHERE ever it is converting com.currency to account currency
ModIFied By : SHINE DAS
ModIFied on : 03/07/2010
Comments : Actual Amount is coming based on account currency. It as
		   wrong. Now added an sp to find account currencies, AND actual amount
		   coverted to account currencies.
Ref ID : 101		
ModIFied By : SHINE DAS
ModIFied on : 26/04/2011
Comments : Variable given to find account exrate was wrong. Earlier its was give department currency id
instead of department id, and changed fromtyp as "d" from "co"
*/
CREATE proc [dbo].[spULshopinterdepsale]
@intCompanyID as INT, @intshopid as INT
as
BEGIN
DECLARE @intJournalID as INT
DECLARE @intJournalDetailID as INT
DECLARE @intFinancialID as INT
DECLARE @dttDate as datetime
DECLARE @strtNo as varchar(50)
DECLARE @inttid as INT
DECLARE @strRemarks as varchar(250)
DECLARE @numtotalValue as NUMERIC(18,2)
DECLARE @numtotalsalesValue as NUMERIC(18,2)
DECLARE @numtotalValueininvcur as float
DECLARE @nummarginamt as NUMERIC(18,2)
DECLARE @numconsmarginamt as NUMERIC(18,2)
DECLARE @numdepmarginamt as NUMERIC(18,2)
DECLARE @numresmarginamt as NUMERIC(18,2)
DECLARE @intinventoryaccid as INT
DECLARE @intcomcurid as INT
DECLARE @inttodepid as INT
DECLARE @dtutime as datetime
DECLARE @intFailcount as INT
DECLARE @intstocktransferaccid  as INT
DECLARE @intinterdepsalescontrolaccid as INT
DECLARE @intinterdepsalesaccid  as INT
DECLARE @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),
@InventoryAccExRate float,
@inttoshopid as INT,
@inttodepcurid as INT,
@intStkTranCurrID as INT,
@FROMDepExRate as NUMERIC(18, 8),
@AccExRate as NUMERIC(18, 8),
@AccExRate1 as NUMERIC(18, 8),
@interDepSalesaAcc  as NUMERIC(18, 8),
@StocktransferaccEX   as NUMERIC(18, 8)
/* 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 @intInventoryaccid = inventoryid,
			@intstocktransferaccid = stocktransfercontrolacc,
			@intinterdepsalescontrolaccid = ISNULL(interdepsalescntrlaccid,0),
			@strzerorate = substring(ISNULL(futurevc,''''),1,1)
	FROM	apackagesettings
	WHERE	companyid = @intcompanyid
	SELECT @intinterdepsalesaccid = ISNULL(interdepsalesaccid,0) FROM ashops WHERE shopid = @intshopid
	
	IF @intinterdepsalescontrolaccid =0 or @intinterdepsalesaccid =0
		RETURN
		SET @intJournalID = @intJournalID + 1
	
	DECLARE trincur CURSOR for
		SELECT ToHID, ToHDate, ToHNO, ToHremarks, tohdepartmentid todep, updatetime, tohConExRate, tohDepExRate, tohExchangeRates, TOHtoShopid
		FROM mestransferoutheader tinh
		WHERE  ToHcancelled =0 AND ToHPosted =0 AND ToHShopid = @intShopId AND ToHTransFinished = 1 AND tohType =''IS''
	OPEN trincur
		FETCH next FROM trincur INTO @inttid , @dttdate, @strtno, @strremarks, @inttodepid,
		@dtutime, @numConExRate, @numDepExRate, @strExRates, @inttoshopid
	
	 WHILE @@Fetch_status = 0
		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 @dttdate  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 mestransferoutdetail , aitem
			WHERE todid= @inttid AND todshopid = @intshopid AND toditemid = itemid AND
			(todcostprice=null or todcostprice=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
							SET @intfailcount=0
					IF @intfailcount = 0  -- item rate=0 check hari 011213
					BEGIN
						EXEC spGetAccExrate @intinterdepsalesaccid,@inttodepcurid,@AccExRate output
						-- to update the item rate to the gadcostprice
						update mestransferoutdetail  SET todcostprice = itemrate FROM aitem
						WHERE (todcostprice=null or todcostprice=0) AND todid= @inttid AND todshopid = @intshopid AND toditemid = itemid
	
					    SET  @numtotalvalue = 0
						SET @numtotalsalesValue = 0
					SELECT @numtotalvalue = sum(TODissuedGoodQty * ToDCostprice) ,
						   @numtotalsalesValue = ISNULL(sum(TODissuedGoodQty * todSellingPrice),0)
					FROM mestransferoutdetail
					WHERE TodShopid  = @intShopId AND TodID = @inttid group by TodShopid, TodID
						
					SELECT @inttodepcurid = depcurrencyid FROM adepartmentmaster d, ashops s
					WHERE s.departmentid = d.departmentid AND s.shopid = @inttoshopid
					
				    SET @nummarginamt =0.0
					SET @nummarginamt = @numtotalsalesValue - @numtotalvalue
			   -- Checking for both the amounts greater than 0
					  -- IF both r zero then no need for posting it
IF (@numtotalvalue>0 or @nummarginamt>0)
BEGIN
insert INTO moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dttDate, @strtNo,
@strremarks, @intFinancialID,''sintsale'', @intcomCurID,@dttdate, @dtutime)
SET @intJournalDetailID = 1
IF @numtotalvalue>0
BEGIN
--- Ref ID : 101			
EXEC spConvertequiamount @inttodepid, ''d'', @intInventoryaccid, ''a'', @strExRates, @numTotalValue, @numtotalValueininvcur  output, ''r''
		 insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
		 JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
		 values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		 @intInventoryaccid, @numTotalValue * @numConExRate,   @numtotalValueininvcur,
		 @numtotalvalue * @numDepExRate, @inttoDepID )
	 --EXEC spConvertequiamount @inttodepcurid, ''co'', @intInventoryaccid, ''a'',
--@strExRates, @numTotalValue, @numtotalValueininvcur  output, ''r''
	---		EXEC spGetAccExrate @intinterdepsalesaccid,@inttodepcurid,@InventoryAccExRate output
--insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
-- JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
-- values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
-- --@intInventoryaccid, @numTotalValue * @numConExRate, @numtotalValueininvcur,
-- @intInventoryaccid, @numTotalValue * @numConExRate,  @numtotalValueininvcur * @InventoryAccExRate,
-- @numtotalvalue * @numDepExRate, @inttoDepID )
SET @intJournalDetailID = @intJournalDetailID + 1
--- Ref ID : 101	
EXEC spConvertequiamount @inttodepid, ''d'', @intstocktransferaccid, ''a'', @strExRates, @numTotalValue, @numaAccAmt  output, ''r''
insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intstocktransferaccid, @numTotalValue * @numConExRate, @numaAccAmt,
@numtotalvalue * @numDepExRate, @inttoDepId)
SET @intJournalDetailID = @intJournalDetailID + 1
END
-- to post the inter division sales, starts
-- to find the margin, convering the inventory amt FROM its currecny to shop(sold) currency
IF  @nummarginamt > 0.0
BEGIN -- the sales is done with some margin
-- crediting the inter dept sales
-- the converstion to be considered for performance later
--EXEC spConvertequiamount @inttodepcurid, ''co'', @intinterdepsalesaccid, ''a'',
--@strExRates, @nummarginamt, @numresmarginamt  output, ''r''
--- Ref ID : 101	
EXEC spConvertequiamount @inttodepid, ''d'', @intinterdepsalesaccid, ''a'', @strExRates, @nummarginamt, @numresmarginamt  output, ''r''
	   insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
		 JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
		 values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		 @intinterdepsalesaccid, @nummarginamt * @numConExRate, @numresmarginamt,
		 @nummarginamt * @numDepExRate, @inttoDepId)
--print ''=========''
--	print @nummarginamt * @interDepSalesaAcc
--print ''=========''
----exec spULshopinterdepsale 1,11
/*
update MOaJournalHeader set cancel=1 where ReferenceNo =''SOA/SAO/11/31''
update mesTransferOutHeader set tohposted=0 where tohno =''SOA/SAO/11/31''
EXEC spULshopinterdepsale 1,11
*/
SET @intJournalDetailID = @intJournalDetailID + 1
--EXEC spConvertequiamount @inttodepcurid, ''co'', @intinterdepsalescontrolaccid, ''a'',
--@strExRates, @nummarginamt, @numresmarginamt  output, ''r''
--- Ref ID : 101	
EXEC spConvertequiamount @inttodepid, ''d'', @intinterdepsalescontrolaccid, ''a'', @strExRates, @nummarginamt, @numresmarginamt  output, ''r''
insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intinterdepsalescontrolaccid, @nummarginamt * @numConExRate, @numresmarginamt,
@nummarginamt * @numDepExRate, @inttoDepId)
--insert INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
--JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
--values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
--@intinterdepsalescontrolaccid, @nummarginamt * @numConExRate, @numresmarginamt,
--@nummarginamt * @numDepExRate, @inttoDepId)
END
SET @intJournalID = @intJournalID + 1
END  -- Checking for both the amounts greater than 0
-- IF both r zero then no need for posting it
-- inter division sales posting ends
/* mark the record as postED */
update mestransferoutheader SET ToHPosted = 1 WHERE tohshopid =
@intshopid AND ToHID = @inttid
END
FETCH next FROM trincur INTO @inttid, @dttdate, @strtno, @strremarks,
@inttodepid, @dtutime, @numConExRate, @numDepExRate, @strExRates, @inttoshopid
END
Close trincur
Deallocate trincur
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULshopinterdeppurchase]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopinterdeppurchase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
/*
exec spULshopinterdeppurchase 1,12
*/
-- Created  on 	: 15/04/2003
-- Created  by	: leo
-----------------------------------------------------------
-- Modified on	: 06/06/2003, 15/10/2003
-- Modified by	: R Harikrishnan, Hariharan R
-- Comments 	: Addedcheck for zero value records.	
--		: initialised @intJournalDetailId in the beggining
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-----------------------------------------------------------
CREATE proc [dbo].[spULshopinterdeppurchase]
	@intCompanyID as int, @intshopid as int
as
begin
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dttDate as datetime
	Declare @strtNo as varchar(50)
	Declare @inttid as int
	Declare @strRemarks as varchar(250)
	Declare @numtotalValue as numeric(18,2)
	Declare @numtotalpurchaseValue as numeric(18,2)
	Declare @numtotalValueinInvcur as numeric(18,2)
	Declare @nummarginamt as numeric(18,2)
	Declare @numconsmarginamt as numeric(18,2)
	Declare @numdepmarginamt as numeric(18,2)
	Declare @numresmarginamt as numeric(18,2)
	Declare @intinventoryaccid as int
	declare @intcomcurid as int
	declare @inttodepid as int
	declare @dtutime as datetime
	declare @intFailcount as int
	declare @intstocktransferaccid  as int
	declare @intinterdepsalescontrolaccid as int
	declare @intinterdeppurchaseaccid  as int
	declare @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),
	@intdepcurid as int,
@StocktransferaccEX   as NUMERIC(18, 8)
	/*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 @intinterdeppurchaseaccid = interdeppurchaseaccid from ashops where shopid = @intshopid
	
	select @intInventoryaccid = inventoryid, @intstocktransferaccid =
	stocktransfercontrolacc, @strzerorate = substring(isnull(futurevc,''''),1,1),
	@intinterdepsalescontrolaccid = interdepsalescntrlaccid
	from apackagesettings where companyid = @intcompanyid
	if (@intInventoryaccid  is null or @intstocktransferaccid is null or
		@intinterdepsalescontrolaccid is null or @intinterdeppurchaseaccid is null)
	begin
		return
	end
	set @intJournalID = @intJournalID + 1
	
	Declare trincur cursor for
		SELECT TIHID, TIHDate, TIHNO, TIHremarks, tihdepartmentid todep, updatetime,
		tihConExRate, tihDepExRate, tihExchangeRates
		FROM LOSTransferinheader tinh
		WHERE  TIHcancel =0 and TIHPosted =0 and TIHShopid = @intshopid
		and TIHTransFinished = 1 and TIHType = ''IP''
	open trincur
	fetch next FROM trincur into @inttid , @dttdate, @strtno, @strremarks, @inttodepid,
		@dtutime, @numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0
	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 @dttdate 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 lostransferindetail, aitem where
			tidid= @inttid and tidshopid = @intshopid and tiditemid = itemid
			and (tidcostprice=null or tidcostprice=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 	-- item rate=0 check hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update lostransferindetail set tidcostprice = itemrate from
			aitem where (tidcostprice=null or tidcostprice=0) and tidid= @inttid
			and tidshopid = @intshopid and tiditemid = itemid
			SELECT @numTotalValue = sum(TIDrecievedgoodqty * TIDCostprice),
			@numtotalpurchaseValue = isnull(sum(TIDrecievedgoodqty * tidSellingPrice),0)
			FROM LOSTransferindetail WHERE TIdShopid  = @intshopid and
			TIdID = @inttid group by TIdShopid, TIdID
			select @intdepcurid = depcurrencyid from adepartmentmaster d,
			ashops s where s.departmentid = d.departmentid and s.shopid = @intshopid
			
			set @nummarginamt = 0.0
			set @nummarginamt = @numtotalpurchaseValue - @numtotalValue
			if (@nummarginamt >0 or @numTotalValue>0 )
			begin
				insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
					referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime)
				values 	(@intJournalID, @intCompanyID, @dttDate, @strtNo,
					@strremarks, @intFinancialID,''sintpur'', @intcomCurID,@dttdate, @dtutime)
				set @intJournalDetailID = 1	
				if @numTotalValue>0
				begin					
					-- converting the inv value to the sold shop currency
					exec spConvertequiamount @intdepcurid, ''m'', @intcurrencyid, ''m'',
					@strExRates, @numTotalValue, @numtotalValueinInvcur output , ''r''
					/* debiting the inventory account with the full */
					insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
						JournalCrEDit, AccountID, Amount, actualAmount,	DepAmount, departmentID)
					values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
						@intInventoryaccid, @numTotalValue * @numConExRate, @numtotalValueinInvcur,
						@numTotalValue * @numDepExRate, @inttoDepID )		
					set @intJournalDetailID = @intJournalDetailID + 1		
					-- converting the inv value to the sold shop currency
					exec spConvertequiamount @intdepcurid, ''m'', @intstocktransferaccid, ''a'',
					@strExRates, @numTotalValue, @numAaccAmt output , ''r''
print @intdepcurid
EXEC spGetAccExrate @intinterdepsalescontrolaccid,@intdepcurid,@StocktransferaccEX output
					/* debiting the inventory account with the full */
					insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
						JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
					values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
						@intstocktransferaccid , @numTotalValue * @numConExRate, @numTotalValue * @StocktransferaccEX,
						@numTotalValue * @numDepExRate, @inttoDepID)			
				
					set @intJournalDetailID = @intJournalDetailID + 1
				end--Total cost value greater than zero
				-- to post the inter division purchase, starts
				-- to find the margin, convering the inventory amt from its currecny to shop(sold) currency
				if  @nummarginamt>0
				begin -- the sales is done with some margin
					-- crediting the inter dept sales
					-- the converstion to be considered for performance later
				
					exec spConvertequiamount @intdepcurid, ''m'', @intinterdeppurchaseaccid, ''a'',
					@strExRates, @nummarginamt, @numresmarginamt  output, ''r''
					insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
						JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
					values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
						@intinterdeppurchaseaccid, @nummarginamt * @numConExRate,
						@numresmarginamt ,@nummarginamt * @numDepExRate, @inttoDepId)							
					set @intJournalDetailID = @intJournalDetailID + 1		
					exec spConvertequiamount @intdepcurid, ''m'', @intinterdepsalescontrolaccid, ''a'',
					@strExRates, @nummarginamt, @numresmarginamt  output, ''r''
					insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
						JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
					values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
						@intinterdepsalescontrolaccid, @nummarginamt * @numConExRate, @numresmarginamt  ,
						@nummarginamt * @numDepExRate, @inttoDepId)		
				end -- inter division sales posting ends
				set @intJournalID = @intJournalID + 1
			end
			/* mark the record as postED */
			update LOSTransferinheader  set TIHPosted = 1 WHERE tihshopid = @intshopid
				and TIHID = @inttid
		end -- item rate=0 check hari 011213
		fetch next FROM trincur into @inttid, @dttdate, @strtno, @strremarks,
			@inttodepid, @dtutime, @numConExRate, @numDepExRate, @strExRates
	end
	Close trincur
	Deallocate trincur	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDateCheck]    Script Date: 10/06/2012 14:17: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].[spDateCheck]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[spDateCheck] (@dtStartDate nvarchar,@dtEnddate nvarchar)
as
begin
declare @strsql as nvarchar(200)
select * from losposheader where poshBillDate>=''''''''''@dtStartDate''''''
--set @strsql= ''select * from losposheader where poshBillDate>=''''''''@dtStartDate'''''' --and  poshBillDate< ''''@dtEnddate''''''''
--print @strsql
print @dtStartDate
--exec sp_Executesql @strsql
end' 
END
GO
/****** Object:  View [dbo].[vwserialnogodownitemstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnogodownitemstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnogodownitemstock] as
select vwg.itemid,ai.itemcode,ai.itemdescription,vwg.serialno,vwg.qty,vwg.godownid,agw.godownname,aic.itemcategoryid,aic.categorynamedescription itemcategory
from vwserialnogodownstock vwg,aitem ai,aitemcategory aic,agodown agw
where vwg.itemid=ai.itemid and aic.itemcategoryid=ai.itemcategoryid and vwg.godownid=agw.godownid'
GO
/****** Object:  View [dbo].[vwSales]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSales]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwSales    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwSales    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwSales    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwSales    Script Date: 20/11/2001 9:58:58 AM ******/
/****** Object:  View dbo.vwSales    Script Date: 17/11/2001 9:21:25 PM ******/
/****** Object:  View dbo.vwSales    Script Date: 16/06/2001 15:36:31 ******/
/****** Object:  View dbo.vwSales    Script Date: 09/03/2001 02:32:26 ******/
/****** Object:  View dbo.vwSales    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwSales] as
select ReferenceNo, JournalDate, AccountID,
isnull(Amount,0) as amount from moajournaldetails jd, moajournalheader jh
where jd.journalid = jh.journalid and JournalCredit =1  and AccountID in
(select accountid from aaccountmaster where groupid = (select salesgroupid from asettings))'
GO
/****** Object:  View [dbo].[vwserialnoitemsshopstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsshopstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnoitemsshopstock] as
select vws.itemid,ai.itemcode,ai.itemdescription,vws.serialno,vws.qty,vws.shopid,ash.shopname,aic.itemcategoryid,aic.categorynamedescription itemcategory
from vwserialnoshopstock vws,aitem ai,aitemcategory aic,ashops ash
where vws.itemid=ai.itemid and aic.itemcategoryid=ai.itemcategoryid and vws.shopid=ash.shopid'
GO
/****** Object:  View [dbo].[vwserialnoitemsissuedshopstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsissuedshopstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnoitemsissuedshopstock] as
select vws.itemid,ai.itemcode,ai.itemdescription,vws.serialno,vws.qty,vws.shopid,ash.shopname,aic.itemcategoryid,aic.categorynamedescription itemcategory,
aif.interfacename
from vwserialnoissueshopstock vws,aitem ai,aitemcategory aic,ashops ash ,ainterface aif
where vws.itemid=ai.itemid and aic.itemcategoryid=ai.itemcategoryid and vws.shopid=ash.shopid and aif.interfaceid=vws.interfaceid'
GO
/****** Object:  View [dbo].[vwserialnoitemsissuedgodownstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoitemsissuedgodownstock]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserialnoitemsissuedgodownstock] as
select vws.itemid,ai.itemcode,ai.itemdescription,vws.serialno,vws.qty,vws.GodownId,ash.Godownname,aic.itemcategoryid,aic.categorynamedescription itemcategory,
aif.interfacename
from vwserialnoissuegodownstock vws,aitem ai,aitemcategory aic,agodown ash,ainterface aif
where vws.itemid=ai.itemid and aic.itemcategoryid=ai.itemcategoryid and vws.godownid=ash.godownid and aif.interfaceid=vws.interfaceid'
GO
/****** Object:  View [dbo].[vwShopGodownDepWise]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopGodownDepWise]'))
EXEC dbo.sp_executesql @statement = N'
--Created By  : Hariharan
--Created Date: 14/10/2003
CREATE view [dbo].[vwShopGodownDepWise] as
select shopid locationid, ''s'' type, departmentid from ashops
union all
select godownid locationid, ''g'' type , departmentid from agodown'
GO
/****** Object:  View [dbo].[vwShopExpirywiseStock]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExpirywiseStock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopExpirywiseStock    Script Date: 18/01/2003 9:45:34 PM ******/
--Created By   : Hariharan
--Created Date : 26/12/2002
CREATE view [dbo].[vwShopExpirywiseStock] as
select shopname, eadshopid, eaditemid, ItemDescription, Code, eadexpirydate,
sum(Stock ) Stock from
(select shopname, eadshopid, eaditemid, ItemDescription, Code, eadexpirydate,
eaditemqty Stock from losexpiryarrivaldetails ad,
vwitemdescription vw, ashops s
where ad.eaditemid = vw.itemid and eadshopid = s.shopid
union all
select shopname, eidshopid, eiditemid, ItemDescription, Code, eidexpirydate,
eiditemqty Stock from losexpiryIssuedetails ad,
vwitemdescription vw, ashops s
where ad.eiditemid = vw.itemid  and eidshopid = s.shopid) Expirystock group by
shopname, eadshopid, eaditemid, itemDescription,  Code, eadexpirydate'
GO
/****** Object:  View [dbo].[vwShopExpiryAlertItems]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExpiryAlertItems]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------
-- Created by	: Kishore
-- Created on	: 10/08/2003
-- Comments	: This view lists items in stock which expire within
--                ExpiryNoOfDays (in aItem) from package date. Typically
--		  used to display alerts
-------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopExpiryAlertItems] AS
SELECT b.ShopId, b.itemid, vw.Code ItemCode, vw.ItemDescription,
b.ExpiryDate, b.qty Stock, vw.vwActive --, p.PackageDate, i.ExpiryNoOfDays, b.ExpiryDate
FROM (SELECT ExpiryDate, ShopId,  ItemId, SUM(qty) qty
	FROM (SELECT eadExpiryDate ExpiryDate,  eadShopId ShopId,
		eadItemId ItemId , SUM(eadItemQty) qty
		FROM losExpiryArrivalDetails
		WHERE eadCancel = 0
		GROUP BY eadExpiryDate, eadShopId, eadItemId
		UNION ALL
		SELECT eidExpiryDate, eidShopId, eidItemId, - SUM(eidItemQty)
		FROM losExpiryIssueDetails
		WHERE eidCancel = 0
		GROUP BY eidExpiryDate, eidShopId, eidItemId) a
	GROUP BY ExpiryDate, ItemId, ShopId
	HAVING SUM(qty) <> 0 ) b,
vwItemDescription vw, aItem i, aPackageSettings p
WHERE b.ItemId = vw.ItemId
AND vw.ItemId = i.ItemId
AND p.PackageDate + i.ExpiryNoOfDays >= b.ExpiryDate'
GO
/****** Object:  View [dbo].[vwShopExchangerateDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopExchangerateDetails]'))
EXEC dbo.sp_executesql @statement = N'
--Created By   : Benzigar S D
--Created On   : 26/01/2009
--Comment      : To Get Company & Department Exchange Rates
-----------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopExchangerateDetails] as
SELECT SHOPID,SHOPNAME,S.DEPARTMENTID,DEPARTMENTNAME,DEPCURRENCYID,
	EX.SELLINGRATE DEPEXRATE,C.COMPANYID,EXC.SELLINGRATE COMPEXRATE,
	EXC.SELLINGRATE /EX.SELLINGRATE CEXRATE,EX.SELLINGRATE/EXC.SELLINGRATE DEXRATE
FROM ASHOPS S
INNER JOIN ADEPARTMENTMASTER D ON S.DEPARTMENTID=D.DEPARTMENTID
INNER JOIN EXCHANGERATEDETAIL EX ON EX.CURRENCYID=D.DEPCURRENCYID
INNER JOIN ACOMPANYMASTER C ON C.COMPANYID=D.COMPANYID
INNER JOIN EXCHANGERATEDETAIL EXC ON EXC.CURRENCYID=c.CURRENCYID'
GO
/****** Object:  View [dbo].[vwpostdatedreceipts]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostdatedreceipts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpostdatedreceipts    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwpostdatedreceipts] as
select jh.companyid, jh.journalid, jh.referenceno, jh.journaldate, jd.accountid,
isnull(amount,0) debitamt, isnull(actualamount,0) debitactualamt, jh.chequedate
from moajournalheader jh, moajournaldetails jd
where jh.companyid = jd.companyid and jh.journalid = jd.journalid and
jh.cancel =0 and jh.type =''R''
and jd.journalcredit = 0  and  jh.chequedate > jh.journaldate'
GO
/****** Object:  View [dbo].[vwpostdatedpayments]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostdatedpayments]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpostdatedpayments    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwpostdatedpayments] as
select jh.companyid, jh.journalid, jh.referenceno, jh.journaldate, jd.accountid,
isnull(amount,0) creditamt, isnull(actualamount,0) creditactualamt, jh.chequedate
from moajournalheader jh, moajournaldetails jd
where jh.companyid = jd.companyid and jh.journalid = jd.journalid and
jh.cancel =0 and jh.type =''P'' and jd.journalcredit = 1 and  jh.chequedate > jh.journaldate'
GO
/****** Object:  View [dbo].[vwPayrollLinkwithjournal]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayrollLinkwithjournal]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created  by Venkitesh 130304
-- Purpose :- To get the information of balance figure and pending data
--MOdified By 	: Hariharan
--Modified Date	: 20/03/2004
--Comments	: Transaction types other than payroll only taken
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
CREATE view [dbo].[vwPayrollLinkwithjournal] as
select max(a.transid)transid,max(a.transno)transno,max(c.PayrollLinktransId)PayrollLinktransId,
max(deptamount)depamount,isnull(sum(c.amount),0)amount,
max(b.accountid)accountid,a.departmentid from  papayacclinkheader a,
papayacclinkdetails b
left outer join (select a.JournalTransID transid,AccountID,amount, PayrollLinktransId from JournalTransheader a,
JournalTransDetails b where
a.JournalTransID = b.JournalTransID  and
a.CompanyID=b.CompanyID and cancelled=0 )c  on
b.transid= PayrollLinktransId
and b.accountid = c.AccountID
where a.transid=b.transid and Cancelled=0 and TransType <>''P''
group by  b.accountid,a.departmentid
having isnull(sum( c.amount),0) < max(b.deptamount)'
GO
/****** Object:  View [dbo].[vwproductwiseservices]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwproductwiseservices]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwproductwiseservices    Script Date: 18/01/2003 9:45:36 PM ******/
/****** Object:  View dbo.vwproductwiseservices    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwproductwiseservices    Script Date: 31/07/2002 2:00:27 PM ******/
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE view [dbo].[vwproductwiseservices]
as
select count(sercallbkhitemid) nooftimes, serbookhshopid, serbookhcompanyid,
v.itemdescription completedescription, a.itemdescription itemname,
a.itemcode, a.part_Code, a.modelno, a.brand, los.sercallbkhcategid serbookhcategid from
losservicebookingheader bh , loscallbookingheader los, ashops s, aitem a, vwitemdescription v where
los.sercallbkhitemid = a.itemid and a.itemid = v.itemid and bh.serbookhshopid = s.shopid and
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid and bh.serbookhinvoiced=1 and los.sercallbkhcancelled=0
group by sercallbkhitemid,serbookhshopid, serbookhcompanyid, v.itemdescription,
a.itemdescription, a.itemcode, a.part_Code, a.modelno, a.brand, los.sercallbkhcategid'
GO
/****** Object:  View [dbo].[vwRequestQuotationPurchase]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestQuotationPurchase]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwRequestQuotationPurchase] As
Select pohShopID ShopIDPO,pohRequestID RequestIDPO,pohPOID,pohPONO ,pohpoDate,pohQuotationID,ShopIDQut,RequestIDQut,
	QuotationID,QuotationNo,QuotationDate,pohQuotationID RequestID,
	ShopIDReq,RequestIDReq,HqRequestID,HqRequestNo,HqRequestDate from lopurchaseorderheader
Left Outer Join
	(Select pohShopID ShopIDQut,pohRequestID RequestIDQut,pohPOID QuotationID,pohPONO QuotationNo ,pohpoDate QuotationDate,pohQuotationID RequestID ,
	ShopIDReq,RequestIDReq,HqRequestID,HqRequestNo,HqRequestDate
	from lopurchaseorderheader 	
	Left Outer Join
		(Select pohShopID ShopIDReq,pohRequestID RequestIDReq,pohPOID HqRequestID,pohPONO HqRequestNo,pohpoDate HqRequestDate
			 From lopurchaseorderheader where pohType=''R'' And  pohCancel=0)PurchaseRequest
	ON HqRequestID=pohQuotationID
	where pohType=''Q''And  pohCancel=0)RequestQuotation
ON QuotationID=pohQuotationID
where pohType=''P''And  pohCancel=0'
GO
/****** Object:  View [dbo].[vwreceiptvouchercreditdetails]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptvouchercreditdetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwreceiptvouchercreditdetails    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
CREATE view [dbo].[vwreceiptvouchercreditdetails] as
select rcd.CompanyID, rcd.ReceiptID, a.accountdesc, Amount from aaccountmaster a,
receiptvouchercreditdetails rcd where a.companyid =  rcd.companyid and
a.accountid = rcd.accountid'
GO
/****** Object:  View [dbo].[vwhpCustomerLedger]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpCustomerLedger]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by : Shinu
Created on : 12/12/2007
Modified by :
Modified on :
Purpose : To Get all the hire purchase Receivables of customers
Modified by : Benzigar
Purpose : To add cheque Details
------------------------------
Modified By : Nidheesh P V
Modified on :04/03/10
comments : added HP reprocessing after settlement
:(HPAdjAmount+Balance Interst Amount)=custAmnt will be in the
:debit side of the ledger.
------------------------------
Modified By : Nidheesh P V
Modified on :16/11/11
comments : Corrected the HQ HP receipt settled amout.
deducted the credited amount from total amount.
Reference: RefNo:1
*/ -------------------------------
CREATE view [dbo].[vwhpCustomerLedger] 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''
-------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
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 ashops s on reh.hprhShopId=s.ShopID
inner join aCustomerMaster c on reh.hprhCustomerId=c.CustomerID
where reh.hprhCancel=0
---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, --RefNo:1 commented and added below
convert(numeric(18,2),(((rph.hprhamount/rph.hprhBankExRate)*rph.hprhCusExRate)-
(case when isnull(hprhcreditaccid,0)<>0 then isnull((hprhCreditAmount/hprhcreditExRate)*rph.hprhCusExRate,0) else 0 end))) pmtamt,
datediff(dd,rph.hprhReceiptDate,getdate())age,rph.hprhUpdatedTime,
0.0 cinvamt,
--convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhComExRate)) cpmtamt,  --RefNo:1 commented and added below
convert(numeric(18,2),(((rph.hprhamount/rph.hprhBankExRate)*rph.hprhComExRate)-
(case when isnull(hprhcreditaccid,0)<>0 then isnull((hprhCreditAmount/hprhcreditExRate)*rph.hprhComExRate,0) else 0 end))) cpmtamt,
rph.hprhFinancialID,0.0 Dinvamt,
--convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhDepExRate)) dpmtamt,  --RefNo:1 commented and added below
convert(numeric(18,2),(((rph.hprhamount/rph.hprhBankExRate)*rph.hprhDepExRate)-
(case when isnull(hprhcreditaccid,0)<>0 then isnull((hprhCreditAmount/hprhcreditExRate)*rph.hprhDepExRate,0) else 0 end))) 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
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
/****** Object:  View [dbo].[vwHPAgreementDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPAgreementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by :  Shinu
Created on : 30/05/2008
Modified by :
Modified on :
Purpose      : To Get the Hire Purchase Agreement Details
*/
Create View [dbo].[vwHPAgreementDetails] As
select ag.hpCompanyID,hpFinancialId,hpAgreementID,hpAgreementNo,hpAgreementDate,
hpItemRegID,IRShipment,IRMode,ColorName,IRItemID,ItemDescription,SoldColor,
IRFrameNo,IREngineNo,IRModelNo,IRCase,RegNo,IRRoadWorthiness,
hpQuotationId,hpqhQuotationNo,ag.hpCustID,hpCustName,hpCancel,hpConfirmed
from ahpAgreementDetail ag
Left Outer Join  vwHPItemRegistrationDetails ON ag.hpCompanyID=IRCompanyID And hpItemRegID=IRRegistrationID
left Outer join losHpInvoiceHeader ON hpqhCompanyID=ag.hpCompanyID And hpQuotationId=hpqhQuotationID
left Outer join losHPCustomerDetails ac ON ag.hpCompanyID=ac.hpCompanyID And ag.hpCustID=ac.hpCustID'
GO
/****** Object:  View [dbo].[vwHPSettlements]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPSettlements]'))
EXEC dbo.sp_executesql @statement = N'
/*
--------------------------------------------------------------------------------
Created by   : Shinu
Created on   : 12/12/2007
Modified by  : Prasanth
Modified on  : 21/05/2009
Purpose      : To Get all the hire purchase Settlements of customers
Modified For : Ge the Account Receipt settlement, separatly for each Payment.
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on :04/03/10
comments : added HP reprocessing after settlement
:(HPAdjAmount+Balance Interst Amount)=custAmnt will be in the
:debit side of the ledger.
--------------------------------
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on :29/09/10
comments : Included the case of partial settlements in the part od HP Account receipts.
Added the condition ''''hprhtype is null'''' to check partial settlment and used ''''hprhAmount''''
to find the total amount settled by the account receipt
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on :16/11/11
comments :  corrected the HQ HP Account receipt amount
Reference: RefNo:1
*/ --------------------------------
CREATE VIEW [dbo].[vwHPSettlements] as
--- Hp Settlements
select
reh.hprhCustomerID CustomerID,reh.hprhReceiptNo ReceiptNo ,reh.hprhCompanyID  CompanyID,red.hprdInvoiceID InvoiceID,
reh.hprhShopId ShopID, reh.hprhReceiptDate SettledDate, s.DepartmentID, sum(hprdSettelmentAmount) SettledAmt,''HPR'' AS Type
from
loshpreceiptheader reh,loshpreceiptDetail red,  ashops s
where
reh.hprhReceiptID=red.hprdReceiptID and reh.hprhShopID=red.hprdShopID
and reh.hprhCancel=0   and reh.hprhShopId=s.ShopID and hprhReceiptType=''S''
group By reh.hprhCustomerID ,reh.hprhReceiptNo  ,reh.hprhCompanyID  ,red.hprdInvoiceID ,
reh.hprhShopId , reh.hprhReceiptDate , s.DepartmentID
--- HP Advance Receipts
union all
select
reh.hprhCustomerID CustomerID,reh.hprhReceiptNo ReceiptNo ,reh.hprhCompanyID  CompanyID,hpqhQuotationID InvoiceID,
reh.hprhShopId ShopID, reh.hprhReceiptDate SettledDate, s.DepartmentID, hprhReceiptAmount SettledAmt,''HPR'' AS Type
from
loshpreceiptheader reh 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''
Union All
--HP Account Receipts
select
hprhCustomerID,hprhReceiptNo ,hprhCompanyID ,hprdPaymentID,0,hprhReceiptDate , hprhDepartmentID
--convert(numeric(18,2),((hphPaymentAmount/ hprhBankExRate)* hprhCusExRate)) settledamt,   --RefNo:1 commented and added below
,convert(numeric(18,2),((rpd.hprdSettledAmnt/rph.hprhBankExRate)*rph.hprhCusExRate))settledamt
,''HQHPR''
from
ahpReceiptHeader rph ,ahpReceiptDetail rpd
where
hprhCompanyID=hprdCompanyID And hprhDepartmentID=hprdDepartmentID And hprhReceiptID =hprdReceiptID
And hprhCancel=0 and rpd.hprdSettledAmnt <>0
union all
---Adjustment Carrying Amount
select
phR.hphCustomerID,phR.hphProcessingNo as ReceiptNo ,phR.hphCompanyID,phR.hphInvoiceID as InvoiceID,a.hprhShopID as ShopID,phR.hphProcessingDate as SettledDate,
phR.hphDepartmentID as DepartmentID,(phR.hphAdjustmentAmount) as settledamt,''HP Adjustment''  AS Type
from ahpprocessingheader phA inner join ahpprocessingheader phR
on phA.hphprocessingid=phR.hphreferenceid and phA.hphdepartmentid=phR.hphdepartmentid
inner join
(select distinct hprdProcessingId,hprdInvoiceID,hprhCustomerID,hprhShopID from loshpreceiptheader h inner join loshpreceiptdetail d on h.hprhShopID=d.hprdShopID
and h.hprhReceiptID=d.hprdReceiptID where h.hprhCancel=0)a
on pha.hphProcessingID=a.hprdProcessingId and phr.hphInvoiceID=a.hprdInvoiceID and phr.hphCustomerID=a.hprhCustomerID
where phA.hphamended=1 and phR.hphreprocessaftersettlement=1 and phR.hphcancel=0'
GO
/****** Object:  View [dbo].[vwhpSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
--select * from vwhpSettlementDetails where hprdProcessingId=236
--created By: Nidheesh P V
CREATE view [dbo].[vwhpSettlementDetails] as
select hprhCompanyID,hprhReceiptID,hprhReceiptNo,Date[hprhReceiptDate],hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,DepartmentID from
(select vrcpt.*,DepartmentID from
(---to select the first settled date for a cheque------
select vrcdate.hprhCompanyID,vrcid.hprhReceiptID,vrcid.hprhReceiptNo,vrcdate.date,vrcdate.hprdInvoiceID,vrcdate.hprdProcessingId,vrcdate.hprdProcessingDetailId,vrcdate.hprhCustomerID,vrcdate.hprhShopID,vrcdate.hprhReceiptType from
(select hprhCompanyID,min(hprhReceiptDate)date,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprhCustomerID,hprhShopID,hprhReceiptType
from loshpreceiptheader inner join loshpreceiptdetail on
hprhShopID=hprdShopID and hprhReceiptID=hprdReceiptID and hprhCancel=0 and hprhCompanyID=hprdCompanyID --and hprdProcessingId=236
group by hprhCompanyID,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprhCustomerID,hprhShopID,hprhReceiptType
)vrcdate
inner join
(select hprhCompanyID,hprhReceiptID,hprhReceiptNo,hprhReceiptDate,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprhCustomerID,hprhShopID,hprhReceiptType
from loshpreceiptheader inner join loshpreceiptdetail on
hprhShopID=hprdShopID and hprhReceiptID=hprdReceiptID and hprhCancel=0 and hprhCompanyID=hprdCompanyID --and hprdProcessingId=236
)vrcid
on vrcdate.hprdInvoiceID=vrcdate.hprdInvoiceID and vrcdate.hprdProcessingId=vrcid.hprdProcessingId
and vrcdate.hprdProcessingDetailId=vrcid.hprdProcessingDetailId and vrcid.hprhReceiptDate=vrcdate.date and vrcid.hprhCustomerID=vrcdate.hprhCustomerID
)vrcpt
---to select the first settled date for a cheque------
inner join loshpinvoiceheader on vrcpt.hprdInvoiceID=hpqhQuotationID and hpqhCustomerID=vrcpt.hprhCustomerID and vrcpt.hprhShopID=hpqhShopID
inner join ashops on hprhShopID=shopid
left outer join
(ahppaymentheader inner join  ahppaymentdetail on hphPaymentID=hpdPaymentID
and hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID and hphCancel=0)
on hpdReceiptID=hprhReceiptID and hpdDepartmentID=DepartmentID and hphCustomerID=hpqhCustomerID
where vrcpt.hprhReceiptType=''s'' and hpqhCancel=0 and hpqhType=''I'' and hphPaymentID is null
)rcpt
UNION ALL
select vwrcpt.hprhCompanyID,hprhReceiptID,hprhReceiptNo,vwrcpt.date,vwrcpt.hprdInvoiceID,
vwrcpt.hprdProcessingId,vwrcpt.hprdProcessingDetailId,vwrcpt.DepartmentID  from
ahpReceiptHEader h inner join ahpReceiptdetail d on hprdReceiptID=hprhReceiptID and hprdDepartmentID=hprhDepartmentID
and hprhCancel=0
inner join
(
select distinct rh.hprhCompanyID,min(arh.hprhReceiptDate)date, vpay.hphCustomerID,vpay.hphPaymentID,--(if partial settlemnt is done ,it takes min date)
hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,DepartmentID
from loshpreceiptheader rh inner join loshpreceiptdetail on  hprhCompanyID=hprdCompanyID and
hprhShopID=hprdShopID and hprhReceiptID=hprdReceiptID and hprhCancel=0 and hprhReceiptType=''s''--and hprdProcessingId=236
inner join loshpinvoiceheader on hprdInvoiceID=hpqhQuotationID and hpqhCustomerID=hprhCustomerID and hprhShopID=hpqhShopID and hpqhCancel=0 and hpqhType=''I''
inner join ashops on hprhShopID=shopid
inner join
(
----to select latest payment raised against a receipt----
select vpayid.hphPaymentID,vpdate.hpdReceiptID,vpdate.hpdDepartmentID,vpdate.hphCustomerID,vpdate.hpdProcessingDetailID from
(select hpdReceiptID,hpdDepartmentID,max(hphPaymentDate)date,hphCustomerID,hpdProcessingDetailID from ahppaymentheader inner join  ahppaymentdetail
on hphPaymentID=hpdPaymentID and hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphCancel=0 group by hpdReceiptID,hpdDepartmentID,hphCustomerID,hpdProcessingDetailID)vpdate
inner join
(select hphPaymentID,hpdReceiptID,hpdDepartmentID,hphPaymentDate,hphCustomerID,hpdProcessingDetailID from ahppaymentheader inner join  ahppaymentdetail
on hphPaymentID=hpdPaymentID and hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphCancel=0)vpayid
on vpdate.hpdReceiptID=vpayid.hpdReceiptID and vpdate.hpdDepartmentID=vpayid.hpdDepartmentID and vpdate.hphCustomerID=vpayid.hphCustomerID
and vpdate.hpdProcessingDetailID=vpayid.hpdProcessingDetailID and vpayid.hphPaymentDate=vpdate.date
--where  vpdate.hphCustomerID= 1170
----to select latest payment raised against a receipt----
)vpay
on vpay.hpdReceiptID=hprhReceiptID and vpay.hpdDepartmentID=DepartmentID and vpay.hphCustomerID=hpqhCustomerID
and hprdProcessingDetailId=vpay.hpdProcessingDetailID
inner join
(
ahpReceiptHEader arh inner join ahpReceiptdetail ard on hprdReceiptID=hprhReceiptID and hprdDepartmentID=hprhDepartmentID
and hprhCancel=0
) on vpay.hphPaymentID=hprdPaymentID and hprdDepartmentID=vpay.hpdDepartmentID
group by rh.hprhCompanyID,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,DepartmentID ,vpay.hphCustomerID,vpay.hphPaymentID
)vwrcpt
on h.hprhCompanyID=vwrcpt.hprhCompanyID and vwrcpt.hphCustomerID=h.hprhCustomerID
and vwrcpt.date=h.hprhReceiptDate
and h.hprhDepartmentID=vwrcpt.DepartmentID
and vwrcpt.hphPaymentID=d.hprdPaymentID'
GO
/****** Object:  View [dbo].[vwJournalDetailOneName]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalDetailOneName]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- Modified on    : 24/11/2003
-- Modified by    : Kishore
-- Comments       : Added PostGroup Is null condition
-------------------------------------------------------------------------------------------------------------
-- RefNo:1
-- Modified on    : 22/01/2012
-- Modified by    : MANUNADH.U
-- Comments       : To show ''particulars'' correctly, add a condition to link with ataxcategorymaster.
-------------------------------------------------------------------------------------------------------------
-- RefNo:2
-- Modified on    : 16/03/2012
-- Modified by    : Jyothish SR
-- Comments  Roll Back to previous querry. journal passed againt GSTa/c is not listed Legdger Report
--   the DSM-797440
CREATE VIEW [dbo].[vwJournalDetailOneName] AS
-- <<RefNo:1>>----Previous Code
select jd.companyid, jd.journalid,case when jd.journalcredit =1 then ''Cr''  when jd.journalcredit =0 then ''Dr''
end as Posting,case when jd.accountid is not null then acc.accountdesc
when jd.customerid is not null then c.customername  when jd.vendorid is not null then v.vendorname
end as particulars
from moajournaldetails jd
left outer join aaccountmaster acc   on jd.companyid = acc.companyid and jd.accountid = acc.accountid
left outer join avendormaster v   on jd.companyid = v.companyid and  jd.vendorid = v.vendorid
left outer join acustomermaster c   on jd.companyid = c.companyid and jd.customerid = c.customerid
,moajournalheader jh
where jh.companyid = jd.companyid   and jh.journalid = jd.journalid   and jh.cancel = 0  and jd.PostGroup IS NULL
--<<RefNo:1>>----Previous Code
-- <<RefNo:1>>----New Code
--select distinct jd.companyid, jd.journalid,case when jd.journalcredit =1 then ''Cr''  when jd.journalcredit =0 then ''Dr''
-- end as Posting,case when jd.accountid is not null then acc.accountdesc
-- when jd.customerid is not null then c.customername  when jd.vendorid is not null then v.vendorname
-- end as particulars ,jd.accountid , T.TaxAccountId
--from moajournaldetails jd
-- left outer join aaccountmaster acc   on jd.companyid = acc.companyid and jd.accountid = acc.accountid
-- left outer join avendormaster v   on jd.companyid = v.companyid and  jd.vendorid = v.vendorid
-- left outer join acustomermaster c   on jd.companyid = c.companyid and jd.customerid = c.customerid
-- left outer join  moajournalheader jh on jh.companyid = jd.companyid   and jh.journalid = jd.journalid   and jh.cancel = 0
-- left outer join ataxcategorymaster T  on t.TaxAccountId=jd.AccountID AND jd.companyid = T.TaxCompanyId
-- left outer join ataxcategorymaster T1  on t.TaxInputAccountId=jd.AccountID AND jd.companyid = T1.TaxCompanyId
--where    jd.PostGroup IS NULL and (T.TaxAccountId is null and T1.TaxInputAccountId is null)
-- <<RefNo:1>>----New Code'
GO
/****** Object:  View [dbo].[vwjournaldebitcreditamt]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldebitcreditamt]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------
-- Created by      : Rajesh Kamalakshan
--Created date:    :  23-12-2011
-- Comments        : Created fo Magnolia Trial Diffrence Finder Tool
--------------------------------------------------------------------------------------
create view [dbo].[vwjournaldebitcreditamt] as
select  DepartmentID , companyid, journalid, sum(debitc) cdebit, sum(creditc) ccredit,sum(debitd) ddebit, sum(creditd) dcredit from
(select jd.DepartmentID , jh.companyid, jh.journalid, sum(amount)debitc, 0 as creditc,sum(depamount)debitd, 0 as creditd  from MOaJournalDetails
jd, MOaJournalHeader jh
where jh.journalid = jd.journalid and jh.companyid = jd.companyid
and jh.cancel =0 and jd.journalcredit = 0 and (accountid is not null or vendorid is not null
or customerid is not null)
group by jh.companyid, jh.journalid   ,jd.DepartmentID
union all
select jd.DepartmentID, jh.companyid, jh.journalid, 0 as debitc, sum(amount) creditc,0 as debitd, sum(depamount) creditd from MOaJournalDetails
jd, MOaJournalHeader jh
where jh.journalid = jd.journalid and jh.companyid = jd.companyid
and jh.cancel =0 and jd.journalcredit = 1 and (accountid is not null or vendorid is not null
or customerid is not null)
group by jh.companyid, jh.journalid, jd.DepartmentID  ) one
group by companyid, journalid, DepartmentID'
GO
/****** Object:  View [dbo].[vwJournalCheckList]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalCheckList]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 		: 28/12/02
-- Modified by 		: dheena
-- Comments 		: add dep id
------------------------------------------------------------------------------------------
-- Modified on		: 30/08/2003
-- Modified by          : Kishore
-- Comments             : Added UpdateTime column
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwJournalCheckList] AS
select jh.CompanyID, jh.JournalTransID, JournalNo,
JournalTransDate, jh.Remarks, Cancelled,
Posted, am.accountdesc, case journaltranscredit when 0 then ''Dr'' when 1 then ''Cr'' end
debitcredit, dm.departmentname, amount,
jd.remarks dtlremarks,jh.departmentid deptid,
jh.UpdateTime
from journaltransheader jh, journaltransdetails jd,
aaccountmaster am, adepartmentmaster dm
where jh.companyid = jd.companyid
and jh.journaltransid = jd.journaltransid
and jd.companyid = am.companyid
and jd.accountid = am.accountid
and jd.companyid = dm.companyid
and jh.departmentid = dm.departmentid'
GO
/****** Object:  View [dbo].[vwadvancepaidReturn]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidReturn]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwadvancepaidReturn] as
select prhReturnID, prhCompanyID, prhVendorId from loPurchaseReturnheader where prhcancelled = 0'
GO
/****** Object:  View [dbo].[new1]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[new1]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[new1]
as
select top 2 * from ashops order by shopid'
GO
/****** Object:  View [dbo].[purchsetracking]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchsetracking]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[purchsetracking] as
select a.pohquotationid as Qid,case when a.pohquotationid is not null then ab.pohpono end as
QuatationNo,ab.pohquotationid from
loPurchaseOrderHeader a left outer join loPurchaseOrderHeader ab
on a.pohquotationid=ab.pohpoid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldExchangeRates1]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldExchangeRates1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  on 	: 21/07/2003
--Created  by 	: R Harikrishnan
--Comments	: To correct all the exchange rates in a table
-----------------------------------------------------------------------------------------
--Modified on 	: 25/08/2003
--Modified by 	: R Harikrishnan
--Comments	: Modified for updating the Vendor Customer Exchange Rates in Payments
--		: and receipts
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateOldExchangeRates1]
	@intGodownID 		as int,
	@intShopID 		as int,
	@intDepartmentID 	as int,
	@intCompanyID 		as int,
	@intCustomerID 		as int,
	@intVendorID 		as int,
	@intAccountID 		as int,
	@intPurShopID 		as int,
	@intTransID 		as int,
	@strTableName 		as varchar(250),
	@strConExRateColName 	as varchar(250),
	@strDepExRateColName 	as varchar(250),
	@strExRatesColName 	as varchar(250),
	@strPKColName1	 	as varchar(250),
	@strPKColName2	 	as varchar(250),
	@strPKColName3	 	as varchar(250),
	@strPKColName3Value	as varchar(250),
	@strPKType 		as char(1)--''S'' for ShopID
					  --''G'' for GodownID
					  --''C'' for CompanyID
as
begin
	--set @strTableName=''AccountsInvoiceHeader''
	--set @strPKColName1=''DepartmentID''
	--set @strPKColName2=''InvoiceID''
	--set @strPKType=''C''
	--set @strConExRateColName=''ExchangeRate''
	--set @strDepExRateColName=''depexrate''
	--set @strExRatesColName=''exchangerates''
	--set @intDepartmentID=15
	--set @intCompanyID=1
	--set @intAccountID=258
	Declare @intConCurrID 		as int,
		@intDepCurrID 		as int,
		@intCusCurrID 		as int,
		@intVenCurrID 		as int,
		@intAccCurrID 		as int,
		@intPurShopCurrID	as int,
		@strType		as char(1),
		@strexrates  	 	as varchar(250),
		@strWhereCondition	as varchar(250),
		@strSql 		as nvarchar(2000),
		@numConExRate		as numeric(18,8),
		@numDepExRate		as numeric(18,8),
		@numVenCustExRate	as numeric(18,8)
	--setting the Exchange rates string
	set @strexrates=''1:2:3:4:5:6:7:8:-12.85:1:3.77:1.73:0.91:1.62:0.63:50:''
	--getting the Customer currency ID
	if @intCustomerID is not null
	begin
		set @intVendorID=null
		set @intPurShopID=null
		set @strType=''C''
		select
			@intCusCurrID=currencyID
		from
			aCustomerMaster
		where
			companyID=@intCompanyID and CustomerID=@intCustomerID
	end
	--getting the Vendor currency ID
	if @intVendorID is not null
	begin
		set @intPurShopID=null
		set @strType=''V''
		select
			@intVenCurrID=currencyID
		from
			aVendorMaster
		where
			companyID=@intCompanyID and VendorID=@intVendorID
	end
	--getting the Account currency ID
	if @intAccountID is not null
	begin
		set @intPurShopID=null
		set @strType=''A''
		select
			@intAccCurrID=currencyID
		from
			aAccountMaster
		where
			companyID=@intCompanyID and AccountID=@intAccountID
	end
	--Setting the type if both is not null
	if (@intVendorID is not null and @intAccountID is not null and @strPKType=''R'')
	begin
		set @strType=''T''
	end
	--Setting the type if both is not null
	if (@intCustomerID is not null and @intAccountID is not null and @strPKType=''R'')
	begin
		set @strType=''U''
	end
	--getting the Account currency ID
	if @intPurShopID is not null and @strPKType<>''J''
	begin
		set @strType=''D''
		select
			@intPurShopCurrID=d.depCurrencyID
		from
			aShops s, aDepartmentMaster d
		where
			s.DepartmentID=d.departmentID and s.companyID=d.CompanyID and
			s.ShopID = @intPurShopID and s.CompanyID=@intCompanyID
	end
	if (@intPurShopID is not null and @strPKType=''J'')
	--If type is ''J'' then @intPurShopID will be the DepartmentId column value of the
	--Journal Table
	begin
		set @strType=''D''
		select
			@intPurShopCurrID=d.depCurrencyID
		from
			aDepartmentMaster d
		where
			d.departmentID = @intPurShopID and d.CompanyID=@intCompanyID
	end
	--getting the department currency ID if a GodownID is passed
	if @intGodownID is not null
	begin
		set @intShopID=null
		set @intDepartmentID=null
		select
			@intDepCurrID=d.depCurrencyID
		from
			agodown g, aDepartmentMaster d
		where
			g.departmentID=d.departmentID and g.companyID=d.CompanyID and
			g.GodownID=@intGodownID and g.CompanyID=@intCompanyID
	end
	--getting the department currency ID if a shopid is passed
	if @intShopID is not null
	begin
		set @intDepartmentID=null
		select
			@intDepCurrID=d.depCurrencyID
		from
			aShops s, aDepartmentMaster d
		where
			s.DepartmentID=d.departmentID and s.companyID=d.CompanyID and
			s.ShopID = @intShopID and s.CompanyID=@intCompanyID
	end
	--getting the department currency ID if a departmentID is passed
	if @intDepartmentID is not null
	begin
		select
			@intDepCurrID=d.depCurrencyID
		from
			aDepartmentMaster d
		where
			D.departmentID = @intDepartmentID and d.CompanyID=@intCompanyID
	end
	--getting the consolidation currency ID
	select
		@intConCurrID=CurrencyID
	from
		acompanymaster
	Where
		Companyid=@intCompanyID
	
	--getting the consolidation exchange rate and the department exchange rate ]
	--when  the base currency is a customer
	if @strType=''C''
	begin
		
		exec spGetExchangeRate @intCompanyID, @intCusCurrID,  @intConCurrID,
		    @numConExRate output
		exec spGetExchangeRate @intCompanyID, @intCusCurrID,  @intDepCurrID,
		    @numDepExRate output
	end
	--getting the consolidation exchange rate and the department exchange rate ]
	--when  the base currency is a vendor
	if @strType=''V''
	begin
		exec spGetExchangeRate @intCompanyID, @intVenCurrID,  @intConCurrID,
		    @numConExRate output
		exec spGetExchangeRate @intCompanyID, @intVenCurrID,  @intDepCurrID,
		    @numDepExRate output
	end
	--getting the consolidation exchange rate and the department exchange rate ]
	--when  the base currency is an account
	if @strType=''A''
	begin
		exec spGetExchangeRate @intCompanyID, @intAccCurrID,  @intConCurrID,
		    @numConExRate output
		exec spGetExchangeRate @intCompanyID, @intAccCurrID,  @intDepCurrID,
		    @numDepExRate output
	end
	
	if @strType=''T''
	Begin
		exec spGetExchangeRate @intCompanyID, @intVenCurrID ,  @intAccCurrID,
		    @numVenCustExRate output
	End
	if @strType=''U''
	Begin
		exec spGetExchangeRate @intCompanyID, @intCusCurrID ,  @intAccCurrID,
		    @numVenCustExRate output
	End
	--getting the consolidation exchange rate and the department exchange rate ]
	--when  the base currency is another department currency
	if @strType=''D''
	begin
		exec spGetExchangeRate @intCompanyID, @intPurShopCurrID,  @intConCurrID,
		    @numConExRate output
		exec spGetExchangeRate @intCompanyID, @intPurShopCurrID,  @intDepCurrID,
		    @numDepExRate output
	end
	--Making the where condition
	select
		@strWhereCondition= @strPKColName1 + ''='' +
		case 	when @strPKType=''S'' then convert(varchar(5),isnull(@intShopID,0))
			when @strPKType=''G'' then convert(varchar(5),isnull(@intGodownID,0))
			when @strPKType=''C'' then convert(varchar(5),isnull(@intDepartmentID,0))
			when @strPKType=''J'' then convert(varchar(5),isnull(@intDepartmentID,0))
			when @strPKType=''R'' then convert(varchar(5),isnull(@intDepartmentID,0))
		end + '' and '' +
		@strPKColName2 + ''='' + convert(varchar(10),isnull(@intTransID,0))
	--If @strPKColName3 is not null (ie. there is a third column in the primary key)
	--then concatinating it with the where condition
	if isnull(@strPKColName3,'''')<>''''
		set @strWhereCondition=@strWhereCondition + '' and '' + @strPKColName3 + ''='' +
			@strPKColName3Value
	--Making the update statement based on the paramenters passed
	if @strPKType=''R''
		set @strSql=''update '' + @strTableName + '' set '' +
			@strConExRateColName +''='' + convert(varchar(50),@numVenCustExRate) +
			'' where '' + @strWhereCondition
	else
		set @strSql=''update '' + @strTableName + '' set '' +
			@strConExRateColName +''='' + convert(varchar(50),@numConExRate) + '','' +
			@strDepExRateColName +''='' + convert(varchar(50),@numdepExRate) + '','' +
			@strExRatesColName +''='''''' + @strexrates +
			'''''' where '' + @strWhereCondition
	exec sp_ExecuteSQl  @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldCostPrice]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldCostPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------
--Created on 	: 21/07/2003
--Created by 	: R Harikrishnan
--Comments	: To correct all the cost price in a detail table according to the
--		: Header table column name
-----------------------------------------------------------------------------------------
CREATE Procedure [dbo].[spUpdateOldCostPrice]
	@intCompanyID 		as int,			--The companyID (mandatory)
	@strTableName 		as varchar(250), 	--The name of the table(Mandatory)
	@strDetailTableName 	as varchar(250), 	--The name of the Detail table(Mandatory)
	@strWherecondition	as varchar(250),	--The where condition (Optional)
	@strCostPriceColName 	as varchar(250),	--The consolidation exchange rate
							--column name of the strTablename
	@strPKColName1	 	as varchar(250),	--The first primary column name of the
							--strTablename (shopID,companyID,GodownID)
							--(Mandatory)
	@strPKColName2	 	as varchar(250),	--The second primary column name of the
							--strTablename (Mandatory)
	@strPKColName3	 	as varchar(250),	--The third primary column name of the
							--strTablename (Optional)
	@strCustIDColName 	as varchar(250),	--The customerID column name of
							--strTablename (Optional)
	@strAccIDColName 	as varchar(250),	--The AcountID column name of
							--strTablename (Optional)
	@strAccIDValue	 	as varchar(250),	--The account value of the transaction
							--strTablename (InventoryID)(Optional)
	@strPKType 		as char(1)		--''S'' for ShopID
							--''G'' for GodownID
					  		--''C'' for CompanyID
as
begin
	--	Commented for testing purpose
	--	set @intCompanyID=1
	--	set @strTableName=''losPosHeader h, losPosDetail d''
	--	set @strDetailTableName=''losPosDetail''
	--	set @strWherecondition=''where h.poshShopID=d.posdShopID and h.poshBillID=d.posdBillID and h.poshBillID=1 ''
	--	set @strCostPriceColName=''posdcostprice''
	--	set @strPKColName1=''posdShopID''
	--	set @strPKColName2=''posdBillID''
	--	set @strPKColName3=null
	--	set @strCustIDColName=null
	--	set @strAccIDColName=''poshCashAccID''
	--	set @strAccIDValue=224
	--	set @strPKType=''S''
	if isnull(@strCustIDColName,'''')='''' and isnull(@strAccIDColName,'''')=''''
	begin
		Select ''Pass either a customerid column name or an accountID column name''	
		return 0
	end
	
	if isnull(convert(int,@strAccIDValue),0)=0
	begin
		Select ''Pass the Inventory currency''	
		return 0
	end
	if isnull(@strTableName,'''')=''''
	begin
		Select ''Pass the table name''	
		return 0
	end
	if isnull(@strDetailTableName,'''')=''''
	begin
		Select ''Pass the detail table name''	
		return 0
	end
	if isnull(@strWherecondition,'''')=''''
	begin
		Select ''Pass the detail where condition.''	
		return 0
	end
	if not exists (Select 1 from sysobjects where name =''CostPriceUpdations'' and type=''U'')
		begin
			Create Table CostPriceUpdations
			(
				pkCol1Value	int not null,
				pkCol2Value	int not null,
				pkCol3Value	int null,
				DetailTableName varchar(250) not null
			)
			
		end
	Create Table #TempExRates
	(
		PkCol1		int not null,
		PkCol2		int not null,
		PkCol3		int null,
		CostPrice	numeric(20,4) null,
		CustomerID	int null,
		AccountID	int null
	)
	declare @strSql 		as nVarchar(2000),
		@intCount		as int,
		@intPK1			as int,
		@intPK2			as int,
		@intPK3			as int,
		@intLoopCount		as int,
		@intCustomerID 		as int,
		@intAccountID 		as int,
		@numCostPrice		as numeric(18,4),
		@intAccCurrID		as int,
		@intCusCurrID		as int,
		@intInvCurrID		as int,
		@strType		as char(1),
		@numInvExRate		as numeric(18,8),
		@strUpdWhereCondition	as varchar(1000)
	set @strSql= ''select '' + @strPKColName1 + '','' + @strPKColName2 + '','' +
		isnull(@strPKColName3,''Null'') + '','' + isnull(@strCostPriceColName,0) + '','' +
		isnull(@strCustIDColName,''Null'') + '','' +
		isnull(@strAccIDColName,''Null'') +
		'' from '' + @strTableName + '' '' + isnull(@strWherecondition,'''')
	--inserting the details into the temporary table
	insert into #TempExRates
		exec sp_executesql @strSql
	--For Inventory Account Currency ID
	if @strAccIDValue is not null
	begin
		select
			@intInvCurrID=currencyID
		from
			aAccountMaster
		where
			companyID=@intCompanyID and AccountID=convert(int,@strAccIDValue)
	end	
	--Getting the total count
	select
		@intCount=count(a.pkCol2)
	from	
		(select
			distinct PkCol1,pkCol2,pkCol3
		from
			#TempExRates) a
	--Setting the count to the total count	
	set @intLoopCount=@intCount
	while @intLoopCount<>0
	begin
		select top 1
			@intPK1=PkCol1,@intPK2=PkCol2,@intPK3=PkCol3,@intCustomerID=CustomerID,
			@intAccountID=AccountID,@numCostPrice=CostPrice
		from
			#TempExRates order by PkCol1,PkCol2,PkCol3
		--exec spUpdateOldExchangeRates1 @intGodownID,@intShopID@intDepartmentID,
		--@intCompanyID,@intCustomerID,@intVendorID,@intAccountID,
		--@intTransID,@strTableName,@strConExRateColName,@strDepExRateColName,
		--@strExRatesColName,@strPKColName1,@strPKColName2,@strPKColName3,
		--@strPKColName3Value,@strPKType
		--For Customer Currency ID
		if @intCustomerID is not null
		begin
			set @intAccountID=null
			select
				@intCusCurrID=currencyID
			from
				aCustomerMaster
			where
				companyID=@intCompanyID and CustomerID=@intCustomerID
			--Getting the exchange rate
			exec spGetExchangeRate @intCompanyID, @intInvCurrID,  @intCusCurrID,
			    @numInvExRate output
		end
		--For Account Currency ID
		if @intAccountID is not null
		begin
			select
				@intAccCurrID=currencyID
			from
				aAccountMaster
			where
				companyID=@intCompanyID and AccountID=@intAccountID
			--Getting the exchange rate
			exec spGetExchangeRate @intCompanyID, @intInvCurrID,  @intAccCurrID,
			    @numInvExRate output
		end
		select
			@strUpdWhereCondition= @strPKColName1 + ''='' +
			convert(varchar(10),isnull(@intPK1,0)) + '' and '' +
			@strPKColName2 + ''='' + convert(varchar(10),isnull(@intPK2,0))
		--If @strPKColName3 is not null (ie. there is a third column in the primary key)
		--then concatinating it with the where condition
		if isnull(@strPKColName3,'''')<>''''
			set @strUpdWhereCondition=@strUpdWhereCondition + @strPKColName3 + ''='' +
				convert(varchar(10),isnull(@intPK3,0))
		
		--Checking whether already the record is updated or not
		if not exists (select 1 from CostPriceUpdations where PkCol1Value=@intPK1 and
			PkCol2Value=@intPK2 and isnull(PkCol3Value,0)=isnull(@intPK3,0) and
			DetailTableName=@strDetailTableName)
		begin
			--Making the update statement based on the paramenters passed
			set @strSql=''update '' + @strDetailTableName + '' set '' +
				@strCostPriceColName +''='' + @strCostPriceColName + '' * '' +  convert(varchar(25),@numInvExRate) +
				'' where '' + @strUpdWhereCondition
			exec sp_ExecuteSQl  @strSql
			insert into CostPriceUpdations
			values(@intPK1,@intPK2,@intPK3,@strDetailTableName)
		end
		--Delete the row after updation
		delete from #TempExRates where
			PkCol1=@intPK1 and PkCol2=@intPK2 and isnull(PkCol3,0)=isnull(@intPK3,0)
	
		set @intLoopCount=@intLoopCount-1
	end
	drop table #TempExRates
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSdummyHeader]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSdummyHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Created By 	: Aneesh
--Created On 	: 14-09-2006
--Purpose    	: To update details to the POS Header Table [LOsPosdummyHeader]
--Modified BY	: Shinu
--Modifies On	: 15-03-2006
--Purpose	: To insert Discount amount In LOsPosdummyHeader
--Modified BY	: Rajesh Kamalskshan
--Modifies On	: 1-05-2007
--Purpose	: for using in dummy pos bill
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdatePOSdummyHeader]
@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,2),
@intDiscount As  Numeric(18,2),
@intBillAmt As  Numeric(18,2),
@intCashAccId As Int,
@intCustId As Int,
@strRemarks As Varchar(250),
@intCmpExRate As  Numeric(18,2),
@intDiscountAmt As  Numeric(18,2),
@confirmed as int
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
--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 LOsPosdummyHeader 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,
poshCounterId=@intCounterId ,poshDiscountAmt=@intDiscountAmt ,poshconfirmed=@confirmed Where poshBillId=@intBillId And poshShopId=@intShopId
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPO]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPO]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLEDgersPO    Script Date: 18/01/2003 9:45:44 PM ******/
--Created on 	: 30/11/2002
--Created by 	: leo
CREATE proc [dbo].[spUpdateLEDgersPO] @intCompanyID as int, @intPOID as int as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@strPOno as varchar(50),
	@dtPODate as datetime,
	@intVendorID as int,
	@strRemarks as varchar(250),
	@intDepartmentID as int,
	@numPOAmt as numeric(18,2),
	@intGITAccid as int,
	@numdepRate as numeric(18,9),
	@numconsRate as numeric(18,9),
	@strexrates as varchar(250),
	@dtutime as datetime,
	@intcurrencyid as int
	
	set nocount on
	
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader WHERE
	CompanyID = @intCompanyID
	select @intGITAccid = POGITAccountid from apackagesettings where companyid =
	@intcompanyid
	SELECT @intPOID=pohPoid, @strPOno=pohpono, @dtPODate=pohPodate, @intVendorID=
	pohVendorID, @numPOAmt=pohvalue, @strRemarks=pohremarks, @intFinancialID= pohfinancialid,
	@intDepartmentid=pohDepartmentid, @numdepRate = pohdepexrate, @numconsrate =
	pohcmpexrate, @dtutime=updatetime, @strexrates = pohexchangerates
	from loPurchaseOrderHeader where pohcompanyid = @intCompanyID and pohPoid=@intPOID
	set @intJournalDetailID = 1
	set @intJournalID = @intJournalID + 1
	select @intcurrencyid = currencyid from avendormaster where companyid = @intcompanyid
	and vendorid = @intvendorid
	if @numPOAmt <> 0
	begin		
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno,
		remarks, financialID,Type,CurrencyID,cancel,realised, chequedate,updatetime)
		values (@intJournalID, @intCompanyID, @dtPODate, @strPOno,
		@strRemarks, @intFinancialID,''PO'',@intcurrencyid,0,0, @dtPODate, @dtutime)			
		/* crediting  the Vendor account with PO amt */
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, vendorID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intVendorID, @numPOAmt * @numconsrate, @numPOAmt,@intDepartmentid,
		@numpoamt * @numdeprate)
			
		set @intJournalDetailID = @intJournalDetailID + 1
		declare @numvendorer as numeric(18,2),
			@numaccer as numeric(18,2),
			@numaccpoamt as numeric(18,2)			
		exec spReturnExrate @intcurrencyid, @strexrates, @numvendorer output
		--to arrive on account currency equivalent, vendorid
		select @intcurrencyid = currencyid from aaccountmaster where
		companyid = @intcompanyid and accountid = @intGITAccid
		exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
		exec spconvertcurrency @numvendorer, @numaccer, @numpoamt, @numaccpoamt output
		 --debit the goods in transit account
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, accountID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intgitaccID, @numPOAmt* @numconsrate,@numaccpoamt , @intDepartmentid,
		@numpoamt * @numdeprate)
	end	
	update loPurchaseOrderHeader  set pohpostED =1 WHERE pohPOID = @intPOID
	and pohCompanyID = @intCompanyID
	
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPCP]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPCP]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spUpdateLEDgersPCP] @intCompanyID as int, @intPCPID as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intRowCount as int,
@intFinancialID as int,
@dtPDate as datetime,
@strPNo as varchar(50),
@strRemarks as varchar(250),
@intDepartmentID as int,
@numAmount as numeric(18,2),
@intPDID as int,
@intPAccountID as int,
@numPAmount as numeric(18,2),
@intPDAccountID as int,
@numPDAmount as numeric(18,2),
@dtutime as datetime,
@intacccurrencyid as int,
@intcurrencyid as int,
@numAccExRate as numeric(18,9),
@numDepExRate as numeric(18,9),
@numComExRate as numeric(18,9),
@numPDAccExRate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,2)
set nocount on
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
SELECT @strPNo = phPaymentNo, @dtPDate = phPaymentDate,
@strremarks = phRemarks, @intFinancialID = phFinancialID, @dtutime = phupdatetime,
@numAccExRate = phExRate,@numComExRate = phComExRate, @numDepExRate = phDepExRate,
@intdepartmentid = phdepartmentid,@numPAmount=phAmount,@intPAccountID=phAccountID
FROM aHqPettyCashPaymentHeader WHERE phcancel =0 and phpostED =0 and
phCompanyID = @intCompanyID and phPaymentid = @intPCPID
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into moajournalheader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, convert(smalldatetime,@dtPDate), @strPNo,  @strRemarks,
@intFinancialID, ''HQPCP'', @intcurrencyID, @dtPdate, @dtutime)
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 1, @intPAccountID,
(@numPAmount/@numAccExRate)*@numComExRate, @numPAmount, @intDepartmentID,
(@numPAmount/@numAccExRate)*@numDepExRate)
set @intJournalDetailID = @intJournalDetailID + 1
Declare DetailCur cursor for
SELECT pdDetailID, pdDebitAccountID, pdAmount,pdExRate  FROM
aHqPettyCashPaymentDetails d, aaccountmaster a WHERE a.companyid = d.pdcompanyid and
a.accountid = d.pdDebitAccountid and a.CompanyID = @intCompanyID and pdPaymentID = @intPCPID
open DetailCur
fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
while @@Fetch_status =0
begin
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 0, @intPDAccountID,
(@numPDAmount/@numPDAccExRate)*@numComExRate, @numPDAmount, @intDepartmentID,
(@numPDAmount/@numPDAccExRate)*@numDepExRate)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update aHqPettyCashPaymentHeader set phpostED =1 WHERE phCompanyID = @intCompanyID and
phPaymentID = @intPCPID
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersPayroll]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersPayroll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created On	: 05/10/2003, 28/02/2004
-- Created By	: R Harikrishnan, Hariharan
-- Comments	: For Payroll Accounts Linking
--		: Given absolute value taking for amounts from account posting table
--------------------------------------------------------
CREATE proc [dbo].[spUpdateLedgersPayroll]
	@intCompanyID 	as int,
	@intTransID 	as int
as
begin
Declare
	@intJournalID 		as int,
	@intJournalDetailID 	as int,
	@intFinancialID 	as int,
	@dtTransDate 		as datetime,
	@strTransNo 		as varchar(50),
	@strRemarks 		as varchar(250),
	@intDepartmentID 	as int,
	@numDrAmount 		as numeric(18,2),
	@numCrAmount 		as numeric(18,2),
	@numCompAmount 		as numeric(18,2),
	@numDepAmount 		as numeric(18,2),
	@intAccountID 		as int,
	@dtutime 		as datetime,
	@intcurrencyid 		as int
set nocount on
	/* getting the maximum Journal ID FROM journal table */
	SELECT
		@intJournalID = isnull(max(JournalID),0)
	FROM
		moajournalheader
	WHERE
		CompanyID = @intCompanyID
	SELECT
		@strTransNo =TransNo, @dtTransDate = TransDate, @strremarks = remarks,
		@dtutime = updatetime, 	@intdepartmentid = departmentid
	FROM
		paPayAccLinkHeader
	WHERE
		cancellED =0 and postED =0 and CompanyID = @intCompanyID and
		TransID = @intTransID
	SELECT
		@intcurrencyID = depCurrencyID
	FROM 	
		adepartmentmaster
	WHERE 	
		CompanyID =@intCompanyID and departmentid = @intdepartmentid
	select
		@intFinancialID = financialID
	from	
		vwfinyearperiod
	where
		@dtTransDate between sdate and edate
	select @dtTransDate
	set @intJournalID = @intJournalID + 1
	set @intJournalDetailID = 1
	insert into moajournalheader
		(JournalID, CompanyID, JournalDate, referenceno,
		remarks, financialID,Type,CurrencyID,chequedate, updatetime)
	values
		(@intJournalID, @intCompanyID, @dtTransDate, @strTransNo,  @strRemarks,
		@intFinancialID, ''PAY'', @intcurrencyID, @dtTransDate, @dtutime)
	Declare DetailCur cursor for
		SELECT
			AccountID, AccCurrID, sum(abs(DebitAmount)), sum(abs(CreditAmount)),
			sum(abs(DeptAmount)), sum(abs(CompAmount))
		FROM
			paPayAccLinkPostingDetails
		WHERE
			CompanyID = @intCompanyID and TransID = @intTransID
		group by
			AccountID, AccCurrID
		
	open DetailCur
	fetch next FROM
		DetailCur
	into
		@intAccountID, @intcurrencyid, @numDrAmount,@numCrAmount, @numDepAmount,
		@numCompAmount
	while @@Fetch_status =0
	begin
		if (@numDrAmount > @numCrAmount)
		Begin
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit,
				AccountID, Amount, actualAmount,departmentid, depamount)
			values
				(@intJournalID, @intJournalDetailID, @intCompanyID, 0,
				@intAccountID, @numCompAmount, @numDrAmount - @numCrAmount,
				@intDepartmentID, @numDepAmount)
			set @intJournalDetailID = @intJournalDetailID + 1
		End
		else if (@numDrAmount < @numCrAmount)
		begin
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit,
				AccountID, Amount, actualAmount,departmentid, depamount)
			values
				(@intJournalID, @intJournalDetailID, @intCompanyID, 1,
				@intAccountID, abs(@numCompAmount), @numCrAmount - @numDrAmount,
				@intDepartmentID, abs(@numDepAmount))
			set @intJournalDetailID = @intJournalDetailID + 1
		end
		
		fetch next FROM
			DetailCur
		into
			@intAccountID, @intcurrencyid, @numDrAmount,@numCrAmount, @numDepAmount,
			@numCompAmount
	end
	Close DetailCur
	Deallocate DetailCur
	/* mark the record as postED */
	update
		paPayAccLinkHeader
	set
		Posted =1
	WHERE
		CompanyID = @intCompanyID and TransID = @intTransID
set nocount off
--rollback tran
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReprocessing]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPReprocessing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------
-- Created Date  : 02/31/2010
-- Created by  : Nidheesh P V
-- Comments  : For HP Re Processing Adjustment,HP Unearned income Posting
------------------------------------------------------
CREATE proc [dbo].[spUpdateLEDgersHPReprocessing] @intCompanyID as int,@intDepartmentID as int,@intProcessingID as int
as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
--@intDepartmentID as int,
@strProcessingNo as varchar(50),
@strRemarks as varchar(300),
@dtutime as datetime,
@dtDate as datetime,
@intcurrencyid as int,
@intAdjustmentAccID as int,
@intInterestAccId as int,
@intCustomerAccID as int,
@CustomerId as int,
@CustomerAmount as numeric(18,2),
@Adjustmentamnt as numeric(18,2),
@UnearnedIncome as numeric(18,2)
select
@intcurrencyid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
Select
@intCustomerAccID =DebtorAcc ,@intAdjustmentAccID=AdjustmentAcc ,@intInterestAccId=SuspenseAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo,
@dtDate=hphProcessingDate, @Adjustmentamnt=hphAdjustmentAmount, @UnearnedIncome=hphBalanceInterest,
@strremarks=hphRemarks,@intFinancialID=hphFinancialID, @CustomerId=hphCustomerID,@dtutime=hphUpdateTime
FROM ahpprocessingdetail left outer join ahpprocessingheader
on hpdprocessingID=hphProcessingID and hpdCompanyID=hphCompanyID and (hphDepartmentID=@intDepartmentID or @intDepartmentID=0)
WHERE hphreprocessaftersettlement=1 and hphReferenceID is not null  and hpdProcessingID=@intProcessingID and hphCompanyID =@intCompanyID
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,updatetime) values
(@intJournalID, @intCompanyID, @dtDate, @strProcessingNo,
@strRemarks, @intFinancialID,''HPRPAS'', @intcurrencyid,@dtutime)
--''HPRPAS''---HP Reprocessing After Settlement
set @intJournalDetailID = 1
if @intAdjustmentAccID<>0  and  @intInterestAccId<>0
begin
/* Debiting Adjustment Carrying Amount in Income account*/
--(@Adjustmentamnt-@UnearnedIncome)===Adjustment Carrying Amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID,0,@intAdjustmentAccID,
(@Adjustmentamnt-@UnearnedIncome) , (@Adjustmentamnt-@UnearnedIncome),@intDepartmentID, (@Adjustmentamnt-@UnearnedIncome), 1)
set @intJournalDetailId = @intJournalDetailId +1
/* Debiting balance HP Interest in Asset account */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intInterestAccId,
@UnearnedIncome,@UnearnedIncome,@intDepartmentID, @UnearnedIncome, 1)
set @intJournalDetailId = @intJournalDetailId +1
set @CustomerAmount= @Adjustmentamnt
/* Crediting against customer account */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@CustomerId ,
@CustomerAmount,@CustomerAmount,@intDepartmentID,@CustomerAmount, 1)
set @intJournalDetailId = @intJournalDetailId +1
/* Crediting against HP Rental receivable in Asset account */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intCustomerAccID ,
@CustomerAmount,@CustomerAmount,@intDepartmentID,@CustomerAmount, 1)
/* mark the record as postED */
update ahpprocessingDetail set hpdPosted =1 WHERE hpdProcessingID= @intProcessingID and hpdDepartmentID=@intDepartmentID
end
end' 
END
GO
/****** Object:  View [dbo].[vwAssets]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssets]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwAssets    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwAssets    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.vwAssets    Script Date: 17/11/2001 9:21:18 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwAssets    Script Date: 09/03/2001 02:32:26 ******/
/****** Object:  View dbo.vwAssets    Script Date: 12/05/00 1:40:14 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 10/17/00 2:19:50 PM ******/
/****** Object:  View dbo.vwAssets    Script Date: 10/7/00 11:07:56 AM ******/
CREATE view [dbo].[vwAssets] as
(select acc.companyid, acc.accountid as accid, max(acc.accountdesc) as accdes,
sum(amount) as puramt, 0 as deptodate
from MOajournaldetails jd, aaccountmaster acc,
agroupmaster gm, asettings s
where gm.companyid = acc.companyid and acc.companyid = jd.companyid and
s.companyid=gm.companyid and jd.accountid = acc.accountid and gm.groupid = acc.groupid and
s.fixedassetgroupid= gm.groupid and jd.journalcredit =0
group by acc.companyid , acc.accountid)
union all
(select acc.companyid, acc.accountid as accid, max(acc.accountdesc) as accdes, 0 as puramt,
sum(amount) as deptodate
from MOajournaldetails jd, aaccountmaster acc, agroupmaster gm,
asettings s
where gm.companyid = acc.companyid and acc.companyid = jd.companyid and s.companyid=gm.companyid
and s.fixedassetgroupid=gm.groupid and jd.accountid = acc.accountid and gm.groupid = acc.groupid
and jd.journalcredit =1
group by acc.companyid ,acc.accountid)'
GO
/****** Object:  View [dbo].[vwAllshops]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllshops]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwAllshops] as
select shopid as sid,shopname as sname from ashops
union
select 0,''HQ'''
GO
/****** Object:  StoredProcedure [dbo].[spValidPlFormats]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spValidPlFormats]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--modified by  : Hariharan
--MOdified Date: 18/09/2002
----------------------------------------------------------------------------------
-- Modified by : Kishore
-- Modified on : 11/06/2003
-- Comments    : given defaultformat bit selection also in the sp result
--               to determine the population in acc reports dll
--               (On comparison with v2)
----------------------------------------------------------------------------------
--Modified By : Nidheesh P V
--Modified on :03/06/2010
--Commenets :commented the part ''and controlledaccount like @strpartchar''.
--:It is able to select accounts for a particular format throug front-end.
--:And also the field ''partionchar''in the table aAccRepFormat was saved as null in the code.
----------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spValidPlFormats] @intCompanyid as int, @strType as char(1) AS
begin
declare @inttotalnoofeandiacc as int,
@inttotalassigned as int,
@intformatid as int,
@strformatname as varchar(100),
@strpartchar as varchar(5)
Create table #formats(
formatid int,
formatname varchar(100))
if @strtype =''p''
select @inttotalnoofeandiacc = count(*)
from aaccountmaster am, agroupmaster gm
where am.companyid = gm.companyid
and am.groupid = gm.groupid
and am.companyid = @intcompanyid
and (gm.accounttype =''e'' or gm.accounttype =''i'')
else
select @inttotalnoofeandiacc = count(*)
from aaccountmaster am, agroupmaster gm
where am.companyid = gm.companyid
and am.groupid = gm.groupid
and am.companyid = @intcompanyid
and (gm.accounttype =''a'' or gm.accounttype =''l'')
and am.accountid <> (select retainedearningsacc
from asettings where companyid = @intCompanyID)
declare fcur cursor for
select formatid, formatname, ''%'' + rtrim(ltrim(partionchar))+''%'' pc from aAccRepFormat
where companyid = @intcompanyid  and type = @strtype
open fcur
fetch next from fcur into @intformatid, @strformatname, @strpartchar
while @@fetch_status = 0
begin
if @strtype =''p''
select  @inttotalassigned = count(*) from aaccountmaster am, agroupmaster gm
where am.companyid = gm.companyid and am.groupid = gm.groupid and am.companyid
= @intcompanyid and (gm.accounttype =''e'' or gm.accounttype =''i'')
--and controlledaccount like @strpartchar
else
select  @inttotalassigned = count(*) from aaccountmaster am, agroupmaster gm
where am.companyid = gm.companyid and am.groupid = gm.groupid and am.companyid
= @intcompanyid and (gm.accounttype =''a'' or gm.accounttype =''l'')
--and controlledaccount like @strpartchar
and am.accountid <> (select retainedearningsacc from asettings where companyid = @intCompanyID)
if (@inttotalnoofeandiacc = @inttotalassigned)
insert into #formats values (@intformatid, @strformatname)
fetch next from fcur into @intformatid, @strformatname, @strpartchar
end
close fcur
deallocate fcur
select #formats.*, DefaultFormat
from #formats, aAccRepFormat
where #formats.formatid = aaccrepformat.formatid
order by #formats.formatname
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePostDateCheque]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePostDateCheque]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------
--Crested By : VinothMurugan V.
--Date   : 19/02/2011
--Purpose  : Posting Post date Cheque Registry
--------------------------------------
--exec spUpdatePostDateCheque 1,8,1
CREATE proc [dbo].[spUpdatePostDateCheque] @intCompanyID as int, @intTransid  as int,@intDetailid as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intCount as int,
@intRowCount as int,
@intFinancialID as int,
@dtChequeDate as datetime,
@strChequeNo as varchar(50),
@strRemarks as varchar(250),
@intDepartmentID as int,
@intChequeDtlID as int,
-- @bitJTC as bit,
@intPDChequeDebitAccid as int,
@intPDChequeCreditAccid as int,
@numAmount as numeric(18,2),
@dtupdatetime as datetime,
@intacccurrencyid as int,
@intcurrencyid as int,
@numconsrate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,2),
@CustomerID as int
set nocount on
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
SELECT @intTransid = PDTransId, @strChequeNo = PDChequeDtlPrefix, @dtChequeDate = PDChequeEntryDate,
@strremarks = Remarks, @intFinancialID = FinancialID, @dtupdatetime = updatetime,
@numconsrate = exchangerate, @strexrates = exchangerates , @intDepartmentID = PDChequeDepartmentid
FROM ahqPostDatedChequeDetails  inner join ahqPDChequeprocessing
on ahqPostDatedChequeDetails.TransID  = ahqPDChequeprocessing.PDTransId
WHERE Cancel =0 and ahqPDChequeprocessing.PDChequePosted =0 and
CompanyID = @intCompanyID and TransID = @intTransid  and PDChequeid = @intDetailid
--group by  TransID,  TransNo,ChDate,Remarks,  FinancialID,exchangerate,  exchangerates ,updatetime ,DepartmentID
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
set @intCount = 1
insert into moajournalheader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtChequeDate, @strChequeNo,  @strRemarks,
@intFinancialID, ''PDCHECK'', @intcurrencyID, @dtChequeDate, @dtupdatetime)
Declare DetailCur cursor for
SELECT d.PDChequeid,p.DepartmentID,d.PDChequeDebitAccid,
d.PDChequeCreditAccid,p.Amount,exchangerates FROM--,p.CustomerID FROM
ahqPostDatedChequeDetails p inner join ahqPDChequeprocessing d
on p.TransID  = d.PDTransId , aaccountmaster a WHERE a.companyid = p.companyid and
a.accountid = d.PDChequeDebitAccid    and a.CompanyID = @intCompanyID and transid = @intTransid
and  PDChequeid = @intDetailid
open DetailCur
fetch next FROM DetailCur into @intChequeDtlID,@intDepartmentID, @intPDChequeDebitAccid,
@intPDChequeCreditAccid,@numAmount ,@strexrates--,@CustomerID --,@numconsrate
while @@Fetch_status =0
begin
exec spConvertequiamount @intdepartmentid, ''d'', @intPDChequeDebitAccid,
''a'', @strexrates, @numAmount, @numresamount output
--debit
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID,CustomerID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 0, @intPDChequeDebitAccid,@CustomerID,
@numAmount * @numconsrate,@numAmount , @intDepartmentID,  @numresamount)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepartmentid, ''d'', @intPDChequeCreditAccid,
''a'', @strexrates, @numAmount, @numresamount output
--credit
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID,CustomerID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, 1, @intPDChequeCreditAccid,@CustomerID,
@numAmount * @numconsrate, @numAmount, @intDepartmentID,  @numresamount)
update ahqPDChequeprocessing  set PDChequePosted =1 WHERE
PDTransId = @intTransid  and   pdchequeid = @intChequeDtlID
--set @intCount = @intCount + 1
-- set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DetailCur into @intChequeDtlID,@intDepartmentID, @intPDChequeDebitAccid,
@intPDChequeCreditAccid,@numAmount,@strexrates--,@CustomerID --,@numconsrate
end
Close DetailCur
Deallocate DetailCur
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spvendoroutstanding]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendoroutstanding]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on	: 12/06/2003
--Created by	: leo
CREATE procedure [dbo].[spvendoroutstanding] @intdepartmentid as int, @strdate as varchar(8) as
begin
	declare @intalertdays as int,
		@strqry as varchar(1000)
	if @intdepartmentid > 0
		select @intalertdays = isnull(payablealertbeforedays,0)  from adepartmentmaster
		where departmentid = @intdepartmentid
	else
		select @intalertdays = isnull(payablealertbeforedays,0)  from asettings
	set @strqry =N''select b.companyid, b.departmentid, b.billsno, b.pbhbilldate, b.duedate,
	b.referenceno, b.pbhbillamount, cur.symbol from acurrencymaster cur, avendormaster v,
	vwbills b left outer join vwpayments s on
	b.companyid = s.companyid and b.departmentid = s.departmentid and b.billsid = s.billsid
	where v.vendorid = b.pbhvendorid and v.currencyid = cur.currencyid and
	datediff(dd,convert(datetime,''''''+ @strdate +''''''),b.duedate) <= '' + ltrim(rtrim(str(@intalertdays))) +
	'' and b.duedate <= dateadd(dd,'' + ltrim(rtrim(str(@intalertdays))) + '',''''''+ @strdate +'''''')
	group by b.companyid, b.departmentid, b.billsno, b.pbhbilldate, b.duedate,
	b.referenceno, b.pbhbillamount, cur.symbol having b.pbhbillamount <>
	sum(isnull(PaidAmount,0.0)) ''
	if @intdepartmentid > 0
	set @strqry = @strqry + N'' and b.departmentid = '' + ltrim(rtrim(str(@intdepartmentid)))
	set @strqry = @strqry + N'' order by b.departmentid, b.billsno asc''
	exec (@strqry)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULUtilityBilling]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULUtilityBilling]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------
--modified by 	: venki , Hariharan R
--Modified Date	: 111103, 19/11/2003
--comments    	: added utility accountid for utilities posting
--		: reinitliaized variables in loop
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spULUtilityBilling] @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 @dtBilldate as datetime
	Declare @intBillNo as varchar(50)
	Declare @intBillid as int
	Declare @strRemarks as varchar(250)
	Declare @intCustomerid as int
	Declare @intadvanceaccid as int
	Declare @intDepartmentID as int
	Declare @intComCurID as int
	Declare @intinventoryaccid as int	
	Declare @intserviceaccid as int
	Declare @intutilityaccid int
	declare @numer as numeric(28,8)
	declare @numBillamount as numeric(18,2)
declare @Depnumer as numeric(28,8)
	declare @intagreementid as int
	Declare @numTenatservamt as numeric(18,2)
	Declare @numTenatutilityamt as numeric(18,2)
	/* getting the defaults into the variables */
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID	
	set @numBillamount = 0.0
	select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid	
	set @intJournalID = @intJournalID + 1
	Declare Billcur cursor for
	select tbhBillId,tbhAgreementId,tbhCustomerId,tbhBillNo,tbhBillDate,
	tbhRemarks,tbhDepartmentID,tbhBankCashID,tbhServiceAccid,tbhAmount,tbhDepExRate,
	tbhExRate,tbhutilityAccid  from
	losTenantServiceBillHeader where tbhPosted=0 and tbhCancelled=0 and
	tbhCompanyId=@intcompanyid and tbhShopId=@intshopid 	
	open Billcur
	fetch next FROM Billcur into @intBillid,@intagreementid , @intcustomerid,@intBillNo,
	@dtBilldate, @strremarks, @intdepartmentid,@intCashAccountID, @intserviceaccid,
	@numBillamount,@Depnumer, @numer,@intutilityaccid
	while @@Fetch_status = 0
	begin		
		--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtBilldate
		between sdate and edate
		set @numTenatservamt = 0.0
		set @numTenatutilityamt = 0.0
	
		---Tenant Service Bill details
		select @numTenatservamt = sum(isnull(tbdAmount,0)) from losTenantServiceBillDetail where
		tbdShopId=@intshopid  and tbdCompanyId=@intcompanyid and tbdBillId=@intBillid
		group by tbdShopId , tbdCompanyId ,tbdBillId
		
		---Tenant Utility Bill details		
		select @numTenatutilityamt = sum(isnull(utdAmount,0)) from losTenantUtilityBillDetail
		where utdBillId=@intBillid and utdShopId=@intshopid and utdCompanyId=@intcompanyid
		group by  utdBillId ,utdShopId, utdCompanyId
		
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
		referenceno, remarks,financialID,Type, CurrencyID,chequedate) values
		(@intJournalID, @intCompanyID, @dtBilldate, @intBillNo,
		@strRemarks, @intFinancialID,''UTB'', @intcomCurID,@dtBilldate)
		set @intJournalDetailID = 1				
		
		if @numTenatservamt>0
		begin	/* crediing the service account with the full Tenant Service   */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			 @intserviceaccid,  @numTenatservamt * @numer, @numTenatservamt
			,@intDepartmentID, @numTenatservamt*@Depnumer )			
			set @intJournalDetailID = @intJournalDetailID +1
		end		
		if @numTenatutilityamt>0
		begin	/* crediing the service account with the full Utility Amount */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			 @intutilityaccid,  @numTenatutilityamt * @numer, @numTenatutilityamt
			,@intDepartmentID, @numTenatutilityamt*@Depnumer )			
			set @intJournalDetailID = @intJournalDetailID +1
		end
		if  (@intCashAccountID is not null and @intCashAccountID <>0)
		begin			
			if @numBillamount>0
			begin
				-- DEBITING cash
				insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intcashaccountid, @numBillamount * @numer, @numBillamount,
				@intDepartmentID,@numBillamount*@Depnumer)
				set @intJournalDetailID = @intJournalDetailID +1
			end			
		
			else if @numBillamount < 0
			begin
				-- Credit Cash cash
				insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@intcashaccountid, abs(@numBillamount) * @numer, abs(@numBillamount),
				@intDepartmentID,abs(@numBillamount)*@Depnumer)
				set @intJournalDetailID = @intJournalDetailID +1
			end
		end
		else
		begin
			if @numBillamount>0
			begin
				-- DEBITING customer
				insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, customerid, Amount, actualAmount,departmentID,depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intcustomerid, @numBillamount * @numer, @numBillamount,
				@intDepartmentID,@numBillamount*@Depnumer)
				set @intJournalDetailID = @intJournalDetailID +1
			end
		end		
		/* mark the record as postED */
		update losTenantServiceBillHeader set tbhPosted =1 WHERE tbhCompanyId = @intCompanyID
		and tbhShopId = @intshopid and tbhBillId = @intBillid
		set @intJournalID = @intJournalID + 1
		fetch next FROM Billcur into @intBillid,@intagreementid , @intcustomerid,@intBillNo,
		@dtBilldate, @strremarks, @intdepartmentid,@intCashAccountID, @intserviceaccid,
		@numBillamount,@Depnumer, @numer,@intutilityaccid
	end
	Close Billcur
	Deallocate Billcur
	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spulShopPurchReturn]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopPurchReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spulShopPurchReturn 1,6
--Created  : 21/06/2008
--Created by  : Shinu
--Purpose : For Posting Shop Purchase Returns
-----------------------------------------------------------------------------------------------------------------------
--Modified  On :
--Modified  By :
--Comments :
-----------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spulShopPurchReturn] @intCompanyId as int, @intShopID as int as
begin
Declare @intJournalID as int,@intJournalDetailID as int,@intswoid as int,@intFinancialID as int,
	@strswoNo as varchar(50),@dtswoDate as datetime,@strRemarks as varchar(500),@intDepartmentId as int,
	@numSwoAmt as numeric(18, 2),@intCompanyCurID as int,@intInventoryAccId as int,@intPurchRetAccid as int,
	@dtutime as datetime,@strzerorate as varchar(1),@intFailcount as int,@numDepExRate as numeric(18, 8),
	@numConExRate as numeric(18, 8),@intCurrencyId as int,@strExRates VarChar(250),@numAccExRate Numeric(18, 2),
	@numTransEr Numeric(18, 2),@numAaccAmt Numeric(18, 2)
--get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID FROM acompanymaster WHERE CompanyId = @intCompanyId
select @intPurchRetAccid = PurchaseRtnAccID from aPackageSettings where CompanyId = @intCompanyId
select @intInventoryAccId = InventoryID,@strzerorate = substring(isnull(futurevc, ''''), 1, 1)
from aPackageSettings
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader WHERE CompanyId = @intCompanyId
set @intJournalID = @intJournalID + 1
Declare swoCur cursor for
SELECT whID, whNo, whDate,  whRemarks, UpdateTime, whConExRate,whDepExRate, whDepartmentId, whExchangeRates
FROM losPurchaseReturnHeader WHERE whCancelled = 0 And whShopId = @intShopID And whPosted = 0 And whType =''P''
open swocur
	fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
	  @dtutime, @numConExRate, @numDepExRate, @intDepartmentId, @strExRates
	while @@Fetch_status = 0
	begin -- cur begin
	  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intInventoryAccId
		and CompanyId = @intCompanyId
	  exec spReturnExRate @intCurrencyId, @strExRates,@numTransEr output
	  -- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
	  select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
	  -- to check the no of records with item rate =0 or null in both the detail table
	  -- and the item master table. If so we cannot do any thing in the posting with out item rate.
	  -- so that transaction will be avoided from posting
	  -- hariharan 011211
	  set @intFailcount = 0
	  select @intFailcount = count(*) from losPurchaseReturnDetail, aItem where
		wdID = @intswoiD and wdShopId = @intShopId and wdItemId = ItemId
		and ( wdCostPrice =null or wdCostPrice =0) and (itemrate=0 or itemrate is null)
	
	  -- to allow to proceed if allow zero rate condition given - hari 020905
	  if @strzerorate = ''z''
		begin
			set @intFailcount=0
		end
	  if @intfailcount = 0 -- for item rate = 0 check
		begin  -- to update the item rate to the gadCostPrice
		  update losPurchaseReturnDetail set wdCostPrice = itemrate from  aItem where ( wdCostPrice =null or
			wdCostPrice = 0) and wdID = @intswoiD and  wdShopId = @intShopId and wdItemId = ItemId
		  insert into moaJournalHeader (JournalID, CompanyId, JournalDate,referenceno, remarks, financialID, Type,
			CurrencyID,chequedate, updatetime )values (@intJournalID, @intCompanyId, @dtswoDate, @strswono,
			@strRemarks, @intFinancialID, ''sret'', @intcompanycurID, @dtswoDate, @dtutime )
		  set @intJournalDetailID = 1
		  -- getting the total amount with qty and item cost price
		  select @numSwoAmt = isnull(sum(wdPurchaseReturnqty * wdCostPrice),0) from losPurchaseReturnDetail swod
		  where wdShopId = @intShopId and wdid = @intswoid
		  -- for converting the amount --->
		  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intPurchRetAccId
		  exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,@numSwoAmt,@numAaccAmt output
		  -- debiting the Purchase Return accid
		  insert into moaJournalDetails (JournalID,journaldetailID,CompanyId,JournalCrEDit,AccountID,Amount,
			actualAmount,DepAmount, DepartmentId)
		  values(@intJournalID, @intjournalDetailID, @intCompanyId,0,@intPurchRetAccid,@numSwoAmt * @numConExRate,
			@numAaccAmt,@numSwoAmt * @numDepExRate,  @intDepartmentId)
		  set @intJournalDetailID = @intJournalDetailID + 1
		  -- credit the inventory acc id
		  insert into moaJournalDetails (JournalID,journaldetailID,CompanyId,JournalCrEDit, accountid, Amount,
			actualamount,DepAmount, DepartmentId)
		  values (@intJournalID, @intjournalDetailID, @intCompanyId, 1,@intInventoryAccId,@numSwoAmt * @numConExRate,
			@numSwoAmt,@numSwoAmt * @numDepExRate, @intDepartmentId )
		
		  update losPurchaseReturnHeader set whPosted = 1 WHERE WhID = @intswoID and whShopId = @intShopId
		  set @intJournalId = @intJournalId + 1
		end -- for item rate = 0 check
	  fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate,@strRemarks, @dtutime, @numConExRate,
		@numDepExRate, @intDepartmentId, @strExRates
	end -- CUR END
Close swoCur
Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersJournal]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersJournal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLEDgersJournal    Script Date: 18/01/2003 9:45:44 PM ******/
-- last modified : 07/12/2002
-- modified by	 : leo
-- Comments	 : the concept of new exchange rate is included
CREATE proc [dbo].[spUpdateLEDgersJournal] @intCompanyID as int, @intJTID as int as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intRowCount as int,
	@intFinancialID as int,
	@dtJTDate as datetime,
	@strJTNo as varchar(50),
	@strRemarks as varchar(250),
	@intDepartmentID as int,
	@numAmount as numeric(18,2),
	@intJTDID as int,
	@bitJTC as bit,
	@intJTDAccountID as int,
	@numJTDAmount as numeric(18,2),
	@dtutime as datetime,
	@intacccurrencyid as int,
	@intcurrencyid as int,
	@numconsrate as numeric(18,9),
	@strexrates as varchar(250),
	@numresamount as numeric(18,2)
set nocount on
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader
	WHERE CompanyID = @intCompanyID
	SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
	SELECT @intJTID = JournalTransID, @strJTNo = JournalNo, @dtJTDate = JournalTransDate,
	@strremarks = remarks, @intFinancialID = financialID, @dtutime = updatetime,
	@numconsrate = exchangerate, @strexrates = exchangerates, @intdepartmentid = departmentid
	FROM JournalTransHeader WHERE cancellED =0 and postED =0 and
	CompanyID = @intCompanyID and journaltransid = @intJTID
	set @intJournalID = @intJournalID + 1
	set @intJournalDetailID = 1
	insert into moajournalheader (JournalID, CompanyID, JournalDate, referenceno,
	remarks, financialID,Type,CurrencyID,chequedate, updatetime)
	values (@intJournalID, @intCompanyID, @dtJTDate, @strJTNo,  @strRemarks,
	@intFinancialID, ''J'', @intcurrencyID, @dtjtdate, @dtutime)
	Declare DetailCur cursor for
	SELECT journaltransdetailID, journaltranscrEDit, d.AccountID, Amount  FROM
	journaltransdetails d, aaccountmaster a WHERE a.companyid = d.companyid and
	a.accountid = d.accountid and a.CompanyID = @intCompanyID and JournalTransID = @intJTID
		
	open DetailCur
	fetch next FROM DetailCur into @intJTDID, @bitJTC, @intJTDAccountID, @numJTDAmount
	while @@Fetch_status =0
	begin
		exec spConvertequiamount @intdepartmentid, ''d'', @intJTDAccountID,
		''a'', @strexrates, @numJTDAmount, @numresamount output
		
		insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
		( @intJournalID, @intJournalDetailID, @intCompanyID, @bitJTC, @intJTDAccountID,
		 @numJTDAmount * @numconsrate, @numresamount, @intDepartmentID, @numjtdamount)
		set @intJournalDetailID = @intJournalDetailID + 1
		fetch next FROM DetailCur into @intJTDID, @bitJTC,
		@intJTDAccountID, @numJTDAmount
	end
	Close DetailCur
	Deallocate DetailCur
	/* mark the record as postED */
	update JournalTransHeader set postED =1 WHERE CompanyID = @intCompanyID and
	JournalTransID = @intJTID
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionJournal]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersInterDivisionJournal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLEDgersJournal    Script Date: 18/01/2003 9:45:44 PM ******/
-- created by  : jyothish
-- Comments  : the concept of new exchange rate is included
CREATE proc [dbo].[spUpdateLEDgersInterDivisionJournal] @intCompanyID as int, @intJTID as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intRowCount as int,
@intFinancialID as int,
@dtJTDate as datetime,
@strJTNo as varchar(50),
@strRemarks as varchar(250),
@intDepartmentID as int,
@numAmount as numeric(18,2),
@intJTDID as int,
@bitJTC as bit,
@intJTDAccountID as int,
@numJTDAmount as numeric(18,2),
@dtutime as datetime,
@intacccurrencyid as int,
@intcurrencyid as int,
@numconsrate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,2)
set nocount on
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
SELECT @intJTID = JournalTransID, @strJTNo = JournalNo, @dtJTDate = JournalTransDate,
@strremarks = remarks, @intFinancialID = financialID, @dtutime = updatetime,
@numconsrate = exchangerate, @strexrates = exchangerates
FROM InterDivisionJournalTransHeader WHERE cancellED =0 and postED =0 and
CompanyID = @intCompanyID and journaltransid = @intJTID
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into moajournalheader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtJTDate, @strJTNo,  @strRemarks,
@intFinancialID, ''IJ'', @intcurrencyID, @dtjtdate, @dtutime)
Declare DetailCur cursor for
SELECT journaltransdetailID, journaltranscrEDit, d.AccountID, Amount  ,departmentid FROM
InterDivisionJournalTransDetails d, aaccountmaster a WHERE a.companyid = d.companyid and
a.accountid = d.accountid and a.CompanyID = @intCompanyID and JournalTransID = @intJTID
open DetailCur
fetch next FROM DetailCur into @intJTDID, @bitJTC, @intJTDAccountID, @numJTDAmount ,@intDepartmentID
while @@Fetch_status =0
begin
exec spConvertequiamount @intdepartmentid, ''d'', @intJTDAccountID,
''a'', @strexrates, @numJTDAmount, @numresamount output
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, @bitJTC, @intJTDAccountID,
@numJTDAmount * @numconsrate, @numresamount, @intDepartmentID, @numjtdamount)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DetailCur into @intJTDID, @bitJTC,
@intJTDAccountID, @numJTDAmount ,@intDepartmentID
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update InterDivisionJournalTransHeader set postED =1 WHERE CompanyID = @intCompanyID and
JournalTransID = @intJTID
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopReceipt]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPShopReceipt]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spULHPShopReceipt 1,4
--Created on   : 17/07/2008
--Created by  : Prasanth Joseph
--Comments  : For Posting HirePurchase Shop Receipt
---------------------------------------------------------------------
--modified on   : 27/11/2011
--modified by  : Nidheesh P V
--Comments  : to post tax amount seperately
--Reference : RefNo:1
---------------------------------------------------------------------
--Created on   : 26/12/2011
--Created by  : Nidheesh P V
--Comments  : to post tax amount seperately
--Reference : corrected RefNo:1
---------------------------------------------------------------------
CREATE proc [dbo].[spULHPShopReceipt]
@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,
@intCashAccId   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intSalesaccid    as int,
@intCustomerAccID   as int,
@intSuspenseAccID  as int,
@InterestAmount   as NumEric(18,2),
@numTotatRecAmount  as NumEric(18,2),
@strReceipteNo    as varchar(50),
@strRemarks    as varchar(250),
@dtReceiptDate    as datetime,
@dtutime    as datetime  ,
@taxamount as numeric(18,2), --RefNo:1
@taxaccountid as int
declare @intTaxCateId as int
declare @taxPerc as numeric(18,2)
declare @intInvId as int
declare @intCountInvoiceId as int
declare @numRecAmount as numeric(18,2)
/* getting the defaults into the variables */
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalId = isnull(max(JournalId),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
set @numTotatRecAmount  = 0.0
set @InterestAmount = 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          -------------**************
@intCashAccId =CashControlAcc, @intCustomerAccID =DebtorAcc,
@intSalesaccid =SalesAcc,@intSuspenseAccID=SuspenseAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select  @intInventoryaccid =inventoryid
from
apackagesettings
where
companyid = @intcompanyid
--To return if the corresponding accounts are not selected
if isnull(@intCashAccId,0)=0
return 0
--To return if the corresponding accounts are not selected
if isnull(@intCustomerAccID,0)=0
return 0
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT
hprhReceiptID,hprhReceiptNo,hprhReceiptDate,hprhCustomerID,
hprhRemarks,hprhFinancialID,hprhupdateTime,hprhReceiptAmount
FROM
loshpReceiptheader
WHERE
hprhCancel=0 and hprhPosted=0
and hprhShopID=@intShopId and hprhCompanyID=@intCompanyID
and hprhReceiptType=''S'' --and hprhReceiptID=23
open invcur
fetch next FROM invcur into
@intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,
@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount
while @@Fetch_status = 0
begin
--RefNo:1----
set @taxamount =0
set @intTaxCateId=0
set @taxPerc=0
set @numTotatRecAmount  = 0.0
set @InterestAmount = 0.0
SELECT hprdInvoiceID,
sum(hprdSettelmentAmount) SettledAmnt,
sum(hpdInterest)Interest,row_number() over (order by hprdInvoiceID) as rowid
into #tempReceptDetls
FROM
loshpReceiptDetail, ahpprocessingdetail
WHERE
hprdProcessingId=hpdProcessingId and hprdProcessingDetailId=hpdDetailID
and hprdReceiptID=@intReceiptId and hprdShopId=@intShopId
group by hprdInvoiceID
SELECT @intCountInvoiceId=count(distinct hprdInvoiceID)
FROM
loshpReceiptDetail
WHERE
hprdReceiptID=@intReceiptId and hprdShopId=@intShopId
while @intCountInvoiceId<>0
begin
set @intInvId=0
set @numRecAmount=0
select @intInvId=hprdInvoiceID,@numRecAmount=SettledAmnt from #tempReceptDetls where rowid=@intCountInvoiceId
select @intTaxCateId=isnull(hpqhServTaxCateId,0) from loshpinvoiceheader
where hpqhQuotationID=@intInvId and hpqhShopID=@intShopId
--select @taxaccountid=TaxAccountId from ashops s inner join ataxcategorymaster t
--on s.ServiceTaxCategoryId=t.TaxId and s.shopid=@intShopId
select @taxaccountid=TaxAccountId,@taxPerc=TaxPercentage
from ataxcategorymaster where TaxId=6--Temporary hardcoded and taken the account id of GST OUTPUT TAX - HP
if @intTaxCateId<>0
begin
select @taxamount=@taxamount+convert(numeric(18,2),@numRecAmount*(1-1/(1+(@taxPerc/100))))
end
set @numTotatRecAmount=@numTotatRecAmount+@numRecAmount
set @intCountInvoiceId=@intCountInvoiceId-1
end
insert into moaJournalHeader
(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
Type, CurrencyId, chequedate, updatetime)
values
(@intJournalId, @intCompanyID, @dtReceiptDate, @strReceipteNo,
@strRemarks, @intFinancialID,''HPSR'', @intcomCurID,@dtReceiptDate, @dtutime)
set @intJournalDetailId = 1
--RefNo:1---- commented and added new--------------
------  /* 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,
------   @intCashAccId, @numTotatRecAmount-@InterestAmount,
------   @numTotatRecAmount-@InterestAmount,@intDepartmentID,@numTotatRecAmount-@InterestAmount, 1)
----------------------------------------------------------------------------
--RefNo:1---- added--start--
/* 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, 0,
@intCashAccId,@numTotatRecAmount,@numTotatRecAmount,@intDepartmentID,@numTotatRecAmount, null)
if @taxamount<>0 --and @intTaxCateId<>0
begin
set @intJournalDetailId =@intJournalDetailId +1
/* crediing tax amount to tax account */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@taxaccountid, @taxamount, @taxamount,@intDepartmentID,@taxamount, null)
end
--RefNo:1---- added--ends--
--------------------------------------------------------------------------------
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, 1, @intCustomerAccID,
convert(numeric(18,2), @numTotatRecAmount-@taxamount), convert(numeric(18,2), @numTotatRecAmount-@taxamount),
@intDepartmentID, convert(numeric(18,2), @numTotatRecAmount-@taxamount), null)
set @intJournalId = @intJournalId + 1
/*
set @intJournalDetailId = @intJournalDetailId +1
/* Debeting the Interest Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intSuspenseAccID, @InterestAmount,
@InterestAmount,@intDepartmentID, @InterestAmount, Null)
set @intJournalDetailId = @intJournalDetailId +1
/* Crediting the  Interest Amount (Earned Finacial Income Earned */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intInterestAccId, @InterestAmount,
@InterestAmount,@intDepartmentID, @InterestAmount, Null)
*/
UPDATE
losHpReceiptHEader set
hprhPosted =1
WHERE
hprhCompanyID = @intCompanyID
and hprhShopID = @intShopId and hprhReceiptID = @intReceiptId
drop table #tempReceptDetls
fetch next FROM invcur into
@intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,
@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount
end    --end of cur
Close invcur
Deallocate invcur
end     --end of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopDownPayment]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPShopDownPayment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spULHPShopDownPAyment 1,4
--Created on   : 17/07/2008
--Created by  : Prasanth Joseph
--Comments  : For Posting HirePurchase Shop Receipt
---------------------------------------------------------------------
--modified on   : 27/11/2011
--modified by  : Nidheesh P V
--Comments  : to post tax amount seperately
--Reference : RefNo:1
---------------------------------------------------------------------
--modified on   : 26/12/2011
--modified by  : Nidheesh P V
--Comments  : to post tax amount seperately
--Reference : corrected RefNo:1
---------------------------------------------------------------------
CREATE proc [dbo].[spULHPShopDownPayment]
@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,
@intCashAccId   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intCustomerAccID   as int,
@numTotatRecAmount  as NumEric(18,2),
@strReceipteNo    as varchar(50),
@strRemarks    as varchar(250),
@dtReceiptDate    as datetime,
@dtutime    as datetime,
@taxamount as numeric(18,2), --RefNo:1
@taxaccountid as int,
@intTaxCateId as int,
@taxPerc as numeric(18,2),
@intInvId as int
/* 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          -------------**************
@intCashAccId =CashControlAcc, @intCustomerAccID =DebtorAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
--To return if the corresponding accounts are not selected
if isnull(@intCashAccId,0)=0
return 0
--To return if the corresponding accounts are not selected
if isnull(@intCustomerAccID,0)=0
return 0
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT
hprhReceiptID,hprhReceiptNo,hprhReceiptDate,hprhCustomerID,
hprhRemarks,hprhFinancialID,hprhupdateTime,hprhReceiptAmount,hprhHPQuotationID
FROM
loshpReceiptheader
WHERE
hprhCancel=0 and hprhPosted=0
and hprhShopID=@intShopId and hprhCompanyID=@intCompanyID
and hprhReceiptType=''A'' --and hprhReceiptID=5
open invcur
fetch next FROM invcur into
@intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,
@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount,@intInvId
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,''HPSDP'', @intcomCurID,@dtReceiptDate, @dtutime)
--HPSDP=Hire Purchase Shop Down Payment
set @intJournalDetailId = 1
---------RefNo:1------commented below and added new-----
--  /* 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,
--   @intCashAccId, @numTotatRecAmount,
--   @numTotatRecAmount,@intDepartmentID,@numTotatRecAmount, 1)
-----RefNo:1--added new code--start--
select @intTaxCateId=isnull(hpqhServTaxCateId,0) from loshpinvoiceheader
where hpqhQuotationID=@intInvId and hpqhShopID=@intShopId
--select @taxaccountid=TaxAccountId from ashops s inner join ataxcategorymaster t
--on s.ServiceTaxCategoryId=t.TaxId and s.shopid=@intShopId
select @taxaccountid=TaxAccountId,@taxPerc=TaxPercentage
from ataxcategorymaster where TaxId=6--Temporary hardcoded and taken the account id of GST OUTPUT TAX - HP
if @intTaxCateId<>0
begin
select @taxamount=convert(numeric(18,2),@numTotatRecAmount*(1-1/(1+(@taxPerc/100))))
end
/* 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, 0,
@intCashAccId, @numTotatRecAmount,
@numTotatRecAmount,@intDepartmentID,@numTotatRecAmount, null)
if @taxamount<>0 and @intTaxCateId<>0
begin
set @intJournalDetailId =@intJournalDetailId +1
/* crediing tax amount to tax account */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@taxaccountid, @taxamount, @taxamount,@intDepartmentID,@taxamount, null)
end
-----RefNo:1--added new code--ends--
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, 1, @intCustomerAccID,
@numTotatRecAmount-@taxamount, @numTotatRecAmount-@taxamount,
@intDepartmentID, @numTotatRecAmount-@taxamount, null)
UPDATE
losHPReceiptHeader  set hprhPosted=1
WHERE
hprhShopID=@intShopId and hprhCompanyID=@intCompanyID
and hprhReceiptType=''A'' and hprhReceiptID=@intReceiptId
set @intJournalId = @intJournalId + 1
fetch next FROM invcur into
@intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,
@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount,@intInvId
end
Close invcur
Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHPSaleInv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPSaleInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on   : 27/11/2007
--Created by  : Shinu
--Comments  : For Posting HirePurchase Invoices
--Modified by:Abhishek on 10/12/09
--Comments:Take confirmed transactions for posting
---------------------------------------------------------------------
--Modified By : Nidheesh PV
--Modified Date : 01/10/2011,30/10/2011
--Reference : RefNo:1
--RefNo:1  is commented jyothish.SR Date:5-5-2012
--Reason  Hp Customer balance is not tally in ledger
---------------------------------------------------------------------
--spULHPSaleInv 1,4
create  proc [dbo].[spULHPSaleInv]
@intCompanyID as int,
@intShopId as int
as
begin
Declare @intJournalId    as int,
@intJournalDetailId   as int,
@intFinancialID   as int,
@intInvoiceId    as int,
@intCustomerId    as int,
@intDepartmentID   as int,
@intComCurID    as int,
@intinventoryaccid   as int,
@intCostOfGoodsAccId   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intSalesaccid    as int,
@intCustomerAccID   as int,
@intSuspenseAccID  as int,
@numtotalinvValue   as NumEric(18,2),
@numTotalCostValue   as NumEric(18,2),
@InterestAmount   as NumEric(18,2),
@numSalesValue   as NumEric(18,2),
@numTotatInstAmount  as NumEric(18,2),
@strinvoiceNo    as varchar(50),
@strRemarks    as varchar(250),
@dtinvoiceDate    as datetime,
@dtutime    as datetime,
@numtaxamount as numeric(18,2), --RefNo:1-
@numSurcharge as numeric(18,2)  --RefNo:1-
/* getting the defaults into the variables */
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalId = isnull(max(JournalId),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select
@intcomcurid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select  @intcomdeptid  =companydepartment
from
apackagesettings
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select @intdepartmentid =DepartmentID From aShops where shopID=@intShopID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select
@intCostOfGoodsAccId =COGSAcc, @intCustomerAccID =DebtorAcc,
@intSalesaccid =SalesAcc,@intSuspenseAccID=SuspenseAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select  @intInventoryaccid =inventoryid
from
apackagesettings
where
companyid = @intcompanyid
--To return if the corresponding accounts are not selected
if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0
return 0
--To return if the corresponding accounts are not selected
if (isnull(@intCustomerAccID,0)=0 or isnull(@intSalesaccid,0)=0)
return 0
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT
hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhCustomerId,  hpqhremarks,
hpqhfinancialid,hpqhupdatetime,hpqhTotAdditional,hpqhInstPrice
FROM
loshpinvoiceheader
WHERE
hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and
hpqhCompanyID = @intCompanyID and hpqhShopId = @intShopId
and hpqhType=''I''
open invcur
fetch next FROM invcur into
@intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime,@InterestAmount, @numTotatInstAmount
while @@Fetch_status = 0
begin
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
SELECT
@numTotalinvValue = sum(hpqdCostPrice),
@numTotalCostValue = sum(hpqdCostPrice),
@numSalesValue=sum(hpqdSellingPrice)
FROM
loshpinvoicedetail
WHERE
hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId
group by
hpqdShopId, hpqdQuotationId
-------RefNo:1------
--if exists (select * from losHpInvoiceDetailOthers where hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId)
--begin
--select @numSalesValue=hpqdActSellingPrice
--,@InterestAmount=hpqdActInterest
--,@numSurcharge =hpqdActSurcharge
--,@numTotatInstAmount=hpqdActInstallmentPrice
--,@numtaxamount=hpqdTotalTax
--from losHpInvoiceDetailOthers
--WHERE hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId
--set @InterestAmount=@InterestAmount+@numSurcharge --Total Additional Amount->Interest A/C
--Actually Total Addition Amount is saved as Total Interest Amount and posted to Interest a/c.
--So interest amount is added upto Surcharge to find total Additional Amount
---end
-------RefNo:1------
insert into moaJournalHeader
(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
Type, CurrencyId, chequedate, updatetime)
values
(@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,
@strRemarks, @intFinancialID,''HPI'', @intcomCurID,@dtinvoicedate, @dtutime)
set @intJournalDetailId = 1
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intSalesaccid, @numSalesValue,
@numSalesValue,@intDepartmentID,@numSalesValue, 1)
set @intJournalDetailId = @intJournalDetailId +1
/* Crediting Interest Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intSuspenseAccID, @InterestAmount,
@InterestAmount,@intDepartmentID, @InterestAmount, 1)
set @intJournalDetailId = @intJournalDetailId +1
-- DEBITING customer Invoice amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerAccID,
@numTotatInstAmount, @numTotatInstAmount,
@intDepartmentID, @numTotatInstAmount, 1)
set @intJournalDetailId = @intJournalDetailId + 1
/* crediing the INVENTORY with the full cost Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intINVentoryAccID, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID,@numTotalCostValue , 4)
set @intJournalDetailId = @intJournalDetailId +1
-- DEBITING THE COST OF GOODS ACCOUNT
insert into moaJournalDetails
(JournalId, JournalDetailId,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intCostOfGoodsAccId, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID, @numTotalCostValue , 4)
/* mark the record as postED */
update loshpinvoiceheader set
hpqhpostED =1
WHERE
hpqhCompanyID = @intCompanyID
and hpqhShopId = @intShopId and hpqhQuotationId = @intInvoiceId
set @intJournalId = @intJournalId + 1
fetch next FROM invcur into
@intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime,@InterestAmount,@numTotatInstAmount
end
Close invcur
Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHPResale]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPResale]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spULHPResale 1,4
--Created on   : 17/07/2008
--Created by  : Shinu
--Comments  : For Posting HirePurchase Repossession
---------------------------------------------------------------------
Create proc [dbo].[spULHPResale]
@intCompanyID as int,
@intShopId as int
as
begin
Declare @intJournalId    as int,
@intJournalDetailId   as int,
@intFinancialID   as int,
@intReSaleId    as int,
@intCustomerId    as int,
@intDepartmentID   as int,
@intComCurID    as int,
@intinventoryaccid   as int,
@intCostOfGoodsAccId   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intCashaccid    as int,
@intCustomerAccID   as int,
@numtotalinvValue   as NumEric(18,2),
@numTotalCostValue   as NumEric(18,2),
@numSalesValue   as NumEric(18,2),
@strReSaleNo    as varchar(50),
@strRemarks    as varchar(250),
@dtReSaleDate    as datetime,
@dtutime    as datetime
/* getting the defaults into the variables */
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalId = isnull(max(JournalId),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select
@intcomcurid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select  @intcomdeptid  =companydepartment
from
apackagesettings
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select @intdepartmentid =DepartmentID From aShops where shopID=@intShopID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select
@intCostOfGoodsAccId =COGSAcc, @intCustomerAccID =DebtorAcc,
@intInventoryaccid=RepossessionInvAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
--To return if the corresponding accounts are not selected
if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0
return 0
--To return if the corresponding accounts are not selected
if (isnull(@intCustomerAccID,0)=0)
return 0
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT
hphResaleID, hphResaleNo, hphReSaleDate, hphCustomerID,  hphRemarks,
hphFinancialID,hphUpdatedTime , hphCashAccID
FROM
losHpReSaleHeader
WHERE
hphCancel =0 and hphposted =0  and
hphCompanyID = @intCompanyID and hphShopId = @intShopId
open invcur
fetch next FROM invcur into
@intReSaleId, @strReSaleno, @dtReSaledate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime ,@intCashaccid
while @@Fetch_status = 0
begin
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
SELECT
@numTotalinvValue = sum(hpdFairValue),
@numTotalCostValue = sum(hpdFairValue),
@numSalesValue=sum(hpdFairValue)
FROM
losHpReSaleDetail
WHERE
hpdShopId = @intShopId and hpdReSaleId  = @intReSaleId
group by
hpdShopId, hpdReSaleId
insert into moaJournalHeader
(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
Type, CurrencyId, chequedate, updatetime)
values
(@intJournalId, @intCompanyID, @dtReSaledate, @strReSaleNo,
@strRemarks, @intFinancialID,''HPSRES'', @intcomCurID,@dtReSaledate, @dtutime)
set @intJournalDetailId = 1
/* Creditin the INVENTORY with the full cost Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intINVentoryAccID, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID,@numTotalCostValue , 4)
set @intJournalDetailId = @intJournalDetailId +1
-- Crediting customer Invoice amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1, @intCustomerAccID,
@numSalesValue, @numSalesValue,
@intDepartmentID, @numSalesValue, 1)
set @intJournalDetailId = @intJournalDetailId + 1
-- Debiting THE COST OF GOODS ACCOUNT
insert into moaJournalDetails
(JournalId, JournalDetailId,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intCostOfGoodsAccId, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID, @numTotalCostValue , 4)
set @intJournalDetailId = @intJournalDetailId + 1
-- Debting Cash Account Invoice amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intCashaccid, @numSalesValue,
@numSalesValue,@intDepartmentID, @numSalesValue, 1)
/* mark the record as postED */
update losHpReSaleHeader set
hphpostED =1
WHERE
hphCompanyID = @intCompanyID
and hphShopId = @intShopId and hphReSaleId = @intReSaleId
set @intJournalId = @intJournalId + 1
fetch next FROM invcur into
@intReSaleId, @strReSaleno, @dtReSaledate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime ,@intCashaccid
end
Close invcur
Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHPRepossession]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPRepossession]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spULHPRepossession 1,4
--Created on   : 17/07/2008
--Created by  : Shinu
--Comments  : For Posting HirePurchase Repossession
---------------------------------------------------------------------
Create proc [dbo].[spULHPRepossession]
@intCompanyID as int,
@intShopId as int
as
begin
Declare @intJournalId    as int,
@intJournalDetailId   as int,
@intFinancialID   as int,
@intRepossessionId    as int,
@intCustomerId    as int,
@intDepartmentID   as int,
@intComCurID    as int,
@intinventoryaccid   as int,
@intCostOfGoodsAccId   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intSalesRetaccid    as int,
@intCustomerAccID   as int,
@numtotalinvValue   as NumEric(18,2),
@numTotalCostValue   as NumEric(18,2),
@numSalesRetValue   as NumEric(18,2),
@strRepossessionNo    as varchar(50),
@strRemarks    as varchar(250),
@dtRepossessionDate    as datetime,
@dtutime    as datetime
/* getting the defaults into the variables */
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalId = isnull(max(JournalId),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select
@intcomcurid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
select  @intcomdeptid  =companydepartment
from
apackagesettings
where
companyid = @intcompanyid
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select @intdepartmentid =DepartmentID From aShops where shopID=@intShopID
--->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Select
@intCostOfGoodsAccId =COGSAcc, @intCustomerAccID =DebtorAcc,
@intSalesRetaccid =SalesReturnAcc,@intInventoryaccid=RepossessionInvAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
--To return if the corresponding accounts are not selected
if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0
return 0
--To return if the corresponding accounts are not selected
if (isnull(@intCustomerAccID,0)=0 or isnull(@intSalesRetaccid,0)=0)
return 0
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT
hprhRepossessionID, hprhRepossessionNo, hprhRepossessionDate, hprhCustomerID,  hprhRemarks,
hprhFinancialID,hprhUpdatedTime
FROM
losHpRepossessionHeader
WHERE
hprhCancel =0 and hprhposted =0  and
hprhCompanyID = @intCompanyID and hprhShopId = @intShopId
open invcur
fetch next FROM invcur into
@intRepossessionId, @strRepossessionno, @dtRepossessiondate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime
while @@Fetch_status = 0
begin
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
SELECT
@numTotalinvValue = sum(hprdFairValue),
@numTotalCostValue = sum(hprdFairValue),
@numSalesRetValue=sum(hprdFairValue)
FROM
losHpRepossessionDetail
WHERE
hprdShopId = @intShopId and hprdRepossessionId  = @intRepossessionId
group by
hprdShopId, hprdRepossessionId
insert into moaJournalHeader
(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
Type, CurrencyId, chequedate, updatetime)
values
(@intJournalId, @intCompanyID, @dtRepossessiondate, @strRepossessionNo,
@strRemarks, @intFinancialID,''HPSRPOS'', @intcomCurID,@dtRepossessiondate, @dtutime)
set @intJournalDetailId = 1
-- Debting Return Account Invoice amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intSalesretaccid, @numSalesRetValue,
@numSalesRetValue,@intDepartmentID, @numSalesRetValue, 1)
set @intJournalDetailId = @intJournalDetailId + 1
/* Debting the INVENTORY with the full cost Amount */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@intINVentoryAccID, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID,@numTotalCostValue , 4)
set @intJournalDetailId = @intJournalDetailId +1
-- Crediting customer Invoice amount
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1, @intCustomerAccID,
@numSalesRetValue, @numSalesRetValue,
@intDepartmentID, @numSalesretValue, 1)
set @intJournalDetailId = @intJournalDetailId + 1
-- Crediting THE COST OF GOODS ACCOUNT
insert into moaJournalDetails
(JournalId, JournalDetailId,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
@intCostOfGoodsAccId, @numTotalCostValue, @numTotalCostValue,
@intDepartmentID, @numTotalCostValue , 4)
/* mark the record as postED */
update losHpRepossessionHeader set
hprhpostED =1
WHERE
hprhCompanyID = @intCompanyID
and hprhShopId = @intShopId and hprhRepossessionId = @intRepossessionId
set @intJournalId = @intJournalId + 1
fetch next FROM invcur into
@intRepossessionId, @strRepossessionno, @dtRepossessiondate, @intCustomerId, @strremarks,
@intfinancialid,  @dtutime
end
Close invcur
Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULSerBooking]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSerBooking]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified by		: Lawrence.J'' Advance Recieved date is given instead of bookingdate
-- Modified on		: 12/06/2003
-- Comments		: Replaced with script from v2
-----------------------------------------------------------------------------------------
--------------------------------------------------------------------
--Modified on                   : 21/08/2003, 15/10/2003
--Modified by                   : Reji Abraham, Hariharan R
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
--			       : given spconvertequiamount for converting related amount to advance account
--				: serbookhstatus <>''n''
----------------------------------------------------------------
CREATE PROC [dbo].[spULSerBooking] @intCompanyID as int, @intshopid as int AS
Begin
	Declare @intadvAccountID as int
	Declare @intCashAccountID as int
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dtBookDate as datetime
	Declare @strBookingNo as varchar(50)
	Declare @intbookingid as int
	Declare @strRemarks as varchar(250)
	Declare @intCustomerid as int
	Declare @intDepartmentID as int
	Declare @numtotalinvValue as numeric(18,2)
	Declare @intComCurID as int
	declare @numer as numeric(28,8)
	declare @dtutime as datetime
	declare @numadvance as numeric(18,2)
	declare @Date1 as datetime
	declare @dtAdvRecDate as datetime
declare @numDep  as numeric(28,8)
	declare @strExRates as varchar(50)
	declare @numRespAmount as numeric(18,2)
	set @strExRates =''''
	/* 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
	
	select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid
	set @intJournalID = @intJournalID + 1
	Declare invcur cursor for
	SELECT serbookhid, serbookhinspectionno serbookhno, serbookhInspectionDate serBookHTime, sercallbkhcustomerid serbookhcustomerid,  serbookhremarks,
	serbookhdepartmentid, serbookadvanceamount, serbookhcmpexrate , serbookhupdatetime,
	serbookadvanceacc, serbookhcashacc,serbookadvancedate,serbookhdepexrate, serbookhExchangeRates
	FROM losservicebookingheader bk, loscallbookingheader los
	WHERE los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid and sercallbkhcancelled = 0 and serbookhposted = 0 and
	serbookhCompanyID = @intCompanyID and serbookhshopid = @intshopid and
	serbookadvanceamount > 0 and serbookhinpcancelled = 0 and serbookhstatus <>''n''
	open invcur
	fetch next FROM invcur into @intbookingid, @strBookingNo, @dtBookDate, @intcustomerid,
	@strremarks, @intdepartmentid, @numadvance, @numer, @dtutime, @intadvAccountID,
	@intCashAccountID, @dtAdvRecDate, @numDep, @strExRates
	while @@Fetch_status = 0
	begin
		--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtAdvRecDate
		between sdate and edate
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
		referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime)
		values
		(@intJournalId, @intCompanyId, @dtAdvRecDate, @strBookingNo,
		@strRemarks, @intFinancialID, ''SB'', @intcomCurID, @dtAdvRecDate, @dtutime)
		set @intJournalDetailID = 1		
		
		set @numRespAmount = 0.00
		exec spConvertEquiamount @intCashAccountID, ''a'', @intadvAccountID, ''a'',
		@strExRates, @numadvance, @numRespAmount output, ''a''
		
		/* crediing the advance account with the full invoice Amount */
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intadvAccountID, @numadvance * @numer, @numRespAmount
		,@intDepartmentID,@numadvance*@numDep)
		set @intJournalDetailID = @intJournalDetailID +1
		-- DEBITING CASH Account
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intCashAccountID, @numadvance * @numer, @numadvance,
		@intDepartmentID,@numadvance*@numDep)			
		/* mark the record as posted */
		update losservicebookingheader set serbookhposted =1 WHERE
		serbookhCompanyID = @intCompanyID and serbookhshopid = @intshopid and
		serbookhid = @intbookingid
		set @intJournalID = @intJournalID + 1
		fetch next FROM invcur into @intbookingid, @strBookingNo, @dtBookDate,
		@intcustomerid,	@strremarks, @intdepartmentid, @numadvance, @numer,
		@dtutime, @intadvAccountID, @intCashAccountID,@dtAdvRecDate,@numDep,
		@strExRates
	end
	Close invcur
	Deallocate invcur
	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBouncedChequeDetailsLC]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBouncedChequeDetailsLC]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------
--CREATED BY: NIDHEESH PV
--CREATED ON: 19/10/2010
--COMMENTS: TO GET ALL DETAILS OF LC REGISTER
--spBouncedChequeDetailsLC 1,0,''20070101'',''20101001'',''S'',2
CREATE proc [dbo].[spBouncedChequeDetailsLC]
@intCompanyID as int,
@intDepartmentID as int,
@strFromDate as varchar(12),
@strToDate as varchar(12),
@strType as char(1)=''D'',
--If passing ''D'' date Range will be considered (both From Date & To Date)
--If passing ''N'' date Range will not be considered (As on date is taken, only To Date is considered)
--If passing ''S'' date Range will not be considered (both From Date & To Date will not be considered/for a single transaction)
@intBcID as int
as
set nocount on
begin
select BcID,CustomerName,BcBankAccName,BcReturnedDate,BcChequeNo,BcAmount,
DepartmentName,Symbol
from aBouncedChequeDetails inner join acustomermaster cust on customerid=BcCustomerID
inner join adepartmentmaster on departmentid=BcDepartmentID and cust.CompanyID=BcCompanyID
inner join acurrencymaster curr on curr.CurrencyID=cust.CurrencyID and curr.CompanyID=BcCompanyID
where BcCancel=0 and BcCompanyID=@intCompanyID and (BcDepartmentID=@intDepartmentID or @intDepartmentID=0) and (BcID=@intBcID or @intBcID=0)
and ((BcDate>=@strFromDate and BcDate<=@strToDate and @strType=''D'') or (BcDate<=@strToDate and @strType=''N'') or (@strType=''S''))
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetExceeds]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetExceeds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 14/09/2002 12:48:13 AM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 20/11/2001 9:59:13 AM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 17/11/2001 9:22:20 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 16/06/2001 15:36:36 ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 09/03/2001 02:32:29 ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 12/05/00 1:40:15 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 10/17/00 2:19:51 PM ******/
/****** Object:  Stored Procedure dbo.spBudgetExceeds    Script Date: 10/7/00 11:07:58 AM ******/
CREATE proc [dbo].[spBudgetExceeds] (@intCompanyID as int, @intAccountID as int,
				@numAmt as numeric(18,2)) as
Declare @AccType as char(1)
Declare @numBudgetAmt as numeric(18,2)
Declare @numDebitBal as numeric(18,2)
Declare @numCreditBal as numeric(18,2)
Declare @CheckSettings as int
begin
	-- To Check whether the Type is Expense or Income
	SELECT @AccType = AccountType
	FROM aGroupMaster
	WHERE GroupID = (SELECT GroupID
			 FROM aAccountMaster
			 WHERE AccountID = @intAccountID and CompanyID = @intCompanyID)
		and CompanyID = @intCompanyID
	-- To fetch the Budget Amount from Group Master for particular Account
	SELECT @numBudgetAmt = isnull(BudgetAmount,0)
	FROM aAccountMaster
	WHERE AccountID = @intAccountID and CompanyID = @intCompanyID
	if @numBudgetAmt <> 0 and @AccType = ''E''		--IF - E
	begin
		SELECT @numDebitBal = sum(isnull(Amount,0))
		FROM MOaJournalDetails
		WHERE JournalCredit = 0 AND CompanyID = @intCompanyID AND
			AccountID = @intAccountID
		SELECT @numCreditBal = sum(isnull(Amount,0))
		FROM MOaJournalDetails
		WHERE JournalCredit = 1 AND CompanyID = @intCompanyID AND
			AccountID = @intAccountID
		if (@numDebitBal + @numAmt - @numCreditBal) > @numBudgetAmt
			return 1
		else
			return 0
	end			-- IF - E
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPDChequeRegisterForPOS]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPDChequeRegisterForPOS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Coded by : Bijesh.B
-- Date     : 13-05-2011
-- Desc     : PDCheque Register (Sonee)
--exec spPDChequeRegisterForPOS 39,1
create PROC [dbo].[spPDChequeRegisterForPOS]
@intTransId  as int,
@intCompanyID  as int
AS
SELECT ChqReg.TransNo,POS.poshBillNo,ChqReg.ChDate,Dept.DepartmentName,
CASE WHEN ChqReg.CustomerID=0 THEN ChqReg.CustomerName ELSE c.CustomerName END ''CustomerName'' ,
bank.BankName,ChqReg.ChequeNo,ChqReg.ChequeDate,ChqReg.Amount,
sh.ShopName,ChqReg.Status,ChqReg.Remarks,
CASE WHEN ChqReg.Cancel=1 then ''Cancelled'' else '''' end ''Cancelled'',
Dept.DepartmentID,ChqReg.ShopID
FROM ahqPostDatedChequeDetails ChqReg
LEFT JOIN aDepartmentMaster Dept ON Dept.DepartmentID = ChqReg.DepartmentID
LEFT JOIN aBankMaster Bank ON Bank.BankID = ChqReg.Bankid
LEFT JOIN aShops Sh ON  sh.ShopID = ChqReg.ShopID
LEFT JOIN LOsPosHeader Pos ON pos.poshBillID = ChqReg.PoshBillID
LEFT JOIN aCustomerMaster C ON c.CustomerID = ChqReg.CustomerID
WHERE ChqReg.TransID=@intTransId and ChqReg.CompanyID=@intCompanyID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetUtilization]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetUtilization]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--modified by    : Hariharan
--Modifed Date	 : 27/09/2003
CREATE procedure [dbo].[spBudgetUtilization]
	@intBudgetAllocationID as int,
	@intcompanyid as int,
	@ToDatePassed as varchar(50) ,@strexrate as varchar (250)
	
	As
	
	set nocount on
	-- Declarations
	declare @maxdetailid as int,
	@BudgetHeadID as int,
	 	@AccountID as int,
	 	@DepartmentID as int,
		@NewDebAmount as numeric(18,2),
		@NewCredAmount as numeric(18,2),
@Amt as numeric(18,2),
		@intCount as int,
		@dtfromdate as datetime,
		@dttodate as datetime,
		@DetailCount as int,
		@MaxDetailIDforSecond as int,
@budgetcurrencyid as int,
		@numaccamt as numeric (18,2)
	-- Create Temporary Table
	create table #temp1 (
	DetailID int,
		BudgetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	create table #temp2 (	DetailID int,
				AccountID int,
		             	DepartmentID int)
	
	create table #temp3 (
	DetailID int,
		BudgetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	-- Select The Allocated Details from the Budget Allocation Details
	insert  into #temp1
	select badDetailID,badBudgetHeadID,badFromDate,badToDate ,0.0
	from BudgetAllocationDetail D , BudgetAllocationHeader H
	where badCompanyId=@intcompanyid and
	D.badBudgetAllocID=H.bahBudgetAllocID And
	H.bahCompanyID=D.badCompanyID and
	H.bahCancelled=0 And
	badBudgetAllocID= @intBudgetAllocationID order by badDetailID
set @amt=0
	select @intcount=count(*) from #temp1
	while @intcount <>0
		begin
	-- Select the Max DetailID from the Temp1
		select @maxdetailid= max(DetailID) from #temp1
		-- Select BudgetHeadID,fromDate,Todate from the Temp1 Table
	Select @BudgetHeadID=BudgetHeadID, @dtfromdate = fromdate,
		@dttodate = todate from #temp1 where DetailID= @maxDetailID     		
		select @budgetcurrencyid=budcurid from budgetmaster where budgetid=@BudgetHeadID
		-- Change the ToDate with Respect to Actual As On Date
		--if @dttodate > @ToDatePassed
			-- @dttodate = @ToDatePassed
		-- Delete Data from the Temp2 table if some data exists
		delete from #temp2
		--To Insert into The Temp2 from the BudgetAccounts Link for the BudgetHead
		Insert #temp2
		Select bacdetailid, bacAccountID,bacDepartmentID from BudgetAccountsLink where
		bacCompanyId=@intcompanyid and bacBudgetID = @BudgetHeadID
		select @DetailCount=count(*) from #temp2   -- Select the Check Count
	 	while @DetailCount <>0
		 begin
		  -- Select the Max DetailID from the Second Table to Check for the Amount
		  select @MaxDetailIDforSecond= max(DetailID) from #temp2
		  select @AccountID = AccountId from #temp2 where detailID=@MaxDetailIDforSecond
		  select @DepartmentID=isnull(DepartmentID,0) from #temp2 where detailID=@MaxDetailIDforSecond
			set @NewDebAmount = 0.0
			set @NewCredAmount = 0.0
		--PRINT @AccountID
		--PRINT CONVERT(vARCHAR(12),@dtfromdate) +  " - " + CONVERT(VARCHAR(12), @dtTOdate)
		  -- Select Amount from the Journal Header and Journal Details
		  if @DepartmentID > 0
			Begin
			select @NewDebAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moaJournaldetails.DepartmentID=@DepartmentID And
			moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
			and JournalCredit = 0
			select @NewCredAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moaJournaldetails.DepartmentID=@DepartmentID And
			moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
			and JournalCredit = 1
			End
		  else
			Begin
			Select @NewDebAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
			and JournalCredit = 0
			Select @NewCredAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
			where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
			moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
			And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
			>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
			and JournalCredit = 1
			End
		select @NewDebAmount = @NewDebAmount - @NewCredAmount
		  -- Delete MaxID from the TempTable2 to take the Next Max DetailID
		  delete from #temp2 where DetailID= @MaxDetailIDforSecond
exec spConvertequiamounttemp @AccountID, ''a'', @budgetcurrencyid, ''m'', @strexrate,
			@NewDebAmount,@numaccamt  output			
		  -- Set the Count from the Temp2
		  select  @DetailCount=count(*) from #temp2
set @amt = @amt + @numaccamt
		end
--Select * from #temp1 where detailid = @maxdetailid
-- PRINT @amt
		  -- To Insert into Temp3 Table with the Selected Values	
		  Insert into #temp3
		  Select * from #temp1 where detailid = @maxdetailid
		  -- to Update the Temp Table with the New Amount	
	               update #TEMP3 set Amount = isnull(amount,0.0) + @amt where detailid = @maxdetailid
set @amt=0
		-- MaxDetailID row from temp1 to get the next max DetailID row
	  	delete from #temp1 where detailID = @maxdetailid
		-- To get the Row Count from the Temp1 Table
		select @intcount=count(*) from #temp1
	       end
	
	drop table #temp2
	--To Select the resultant rows from the temp3 table
	select  distinct(BudgetHeadID),DetailID,FromDate,ToDate,Amount from #temp3
	set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopExpiryStock]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopExpiryStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on 	: 22/02/2003, 30/09/2003
-- Created by 	: R Harikrishnan, Hariharan
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on  : 17/12/2003
-- Modified by  : Kishore
-- Comments     : Added fields item code, shop name, expiry date so that this sp
--                can be used in rptShopExpiry report
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE procEDURE [dbo].[spShopExpiryStock]
	@intShopId 		as int = 0,
	@dtExpiryDate 		as varchar(10) = '''',
	@intItemID 		as int = 0,
	@OpeningStockYesNO 	as bit,
	@NegativeStockYesNo 	as bit,
@dtExpiryDateTo         as varchar(10) = ''''
AS
Begin
declare @strSql as nvarchar(4000)
declare @strShopName as varchar(250)
SELECT @strShopName = ShopName
FROM aShops
WHERE ShopId = @intShopId
set @strSql=N''select
		eadShopID, eaditemid, sum(quantity) quantity,
		itemDescription, CategoryNameDescription, ItemCode, ExpiryDate,''
+ Char(39) + @strShopName + Char(39) + '' ShopName
	from
		(select
			ea.eadShopID, ea.eaditemid, sum(ea.eaditemqty) quantity,
			case 	when coalesce(cl.ColorName,"") + coalesce(sz.SizeName,"")="" then it.ItemDescription
				when coalesce(cl.ColorName,"") ="" then it.ItemDescription + " - " + cl.ColorName
				when coalesce(sz.SizeName,"") ="" then it.ItemDescription + " - " + sz.SizeName
				else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
			end 	ItemDescription,itc.CategoryNameDescription,
			sz.SizeName, cl.ColorName, ItemCode, eadExpiryDate ExpiryDate
		from
			losExpiryarrivaldetails ea,aItem it,aColor cl,aSize sz,aItemCategory itc
		where
			ea.eaditemid = it.ItemID and it.ItemCategoryID = itc.ItemCategoryID and
			it.ColorId *= cl.ColorID and it.SizeID *= sz.SizeID and
			ea.eadcancel = 0 ''
		if @intShopId<>0
			set @strSql = @strSql+ N'' and ea.eadShopID='' + convert(varchar(10),@intShopId)
		if @OpeningStockYesNO=1
			set @strSql = @strSql+ N'' and ea.eadInterfaceID=555''
		if @dtExpiryDate <> ''''
			set @strSql = @strSql+ N'' and ea.eadExpiryDate >= '' + Char(39) + @dtExpiryDate + Char(39)
if @dtExpiryDateTo <> ''''
set @strSql = @strSql+ N'' and ea.eadExpiryDate <= '' + Char(39) + @dtExpirydateTo + Char(39)
		if @intItemID<>0
			set @strSql = @strSql+ N'' and ea.eaditemid='' + convert(varchar(10),@intItemID)
	set @strSql = @strSql+ N'' group by
		ea.eadShopID, ea.eaditemid, it.ItemDescription,
		itc.CategoryNameDescription, sz.SizeName, cl.ColorName, ItemCode, eadExpiryDate
union all ''
	set @strSql = @strSql+ N''select
		ei.eidShopID, ei.eiditemid, - sum(ei.eiditemqty) quantity,
		case 	when coalesce(cl.ColorName,"") + coalesce(sz.SizeName,"")="" then it.ItemDescription
			when coalesce(cl.ColorName,"") ="" then it.ItemDescription + " - " + cl.ColorName
			when coalesce(sz.SizeName,"") ="" then it.ItemDescription + " - " + sz.SizeName
			else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
		end 	ItemDescription, itc.CategoryNameDescription,
		sz.SizeName, cl.ColorName, ItemCode, eidExpiryDate
		from
			losExpiryIssuedetails ei,aItem it,aColor cl,aSize sz,aItemCategory itc
		where
			ei.eiditemid = it.ItemID and it.ItemCategoryID = itc.ItemCategoryID and
			it.ColorId *= cl.ColorID and it.SizeID *= sz.SizeID and
			ei.eidcancel = 0 ''
	if @intShopId <> 0
		set @strSql = @strSql+ N'' and ei.eidShopID='' + convert(varchar(10),@intShopId)
	if @OpeningStockYesNO = 1
		set @strSql = @strSql+ N'' and ei.eidinterfaceid=555''
	if @dtExpiryDate <> ''''
		set @strSql = @strSql+ N'' and ei.eidExpiryDate >= '' + Char(39) + @dtExpirydate + Char(39)
if @dtExpiryDateTo <> ''''
set @strSql = @strSql+ N'' and ei.eidExpiryDate <= '' + Char(39) + @dtExpirydateTo + Char(39)
	if @intItemID <> 0
		set @strSql = @strSql+ N'' and ei.eiditemid='' + convert(varchar(10),@intItemID)
set @strSql = @strSql + N'' group by
	ei.eidShopID, ei.eiditemid, it.ItemDescription,
	itc.CategoryNameDescription, sz.SizeName, cl.ColorName, ItemCode, eidExpiryDate) s
	group by eadShopID, eaditemid,	itemDescription,
	CategoryNameDescription, SizeName, ColorName, ItemCode, ExpiryDate ''
if @NegativeStockYesNo = 1
Begin
	        set @strSql = @strSql+ N'' having sum(quantity) < 0''
End
Else
Begin
set @strSql = @strSql+ N'' having sum(quantity) <> 0''
End
print @strSql
exec sp_executesql @strSql
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecasting]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReorderLevelForecasting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by: Regin
--Created on: 09-10-2008
--Desc: To get the items going to reach reorder level on given date
--------------------------------------------------------------------------------
--Steps:	
--1.	Find the average sales
--2.	Find the current stock of each item
--3.	Find the difference between package date and the given future date.
--4.	Find the future stock level using below formula.
--	Future Stock = Current Stock - Avg. Sales per day * No.of days between package date and given future date.
--5.	If the future stock is less than reorder level then display that item.
--------------------------------------------------------------------------------
--spReorderLevelForecasting ''20080507''
CREATE procedure [dbo].[spReorderLevelForecasting]
@asOndate char(8)
as
declare @days as int	--Stores no. of days in between package date and given asOnDate
declare @strSql as nvarchar(4000)
begin
select @days=datediff("d",PackageDate,convert(datetime,@asOndate)) from apackagesettings
--print @days
set @strSql = N''select d.itemid, itemcode, itemdescription, d.itemreorderlevel, d.reorderquantity, d.shopid,
ic.categorynamedescription, ic.itemcategoryid, isnull(c.colorname,'''''''') colorname, a.brand,
isnull(z.sizename,'''''''') sizename,  isnull(Stock,0) stock, isnull(v.avgSalesQty,0) avgSalesQty,
isnull(avgSalesQty,0)* '' + convert(varchar, @days) + '' expectedSalesQty,
isnull(stock,0)-isnull(avgSalesQty,0)* '' + convert(varchar, @days) + '' expectedStock from
aitem  a left outer join acolor c on
a.colorid=c.colorid left outer join asize z on a.sizeid=z.sizeid,
aShopItemDetail d left outer join vwinquiryshopstock ss on d.shopid = ss.shopid
and d.itemid = ss.itemid left outer join vwAverageSalesQtyItemWise v on  d.shopid=v.shopID and d.itemID=v.itemID,
aitemcategory ic where a.itemid=d.itemid and
a.itemcategoryid= ic.itemcategoryid
and itemreorderlevel>isnull(stock,0)-isnull(avgSalesQty,0)* '' + convert(varchar, @days)
--print @strSql
exec sp_Executesql @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShipmentClearence]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShipmentClearence]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------
--Created on	: 26/06/2003
--Created By 	: R Harikrishnan
--Comments	: For Shipment Clearence Cheque Details
-------------------------------------------------------------------------
CREATE Proc [dbo].[spShipmentClearence]
	@intComapanyID		int,
	@intDepartmentID	int,
	@strFromDate 		varchar(8),
	@strToDate 		varchar(8)
as
begin
	set nocount on
	Declare @strCurrSymbol as varchar(25)
	select
		@strCurrSymbol = cm.Symbol
	from
		aDepartmentMaster dm, aCurrencyMaster cm
	where
		dm.DepCurrencyID = cm.CurrencyID and dm.CompanyID = cm.CompanyID and
		dm.CompanyID = @intComapanyID and dm.DepartmentID = @intDepartmentID
	
	select
		ch.ClearenceID,ch.ClearenceNo,ch.ClearenceDate,ch.ClearedBy,
		ch.ActualClearenceDate,	cd.ChequeNo,cd.ChequeAmt, @strCurrSymbol Symbol
	from
		ShipmentClearenceHeader ch,ShipmentClearenceChequeDetails cd,
		aShops sh
	where
		ch.ShopID=cd.ShopID and ch.ClearenceID=cd.ClearenceID and
		ch.ShopID = sh.ShopID and ch.ClearenceDate between @strFromDate and
		@strToDate and sh.DepartmentID= @intDepartmentID and ch.Cancelled=0
	order by ch.ShopID, ch.ClearenceID
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationStock]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopLocationStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- Modified on  : 22/02/2003, 30/09/2003, 17/12/2003
-- Created by  : R Harikrishnan, Hariharan R
-- Comments : given - to take issues as -ve
--              : Modified so that now this sp can be used rptShopLocationStock report
--------------------------------------------------------------------------------------
--Modified By :Nidheesh P V
--Modified on :20/12/2010
--Comments : Added UnitCode (for KOODOO)
------------------------------------------------------------------------------------
--spShopLocationStock 5,0,0,''29,31,23'',''Apex'',0,1
--Modifed by dheena add partcode
CREATE  PROCEDURE [dbo].[spShopLocationStock]
@intShopId   as int = 0,
@intLocationID   as int = 0,
@intItemID   as int = 0,
@strItemCategoryIDs as varchar(600) = '''',
@strBrandName   as Varchar(100) = '''',
@OpeningStockYesNO  as bit,
@NegativeStockYesNo  as bit AS
Begin
declare @strSql as nvarchar(4000)
Declare @strShopName as Varchar(250)
SELECT @strShopName = ShopName
FROM aShops
WHERE ShopId = @intShopId
if @strshopname=''''
begin
set @strshopname = '' ''
end
set @strSql=N''select
ladShopId, ladLocationId, ladItemId, sum(quantity) Quantity,
Avg(ItemRate) CostPrice, ItemDescription, lLocationName,
CategoryNameDescription, ItemCode, ''
+ Char(39) + @strShopName + Char(39) + '' ShopName, lGroupId, lgGroupName,part_code,UnitCode
from
(select
la.ladShopID, la.ladlocationid, la.laditemid, sum(la.laditemqty) quantity,
case    when coalesce(cl.ColorName, "") + coalesce(sz.SizeName,"")="" then it.ItemDescription
when coalesce(cl.ColorName, "") ="" then it.ItemDescription + " - " + cl.ColorName
when coalesce(sz.SizeName, "") ="" then it.ItemDescription + " - " + sz.SizeName
else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
end ItemDescription, it.ItemRate, lc.lLocationName,
itc.CategoryNameDescription, ItemCode, lc.lGroupId,part_code,au.UnitCode
from
loslocationarrivaldetails la, aItem it, losLocation lc, aColor cl, aSize sz, aItemCategory itc,aunit au
where
la.ladShopId = lc.lShopId
and la.ladlocationid = lc.lLocationId
and la.laditemid = it.ItemId
and it.ItemCategoryID = itc.ItemCategoryID
and it.ColorId *= cl.ColorID
and it.SizeID *= sz.SizeID
and la.ladcancel = 0
						and it.UnitsID=au.UnitID''
if @intShopId <> 0
set @strSql = @strSql+ N'' and la.ladShopID='' + convert(varchar(10),@intShopId)
if @OpeningStockYesNO = 1
set @strSql = @strSql + N'' and la.ladinterfaceid=555''
if @intLocationID<>0
set @strSql = @strSql + N'' and la.ladlocationid='' + convert(varchar(10),@intLocationID)
if @intItemID<>0
set @strSql = @strSql + N'' and la.laditemid='' + convert(varchar(10),@intItemID)
if @strBrandName<>''''
set @strSql = @strSql + N'' and it.Brand='' + char(39) + @strBrandName + char(39)
if @strItemCategoryIDs<>''''
set @strSql = @strSql + N'' and it.ItemCategoryID in('' + @strItemCategoryIDs +'')''
set @strSql = @strSql+ N'' group by
la.ladShopID, la.ladlocationid, la.laditemid, it.ItemDescription,it.ItemRate,
lc.lLocationName, itc.CategoryNameDescription, sz.SizeName, cl.ColorName, ItemCode, lGroupId,part_code,au.UnitCode
union all ''
set @strSql = @strSql+ N''select
li.lidShopID, li.lidlocationid, li.liditemid, -sum(li.liditemqty) quantity,
case  when coalesce(cl.ColorName,"") + coalesce(sz.SizeName,"")="" then it.ItemDescription
when coalesce(cl.ColorName,"") ="" then it.ItemDescription + " - " + cl.ColorName
when coalesce(sz.SizeName,"") ="" then it.ItemDescription + " - " + sz.SizeName
else it.ItemDescription + " - " + cl.ColorName + " - " + sz.SizeName
end  ItemDescription,it.ItemRate,lc.lLocationName, itc.CategoryNameDescription, ItemCode, lc.lGroupId,part_code ,au.UnitCode
from
loslocationIssuedetails li,aItem it,losLocation lc,aColor cl,aSize sz,aItemCategory itc,aunit au
where
li.lidShopID = lc.lShopID and li.lidlocationid = lc.lLocationID and
li.liditemid = it.ItemID and it.ItemCategoryID = itc.ItemCategoryID and
it.ColorId *= cl.ColorID and it.SizeID *= sz.SizeID and
li.lidcancel = 0 and it.UnitsID=au.UnitID''
if @intShopId <> 0
set @strSql = @strSql+ N'' and li.lidShopID='' + convert(varchar(10),@intShopId)
if @OpeningStockYesNO=1
set @strSql = @strSql+ N'' and li.lidinterfaceid = 555''
if @intLocationID<>0
set @strSql = @strSql+ N'' and li.lidlocationid = '' + convert(varchar(10),@intLocationID)
if @intItemID<>0
set @strSql = @strSql+ N'' and li.liditemid = '' + convert(varchar(10),@intItemID)
if @strBrandName<>''''
set @strSql = @strSql+ N'' and it.Brand = '' + char(39) + @strBrandName + char(39)
if @strItemCategoryIDs<>''''
set @strSql = @strSql+ N'' and it.ItemCategoryID in('' + @strItemCategoryIDs +'')''
set @strSql = @strSql+ N'' group by
li.lidShopID, li.lidlocationid, li.liditemid, it.ItemDescription,it.ItemRate,
lc.lLocationName, itc.CategoryNameDescription,sz.SizeName, cl.ColorName, ItemCode, lGroupId,part_code,au.UnitCode) s, loslocationgroup lg
Where s.lGroupId = lgGroupId
And lg.lgShopId = '' + convert(varchar(10),@intShopId) +
'' group by lLocationName, itemDescription,CategoryNameDescription,ladShopID,
ladlocationid, laditemid, ItemCode, lGroupId, lgGroupName,part_code,UnitCode''
if @NegativeStockYesNo = 1
Begin
set @strSql = @strSql + N'' having sum(quantity) < 0''
End
Else
Begin
set @strSql = @strSql + N'' having sum(quantity) <> 0''
End
set @strSql = replace(@strSql, ''"'', char(39))
--print @strSql
exec sp_executesql @strSql
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesOfLastYear]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpShopItemSalesOfLastYear]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--SpShopItemSalesOfLastYear  1, 2003, 1, ''12132'',''''
--Modified on                  : 22/07/2004
--Modified by                  : venkitesh
--Comments                     : Created for Budgeting item sales value taking
--
CREATE Proc [dbo].[SpShopItemSalesOfLastYear] (@intdepartmentid as int,
	@intyearid as int, @intCompanyId as int, @Time as varchar(50),
	@strHeaderTableName as varchar(50) output)
as
set nocount on
-- 1
begin
declare
@strquery nvarchar(4000)
Declare @intInvCurrId as int, @intDepCurrId as int, @numExchangeRate as numeric(18,8)
Select @intInvCurrId = m.CurrencyId from aPackageSettings a, aAccountMaster m where
a.InventoryId = m.AccountId and a.CompanyId = m.CompanyId and a.COmpanyId = @intCompanyId
Select @intDepCurrId = depCurrencyId from aDepartmentMaster where DepartmentId =
@intDepartmentID  and CompanyId =   @intCompanyID
exec spGetExchangeRate @intCompanyId, @intInvCurrId, @intDepCurrId, @numExchangeRate OUTPUT
set @strHeaderTableName = ''##SalesForBudget'' + convert(varchar(3),@intDepartmentId) + @Time
set @strquery = ''Create table '' +  @strHeaderTableName + ''
(
sitemid integer,
Categoryid integer,
costprice numeric(18,2),
dcostprice numeric(18,2),
ccostprice numeric(18,2),
amount numeric(18,2),
damount numeric(18,2),
camount numeric(18,2),
MonthNo int,
Purchases Numeric(18,2))''
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	posditemid,0,
	sum(posdcostprice * posdQuantity ) costprice,
	sum(posdcostprice * poshDepExRate * posdQuantity) dcostprice,
	sum(posdcostprice * poshExchangeRate * posdQuantity) ccostprice,
	sum(convert(numeric(18, 2),posdUnitPrice)) Amount,
	sum(convert(numeric(18, 2),posdUnitPrice * poshExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),posdUnitPrice * poshDepExRate)) dAmount,
	month(poshBilldate), 0
from
		losposdetail, losposheader
where
	poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0
	and year(poshBilldate)=''+convert(varchar(5),convert(varchar(5),@intyearid))  +
	'' and poshDepartmentid = ''+ convert(varchar(3),@intdepartmentid)+
	'' and  poshCompanyid = '' + convert(varchar(4),@intCompanyId) +
	'' group by posditemid, month(poshBilldate) ''
exec sp_Executesql @strquery
set @strquery = ''insert into '' + @strHeaderTableName + ''
select
	iditemid,0, sum(idcostprice * idQuantity)costprice,
	sum(idcostprice * ihDepExRate * idQuantity)dcostprice,
	sum(idcostprice * ihExchangeRate * idQuantity) ccostprice,
	sum(convert(numeric(18, 2),idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),idUnitPrice * ihExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),idUnitPrice * ihDepExRate)) dAmount,
	month(ihInvoicedate), 0
from
	losinvoiceheader ih, losinvoicedetail invd
where
	ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND
	IHCANCELLED = 0 and ihproforma = 0 and ihtype = ''''i''''
	 and year(ihInvoicedate)=''+ convert(varchar(5),@intyearid) +
	'' and ihDepartmentID=''+ convert(varchar(3),@intdepartmentid) +
	'' and ihCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by iditemid, month(ihInvoicedate) ''
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select  seditemid, 0, sum(sedcostprice * sedQuantity) costprice,
	sum(sedcostprice *  sehDepExRate * sedQuantity ) dcostprice,
	sum(sedcostprice * sehExchangeRate * sedQuantity) ccostprice,
	sum(convert(numeric(18, 2),sedUnitPrice))  Amount,
	sum(convert(numeric(18, 2),sedUnitPrice * sehExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),sedUnitPrice * sehDepExRate)) dAmount,
	Month(sehExchangeDate), 0
from
	losposexchangeheader, losposexchangedetail
where
	sedExchangeid = sehExchangeID and sedShopID = sehShopid and
	SEHCANCELLED = 0 and sedbillorexchange  = ''''E''''
	and year(sehExchangeDate)='' + convert(varchar(5),@intyearid) +
	'' and sehDepartmentID= '' + convert(varchar(3),@intdepartmentid) +
	'' and sehCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by seditemid, Month(sehExchangeDate) ''
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	iditemid,0,sum(idcostprice * reqQty)costprice,
	sum(idcostprice * ihDepExRate * reqQty) dcostprice,
	sum(idcostprice * ihExchangeRate * reqQty) ccostprice,
	sum(convert(numeric(18, 2),idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),idUnitPrice * ihExchangeRate))  cAmount,
	sum(convert(numeric(18, 2),idUnitPrice * ihDepExRate))  Amount,
	month(ihInvoiceDate), 0
from
	 losspecialinvoicedetail, losspecialinvoiceheader ,ashops a,adepartmentmaster b
where
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND
	IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0
	and IhTransFinished = 1 and a.departmentid=b.departmentid
	and year(ihInvoicedate)='' + convert(varchar(5),@intyearid) +
	'' and b.departmentid= ''+ convert(varchar(3),@intdepartmentid) +
	'' and ihCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by iditemid, month(ihInvoiceDate) ''
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	seditemid, 0,
	-sum(sedcostprice*sedExchangeQty) costprice,
	-sum(sedcostprice * sehDepExRate * sedExchangeQty)Dcostprice ,
	-sum(sedcostprice * sehExchangeRate* sedExchangeQty) Ccostprice,
	sum(convert(numeric(18, 2),- sedUnitPrice)) Amount,
	sum(convert(numeric(18, 2),- sedUnitPrice * sehexchangerate))  cAmount,
	sum(convert(numeric(18, 2),- sedUnitPrice * sehDepExRate))  dAmount,
	month(sehExchangeDate), 0
from
	losposexchangeheader, losposexchangedetail
where
	sedExchangeid = sehExchangeID and sedShopID = sehShopid and
	SEHCANCELLED = 0 and sedbillorexchange  =  ''''B'''' and sedexchangeqty>0
	and year(sehExchangeDate)='' + convert(varchar(5),@intyearid) +
	'' and sehDepartmentID='' + convert(varchar(3),@intdepartmentid) +
	'' and sehCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by seditemid, month(sehExchangeDate) ''
-- 6
-- Special invoice return
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	iditemid,0,sum(idcostprice * Reqqty) costprice,
	sum(idcostprice * ihDepExRate* Reqqty) Dcostprice,
	sum(idcostprice * ihExchangeRate* Reqqty) Ccostprice,
	sum(convert(numeric(18, 2),-idUnitPrice)) Amount,
	sum(convert(numeric(18, 2),-idUnitPrice * ihExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),-idUnitPrice * ihDepExRate)) dAmount,
	month(IhInvoiceDate), 0
from
	 losspecialinvoicedetail,losspecialinvoiceheader
where
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
	idratetype = 1 and ihproforma = 0 and ihTransFinished = 1
	and year(ihInvoicedate)='' + convert(varchar(5),@intyearid) +
	'' and IhDepartmentID='' + convert(varchar(3),@intdepartmentid) +
	'' and ihCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by iditemid, month(IhInvoiceDate)  ''
-- 7
-- (- Qty has to be minus so when multiplying - * - =+ so i am removing the - on values )
--venkitesh 150403
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
Select 	grnditemid,0,sum(grncostprice * GRNDQuantity) costprice,
	sum(grncostprice * grnhDepExRate * GRNDQuantity) dcostprice,
	sum(grncostprice * grnhExchangeRate * GRNDQuantity) Ccostprice,
	sum(convert(numeric(18, 2),-grndUnitPrice)) Amount,
	sum(convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),-grndUnitPrice * grnhDepExRate)) dAmount,
	Month(GrnhGoodsreturnnoteDate), 0
from
	losgoodsreturnnoteheader, losgoodsreturnnotedetail
where 	
	GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and
	grnhShopid =  GRNDShopid AND GrnhCancel = 0
	and year(GrnhGoodsreturnnoteDate)= ''+ convert(varchar(5),@intyearid) +
	'' and grnhDepartmentid='' + convert(varchar(3),@intdepartmentid) +
	'' and GrnCompanyID = '' + convert(varchar(4),@intCompanyId) +
	'' group by grnditemid, Month(GrnhGoodsreturnnoteDate) ''
-- 8
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	repinvdpartsid,0,
	sum(repinvdcostprice * repinvdqty) costprice,
	sum( repinvdcostprice *  seinvhDepExRate * repinvdqty) Dcostprice,
	sum(repinvdcostprice * serinvhcmpexrate * repinvdqty) Ccostprice,
	sum(convert(numeric(18, 2),RepInvDRate * repinvpackqty)) Amount,
	sum(convert(numeric(18, 2),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty)) cAmount,
	sum(convert(numeric(18, 2),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty)) dAmount ,
	Month(serinvhdate), 0
from
	losinvoicedpartsreplacedetails,  losserviceinvheader
where
	serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND
	serinvhcancelled = 0 and year(serinvhdate)=''+ convert(varchar(5),@intyearid) +
	'' and serinvhdepartmentid=''+ convert(varchar(3),@intdepartmentid) +
	'' and serinvhCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by repinvdpartsid, Month(serinvhdate) ''
-- 9
exec sp_Executesql @strquery
set @strquery =''insert into '' + @strHeaderTableName + ''
select
	reditemid,0, sum(redcostprice * redQuantity) costprice,
	sum(redcostprice * rehDepExRate * redQuantity) dcostprice,
	sum(redcostprice * rehExchangeRate * redQuantity) ccostprice,
	sum(convert(numeric(18, 2),redUnitPrice)) Amount,
	sum(convert(numeric(18, 2),redUnitPrice * rehExchangeRate)) cAmount,
	sum(convert(numeric(18, 2),redUnitPrice * rehDepExRate)) Amount,
	month(rehExportDate), 0
from
	losExportDetail,  losExportHeader
where
	rehExportID = redExportID and rehShopID = redShopID AND
	rehCancelled = 0 and rehproforma = 0 and rehtype = ''''i''''
	and year(rehExportDate)=''+ convert(varchar(5),@intyearid) +
	'' and rehDepartmentID='' + convert(varchar(3),@intdepartmentid) +
	'' and rehCompanyId = '' + convert(varchar(4),@intCompanyId) +
	'' group by reditemid, month(rehExportDate) ''
	
	exec sp_Executesql @strquery
	set @strquery =''insert into '' + @strHeaderTableName +
	'' select cdItemID, 0, 0, 0, 0, 0, 0, 0, Month(ChCostingDate),
	isnull(sum(cdItemQuantity*  cdCostingPrice),0)  PurchasePrice from
	loacostingheader a , loacostingdetail  b  Where
	a.chCostingID = b.cdCostingID  and a.chcompanyid= ''
	+ convert(varchar(4),@intCompanyId) + '' and year(a.chCostingDate) = '' +
	convert(varchar(5),@intyearid) + ''and chCancelled=0 and chDepartmentId = '' +
	convert(varchar(3),@intdepartmentid) +
	'' Group by cdItemID, MOnth(chCostingDate)''
	exec sp_Executesql @strquery
	
	set @strquery =''insert into '' + @strHeaderTableName +
	'' select lpcditemid, 0, 0, 0, 0, 0, 0, 0, Month(lpchDate),
	isnull(sum(lpcditemqty*  lpcdcostedprice),0)  PurchasePrice from
	loalocalpurchasecostingheader a , loalocalpurchasecostingdetail  b Where
	a.lpchCostingid = b.lpcdcostingid  and a.lpchCompanyid= ''
	 + convert(varchar(4),@intCompanyId) + ''and year(a.lpchDate)= '' +
	 convert(varchar(5),@intyearid) + ''and lpchposted=0  and lpchDepartmentid= '' +
	convert(varchar(3),@intdepartmentid) + '' group By lpcditemid, month(lpchDate)''
	exec sp_Executesql @strquery
	set @strquery = ''Update ''  + @strHeaderTableName +
	'' Set CategoryId = ItemCategoryId
	from aItem where sItemId = aitem.Itemid ''
	
	exec sp_Executesql @strquery
	set @strquery = ''Update ''  + @strHeaderTableName +
	'' Set Purchases = Purchases * '' + convert(varchar(50),@numExchangeRate )
	exec sp_Executesql @strquery
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sphpBouncedChequeDetails]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpBouncedChequeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sphpBouncedChequeDetails 1,''20060101'',''20101010''
--CREATED BY : NIDHEESH PV
--CREATED ON : 14/09/2010
--COMMENTS : To get details of bounced cheques
CREATE proc [dbo].[sphpBouncedChequeDetails] (@IntcompanyId as int, @dtFromDate as varchar(12), @dtTodate as varchar(12))
as
begin
set nocount on
with ctePaymentforShoprcpt(hprhCompanyID,hphCustomerID,hphPaymentID,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprdSettelmentAmount,DepartmentID)
as
(
select distinct rh.hprhCompanyID,vpay.hphCustomerID,vpay.hphPaymentID,
hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprdSettelmentAmount,DepartmentID
from loshpreceiptheader rh inner join loshpreceiptdetail on  hprhCompanyID=hprdCompanyID and
hprhShopID=hprdShopID and hprhReceiptID=hprdReceiptID and hprhCancel=0 and hprhReceiptType=''s''--and hprdProcessingId=236
inner join loshpinvoiceheader on hprdInvoiceID=hpqhQuotationID and hpqhCustomerID=hprhCustomerID and hprhShopID=hpqhShopID and hpqhCancel=0 and hpqhType=''I''
inner join ashops on hprhShopID=shopid
inner join
(
----to select latest payment raised against a receipt----
select vpayid.hphPaymentID,vpdate.hpdReceiptID,vpdate.hpdDepartmentID,vpdate.hphCustomerID,vpdate.hpdProcessingDetailID from
(select hpdReceiptID,hpdDepartmentID,max(hphPaymentDate)date,hphCustomerID,hpdProcessingDetailID from ahppaymentheader inner join  ahppaymentdetail
on hphPaymentID=hpdPaymentID and hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphCancel=0 group by hpdReceiptID,hpdDepartmentID,hphCustomerID,hpdProcessingDetailID)vpdate
inner join
(select hphPaymentID,hpdReceiptID,hpdDepartmentID,hphPaymentDate,hphCustomerID,hpdProcessingDetailID from ahppaymentheader inner join  ahppaymentdetail
on hphPaymentID=hpdPaymentID and hphCompanyID=hpdCompanyID and hphDepartmentID=hpdDepartmentID
and hphCancel=0)vpayid
on vpdate.hpdReceiptID=vpayid.hpdReceiptID and vpdate.hpdDepartmentID=vpayid.hpdDepartmentID and vpdate.hphCustomerID=vpayid.hphCustomerID
and vpdate.hpdProcessingDetailID=vpayid.hpdProcessingDetailID and vpayid.hphPaymentDate=vpdate.date
--where  vpdate.hphCustomerID= 1170
----to select latest payment raised against a receipt----
)vpay
on vpay.hpdReceiptID=hprhReceiptID and vpay.hpdDepartmentID=DepartmentID and vpay.hphCustomerID=hpqhCustomerID
and hprdProcessingDetailId=vpay.hpdProcessingDetailID
)
---select * from ctePaymentforShoprcpt
,ctechqdtls(hpdDepartmentID,hpdProcessingId,hpdDetailID,hpdChequeDate,hpdBankName,hpdChequeNo)
as
(
select hpdDepartmentID,hpdProcessingId,hpdDetailID,hpdChequeDate,hpdBankName,hpdChequeNo from ahpprocessingdetail
where  hpdChequeDate>=@dtFromDate and hpdChequeDate<=@dtTodate
)
,cteOutput(hprhCompanyID,hphCustomerID,hphPaymentID,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprdSettelmentAmount,DepartmentID,hpCustName,DepartmentName,hpdChequeDate,hpdBankName,hpdChequeNo)
as
(
select cte.hprhCompanyID,hphCustomerID,hphPaymentID,hprdInvoiceID,hprdProcessingId,hprdProcessingDetailId,hprdSettelmentAmount,cte.DepartmentID,hpCustName,DepartmentName,hpdChequeDate,hpdBankName,hpdChequeNo
from ctePaymentforShoprcpt cte left outer join
(ahpReceiptHEader arh inner join ahpReceiptdetail ard on hprdReceiptID=hprhReceiptID and hprdDepartmentID=hprhDepartmentID
and hprhCancel=0 and (hprhnewcheque is null or hprhnewcheque=0))
on hphPaymentID=hprdPaymentID and hprdDepartmentID=DepartmentID
inner join loshpcustomerdetails on hpCustID=hphCustomerID and hpCompanyID=cte.hprhCompanyID
inner join adepartmentmaster d on d.departmentid=cte.DepartmentID and CompanyID=cte.hprhCompanyID
inner join ctechqdtls on hprdProcessingId=hpdProcessingId and hprdProcessingDetailId=hpdDetailID
where hprhReceiptID is null
)
select * from cteOutput where hprhCompanyID=@IntcompanyId
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyHeader]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSdummyHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Modified BY : Rajesh Kamalskshan
--Modifies On : 1-05-2007
--Purpose : for using in dummy pos bill
-----------------------------------------------------------------------------------------------------------------------------
--Modified BY : Nidheesh P V
--Modifies On : 23-06-2011
--Purpose : Added new parameter
--Reference : RefNo-1
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spInsertPOSdummyHeader]
@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,2),
@intDiscount As Numeric(18,2),
@intBillAmt As Numeric(18,2),
@intCashAccId As Int,
@intCustId As Int,
@strRemarks As Varchar(250),
@intCmpExRate As Numeric(18,2),
@strBillNo As Varchar(30),
@strConCardNo as Varchar(50),
@intDiscountAmt as Numeric(18,2),
@intBalanceAmt as Numeric(18,2),
@intconfirmed as int
As
Begin
Declare @intDepId As Int
Declare @strUser As Varchar(20)
Declare @intSalesAccId As Int
Declare @intWholeSale As Int
Declare @strCardNo as Varchar(20)
--Finding the User Name with the @intUserId passed
Select @strUser = UserName From aUsers Where UserId=@intUserId
--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
--Insertion is done in the following sequence
--poshShopID,poshBillID,poshBillNo,poshBillDate,poshCustomerName,poshCancelled,poshCancelledRemarks,poshRecAddUser,
--poshRecModifyUser,poshPosted,poshDiscount,poshBillAmount,poshCashAccID,poshSalesAccID,poshCompanyID,poshReturned,
--poshWholesale,poshcbid,poshExchangeRate,poshfuturevc,updatetime,poshDepartmentid,poshsalespersonid,poshcustomerid,
--poshCustomerCardNo,poshfutureint,poshcurexrates,rowguid,poshdepexrate,poshexchangerates,poshUserId,poshCounterId
Insert InTo LOsPosdummyHeader Values(@intShopId,@intBillId,@strBillNo,@dtBillDate,@strCustName,0,
@strRemarks,@strUser,NULL,0,@intDiscount,@intBillAmt,@intCashAccId,@intSalesAccId,1,0,
@intWholeSale,NULL,@intCmpExRate,NULL,GetDate(),@intDepId,@intSalesPerId,
@intCustId,@strCardNo,NULL,NULL,NewId(),@intDepExRate,@strExRate,@intUserId,@intCounterId,@strConCardNo,
@intDiscountAmt,@intBalanceAmt,right(current_timestamp,7),0,@intconfirmed,Null) --RefNo-1
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlightOperator]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertFlightOperator]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
--Created on 	: 04/Oct/2010
--Created by	: Praveen S
--Comments	: For Inserting the Details In Flight Operator
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spInsertFlightOperator]
@flghtopcompanyid INT,
@flghtopid INT,
@flghtopname VARCHAR(50),
@flghtsegid INT,
@flghtopcrtdate DATETIME,
@flghtremarks VARCHAR(250),
@flghtactive BIT
AS BEGIN
	 SET NOCOUNT ON
	 INSERT INTO FlightOperatorMaster(companyid,FlghtOpid,FlghtOpName,FlghtSegID,Createddate,Remarks,Active)
	 VALUES
	 (@flghtopcompanyid,@flghtopid,@flghtopname,@flghtsegid,@flghtopcrtdate,@flghtremarks,@flghtactive )
		
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertAccountsDefaultValues]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertAccountsDefaultValues]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATE PROC [dbo].[spInsertAccountsDefaultValues] @intCompanyid as int,@intUserid as int,
--@intCurrencyid as int,@finyearperiod as int,@companycode as varchar(10)
CREATE PROC [dbo].[spInsertAccountsDefaultValues]
as
Begin
update apackagesettings set customsaccid=Null,HQPurchaseAccID=NULL,GoodsInTransitID=NULL,
LCGroupID=NULL,InventoryID=NULL,CostofGoodsid=NULL,LcMarginGroupID=NULL,
shipmentfixedandactualvaluediff=NULL,compprofitshareacc=NULL,costofsalesid=NULL,
stocktransfercontrolacc=NULL,profittransfercontrolacc=NULL,Returnadjustmentaccid=NULL,
PurchaseRtnAccID=NULL,POGITAccountid=NULL,AssetConversionAccid=NULL,
interdepsalescntrlaccid=NULL,BusinessPromotionAcc=NULL,WarrentyClaimAcc=NULL,
PPandEAccid=NULL
DELETE FROM aSettings
DELETE FROM aAccountMaster
DELETE FROM aGroupMaster
DELETE FROM MiscSettings
DELETE FROM abarcodetype
DELETE FROM aShipment
DELETE FROM aUserRights
DELETE FROM AUserMasterGridSettings
DELETE FROM aUserGroupreportrights
DELETE FROM aUserGroupRights
DELETE FROM ausers
DELETE FROM aUsergroups
---*****************For inserting Group Master*****************--------
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (1,1,''Fixed Assets'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (2,1,''Current Assets'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (3,1,''Long Term Liabilities'',''L'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (4,1,''Short Term Liabilities'',''L'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (5,1,''Capital & Drawings'',''L'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (6,1,''Sales Income'',''I'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (7,1,''Income from Other Source'',''I'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (8,1,''Administrative Expenses'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (9,1,''Financial Expenses'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (53,1,''Trade Creditors'',''L'',4,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (55,1,''Advances, Deposits and Prepayments'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (13,1,''Land '',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (14,1,''Building'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (15,1,''Building - Leasehold'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (16,1,''Office Equipments'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (59,1,''Electrical Equipments'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (18,1,''Bank and Cash '',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (19,1,''Trade Debtors'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (20,1,''Stock'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (60,1,''Computers'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (45,1,''Cost of sales'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (26,1,''Electricity Charges'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (27,1,''Fee, Taxes Payable'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (29,1,''Insurance'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (30,1,''Expatriate Charges'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (31,1,''Misc. Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (32,1,''Rent '',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (33,1,'' Repairs and Maintenance'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (34,1,''Periodicals & Subscriptions '',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (36,1,''Gas, Fuel and Water Charges'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (38,1,''Entertainment Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (40,1,''Other Assets'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (42,1,''LC Margin A/cs'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (43,1,''Others Short Term Liabilities'',''L'',4,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (44,1,''SPE Payable '',''L'',4,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (46,1,''Selling and Distribution Expenses'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (47,1,''Staff Expneses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (48,1,''Travelling Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (49,1,''Telephone, Telex and Fax Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (50,1,''Printing and Stationary Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (52,1,''Postage Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (54,1,''Donations'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (56,1,''Advances'',''A'',55,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (57,1,''Deposits'',''A'',55,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (58,1,''Prepayments'',''A'',55,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (61,1,''Furnitures & Fixtures'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (63,1,''Vehicles'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (69,1,''Other Debtors'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (65,1,''Capital'',''L'',5,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (66,1,''Drawings'',''L'',5,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (67,1,''Retained Earnings'',''L'',5,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (68,1,''Other Current Liabilities'',''L'',4,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (80,1,''Cost of Goods Sold'',''E'',45,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (72,1,''Inventories'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (73,1,''Goods in transit'',''A'',72,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (74,1,''Goods In Hand'',''A'',72,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (75,1,''Current Liabilities'',''L'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (76,1,''Short Term Borrowings'',''L'',75,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (77,1,''LC Outstanding'',''L'',76,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (78,1,''Cash & Cash Equivalents'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (79,1,''L/c Margin with Banks'',''A'',78,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (81,1,''Purchase Account'',''E'',80,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (82,1,''Direct Expenses'',''E'',80,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (83,1,''Prchase Return'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (84,1,''Non  Current Assets'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (85,1,''Asset Conversion Account'',''A'',84,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (86,1,''Stock Loss/Recovered'',''E'',80,3,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (87,1,''Compny Dept profit account'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (88,1,''Profit Transfer'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (107,1,''POGITA'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (90,1,''Control Accont'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (91,1,''Business Promotion Acc'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (92,1,''Warrenty Claim'',''A'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (93,1,''PP&E account'',''A'',1,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (94,1,''Other Expenses'',''E'',8,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (95,1,''Other income'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (96,1,''Cash Sales'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (97,1,''credit Sales'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (98,1,''discount'',''E'',46,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (99,1,''Utility Account'',''E'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (100,1,''Debit/credit'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (101,1,''Write Off account'',''E'',46,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (102,1,''Goods Return'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (103,1,''Service account'',''A'',40,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (104,1,''Servicing'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (105,1,''Advance'',''L'',75,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (106,1,''Fine /discount'',''I'',7,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (108,1,''TAX Account'',''A'',2,2,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (200,1,''Tax Liabilities'',''L'',NULL,1,11,newid())
INSERT INTO [adminv2].[dbo].[agroupmaster]  ([GroupID]  ,[CompanyID]  ,[GroupDesc]  ,[AccountType]  ,[ParentGroupID]  ,[LevelCode]  ,[OrderNo]  ,[rowguid])  VALUES (201,1,''Out PUT GST '',''L'',75,2,11,newid())
---**********************For inserting Account Master *******************---
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (6,1,''06'',1,81,''COST OF GOODS'',''S'',0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (2,1,''02'',1,73,''GOODS IN TRANSIT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (3,1,''03'',1,74,''INVENTORY'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (5,1,''05'',1,79,''LC MARGIN'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (7,1,''01'',1,82,''CUSTOMS DUTY'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (8,1,''07'',1,83,''PURCHASE RETURN A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (9,1,''08'',1,85,''ASSET CONVERSION'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (10,1,''09'',1,86,''IMPORT SHORT/EXCESS'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (11,1,''10'',1,81,''COSTING DIFF A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (12,1,''11'',1,74,''STOCK TRANSFER CONTROL ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (13,1,''12'',1,87,''COMPANY DEPT PROFIT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (14,1,''13'',1,88,''PROFIT TRANSFER ACC'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (15,1,''14'',1,86,''RECOVERY OF STOCK'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (46,1,''19'',1,107,''POGITA ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (17,1,''16'',1,90,''INTER DEPT PROFIT CONTROL A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (18,1,''17'',1,91,''BUSINESS PROMOTION A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (19,1,''18'',1,92,''WARRENTY CLAIM ACC'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (23,1,''22'',1,94,''EXCHANGE GAIN OR LOSS'',''ED'',0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (21,1,''20'',1,19,''TRADE DEBITORS'',''TD'',0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (22,1,''21'',1,53,''TRADE CREDITORS'',''TC'',0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (24,1,''23'',1,67,''RETAINED PROFIT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (27,1,''26'',1,90,''FIXED ASSETS TRANS CONTROL A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (28,1,''27'',1,18,''CASH ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,''CA'',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (29,1,''28'',1,18,''BANK ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,''BA'',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (30,1,''29'',1,96,''CASH SALES'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (31,1,''30'',1,81,''PURCHASING A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (32,1,''31'',1,97,''CREDIT SALES A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (33,1,''32'',1,9,''SHOP EXPENCES'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (34,1,''33'',1,98,''DISCOUNT A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (35,1,''34'',1,99,''UTILITY ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (36,1,''35'',1,100,''DEBIT/CREDIT ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (37,1,''36'',1,101,''WRITEOFF A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (38,1,''37'',1,94,''OTHER CHARGES A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (39,1,''38'',1,94,''IN-HOUSE A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (40,1,''39'',1,102,''GOODS RETURN A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (42,1,''41'',1,104,''SERVICE A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (43,1,''42'',1,105,''ADVANCE A/C'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (44,1,''43'',1,106,''FINE ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (47,1,''45'',1,95,''DISPOSAL SALES ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (48,1,''46'',1,85,''ASSET DISPOSAL'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (49,1,''47'',1,85,''ASSET TRANSFER CONTROL'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (51,1,''48'',1,18,''PD CHEQUE'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (52,1,''49'',1,108,''GODDS TAX  ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (53,1,''888'',1,77,''SERVICE TAX  ACCOUNT'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (57,1,''54'',1,201,''GOODS OUTPUT TAX'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (58,1,''55'',1,201,''SERVICE OUT PUT TAX'',NULL,0.00,NULL,NULL,NULL,11,1,'''',newid())
---****************For inserting Accounts Settings---*******************
INSERT [dbo].[aSettings] ([SettingID], [CompanyID], [NoOfPreviousDays], [InvoicePeriod], [FinancialYearPeriod], [FixedAssetGroupID], [CashGroupID], [BankGroupID], [TradeDebtorAcID], [TradeCreditorAcID], [SalesGroupID], [PurchaseGroupID], [SepProformaInvoiceNo], [SepProductServiceNo], [AverageRate], [EnableTargetCheck], [EnableBudgetCheck], [ExchangeDiffAcID], [Retainedearningsacc], [openingfreezed], [BackDay], [depreciationid], [rowguid], [autogenerateasstcode], [debtorsaccid], [creditorsaccid], [payablealertbeforedays], [alertbeforedays], [depriciationexpaccid], [disposalaccount], [transferaccount], [astopendate], [RefBillId], [CurrentAssetGroupId], [CurrentLiabilityGroupId], [CurrentShareCapitalGroupId]) VALUES (1, 1, 30, 30, 12, 1, 1, 18, 21, 22, 6, 81, 0, 0, 0, 0, 0, 23, 24, 0, NULL, NULL, newid(), 0, 21, 22, NULL, NULL, 47, 48, 49, CAST(0x00009D5000000000 AS DateTime), NULL, 2, 75, NULL)
---****************For inserting Accounts Package Settings---*******************
update apackagesettings set BackNoOfDays=30,HQPurchaseAccID=10,customsaccid=7,GoodsInTransitID=2,
LCGroupID=77,
InventoryID=3,CostofGoodsid=6,LcMarginGroupID=79,futureint=15,futurevc=''n'',
movementperiod=30,importperiod=30,analysisperiod=''M'',shipmentfixedandactualvaluediff=11,compprofitshareacc=13,
stocktransfercontrolacc=12,
profittransfercontrolacc=14,AllowItemCodeDuplication=0,
PurchaseRtnAccID=8,POGITAccountid=46,AssetConversionAccid=9,interdepsalescntrlaccid=17,
EnableCRMContacts=0,CompanyLogin=0,hirepurchase=0,Payrollneeded=0,DisableDataFiltersForCustomers=0,
DisableDataFiltersForVendors=0,BusinessPromotionAcc=18,WarrentyClaimAcc=19,HQLocalPurchaseConfirmation=0,
BlockAddingNewItemToShops=0,FineEnabled=0,IntegerQuantity=0,Alias=0,ActiveDirectoryLogin=0,
AllowEnteringSlNoInSplInvoice=0,
ReorderLevelMandatory=0,ItemwiseAccountinginInHousecon=0,
AllowDirectLocalPurchaseCosting=0,
DeliveryItemsVerificationUrl='''',VisibleDepartmentPurReq=0,AllowMultipleQuotations=0,EnableRemainderAccBills=0,
AutoConfirmAccTrans=0,SellingPriceBelowCostPrice=0,CreditLimitType=''C'',ReportServerName='''',PPandEAccid=93,
NoCreditForOverdueCustomers=0,ReportLogo=0,postdatedcheque=0,AutomateSegmentwisePrice=0,
EnableGST=0,TaxCategoryforServices=0,EnableGSTinForeignPurchase=0
---****************For inserting Misc Settings---*******************
INSERT [dbo].[MiscSettings] ([ItemCodeAutoGen], [SupplierCodeAutoGen], [CustomerCodeAutoGen], [showavailableqtyinTrOut], [showavailableqtyinGReq], [backdateprocess], [lastdatatransfercheckdate], [showlocationswitch], [freezbalanceday], [Docomparebcandstock], [setcom], [AllowItemCodeDuplication], [allowlocalpurchhq], [fixsellingpriceaftercosting], [allowoldporefinpurchasebill], [customertoshoponcreation], [openingbalancenottallying], [moduleextended], [defaultfetch], [ReportSorting], [AccountsFreezeDate], [Lctoaccount], [AllowZeroLcMargin], [CustomisedFor]) VALUES (0, 0, 0, NULL, NULL, 0, NULL, 1, NULL, NULL, NULL, 0, 0, 1, 0, 0, 0, NULL, N''ItemCode'', NULL, CAST(0x0000934F00000000 AS DateTime), 1, 0, NULL)
---****************For inserting abarcodetype---*******************
INSERT [dbo].[abarcodetype] ([barcodetype], [filename], [rowguid]) VALUES (1, N''C:\MiscSetting'', N''f996d425-4178-498a-8764-0cec070738ef'')
---****************For inserting [aShipment]---*******************
INSERT [dbo].[aShipment] ([sShipmentID], [sShipmentNO], [sBillID], [sShipmentDate], [sCostingDone], [rowguid]) VALUES (1, N''shipment'', 0, CAST(0x0000931300D7F58C AS DateTime), 0, N''9cbf2053-5b86-431b-a1da-d6fad7712003'')
---****************For inserting [usergroup]---*******************
INSERT [dbo].[aUsergroups] ([UserGroupID], [CompanyID], [UserGroupName], [Description], [rowguid]) VALUES (1, 1, N''Full Rights User'', N''Full Rights User'', N''f5136cef-652f-4e65-96f6-a6100d793f5b'')
---****************For inserting [user]---*******************
INSERT [dbo].[aUsers] ([UserID], [CompanyID], [UserName], [UserPwd], [FullName], [ShopID], [GodownID], [logedon], [GlobalUserID], [rowguid], [UserGroupID], [EmailID]) VALUES (2, 1, N''fies'', N'''', N''fies'', NULL, NULL, 1, NULL, N''80441252-5a68-472b-a08c-cebc7dcf62ce'', 1, N'''')
/****** Object:  Table [dbo].[aUserGroupRights]    Script Date: 04/12/2012 15:18:14 ******/
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 8019, N''NEDPU'', 1, N''c3f0e6e5-73e8-4400-899b-9ee3eb5a2a83'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 22, N''NEDPU'', 1, N''6ea6d98f-8e40-47df-a66b-b1d5ca902062'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91028, N''NEDP'', 1, N''ee7b0002-4254-40cc-8355-c01ecba934f2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91035, N''NEDP'', 1, N''7a1a9b30-5462-4af7-9679-8400e5d37ff0'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90002, N''NEDP'', 1, N''c625e500-7da8-4c52-8ba9-a2bdf226af9f'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91019, N''NEDP'', 1, N''0f497524-bd7d-4696-8cf0-be1c55cefd7d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90019, N''NEDP'', 1, N''c6b4c0bd-e548-4451-b6de-cd118788731f'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90010, N''NEDP'', 1, N''532dd8b7-3e80-4f0d-b24e-4cb2ea2470ce'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90020, N''NEDP'', 1, N''2cc17f6f-90be-4864-a8e2-f63036909209'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91034, N''NEDP'', 1, N''a5b4bb09-1ef4-4bb7-9b5f-de3dd761dcb3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90016, N''NEDP'', 1, N''167c6803-ba35-4a2f-8fa0-207396fffd77'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90017, N''NEDP'', 1, N''f128dffc-33c9-42c0-a281-d3a22db4a9bc'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91029, N''NEDP'', 1, N''82cbd872-c30d-4629-b9dc-7072b3be962d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90003, N''NEDP'', 1, N''35f37bbb-dd29-4a7f-a28c-79c6a3b18f79'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 92000, N''NEDP'', 1, N''686699d7-af84-432d-b627-f66d9a1a2090'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90001, N''NEDP'', 1, N''43ef9272-96f3-416a-980f-028050c16170'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91003, N''NEDP'', 1, N''2daaffdc-fd5b-463d-8243-21034d987521'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90008, N''NEDP'', 1, N''ce6d496c-a592-492b-9f76-cfc9ffb59a15'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91027, N''NEDP'', 1, N''8c0f5ba3-aa22-4b88-a58c-7543d3d99864'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90009, N''NEDP'', 1, N''3436c7fe-453c-439e-84f2-70da059caf42'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91030, N''NEDP'', 1, N''8fc3ab07-0337-420a-9def-c521735c2233'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90023, N''NEDP'', 1, N''e4862584-c225-41f2-b118-e46ea9676a3d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 3000, N''NEDP'', 1, N''a5bcd5b5-4462-40ad-a22f-42d5aadfe0fd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91025, N''NEDP'', 1, N''13b8e16d-2972-4931-8eb5-55ec2ee80487'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91031, N''NEDP'', 1, N''f11c7aec-5002-416c-a2c6-cd3f6dc7f4a5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90018, N''NEDP'', 1, N''b7164235-9424-4ba4-b0f8-40f053ee64fa'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91017, N''NEDP'', 1, N''c1299442-1545-4bf6-8e17-5a4e8c9ef292'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90015, N''NEDP'', 1, N''d274b29d-3db7-4a49-ba88-eed5c359b976'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90007, N''NEDP'', 1, N''b6035dbd-5dff-453d-93cb-bf4d19a0adb8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91004, N''NEDP'', 1, N''dfb9c641-c656-4010-94e8-96dba7f367c7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91032, N''NEDP'', 1, N''d91421b5-4fe6-4a37-a707-16e60d387248'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90022, N''NEDP'', 1, N''a8d2b9e6-cba5-48ac-b649-24277d52c71a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91016, N''NEDP'', 1, N''5347bf2e-3d1f-439c-8976-2d175c926c10'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91018, N''NEDP'', 1, N''b6cc4e4c-2ce5-4604-a1dc-b006aac3d2ac'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91005, N''NEDP'', 1, N''a2ff9947-1e14-4183-bdcc-204067b1d8c8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91006, N''NEDP'', 1, N''3644319e-2279-4025-bac0-ddabfb242fc5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91020, N''NEDP'', 1, N''fcba07e0-ff5e-44f4-9d54-676412862be0'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90006, N''NEDP'', 1, N''2bb8a165-3992-45e9-a270-8d742b425466'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91026, N''NEDP'', 1, N''44c79a7f-f366-41e9-9668-0820b76c14fc'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91011, N''NEDP'', 1, N''23152d9a-446f-4667-985c-3de08d125b2e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90004, N''NEDP'', 1, N''1309dae4-b751-4386-9a57-f80783d4a133'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91001, N''NEDP'', 1, N''0cb1690d-b567-4bb9-9934-b0b69eac581c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90014, N''NEDP'', 1, N''e41a0913-04ed-4735-851c-1ccdaa65b32d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91013, N''NEDP'', 1, N''9d9fd556-4ac9-4579-9cca-a8618dec84d9'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91007, N''NEDP'', 1, N''d4d21499-e372-4c71-97ac-33d3a3d97206'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91002, N''NEDP'', 1, N''56dd2e02-7607-41d8-9865-07013eda65bd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91024, N''NEDP'', 1, N''ed23ace2-3c1f-4696-88ec-9bc4dc07cbdc'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91037, N''NEDP'', 1, N''62fab9ea-d14c-4447-b823-cf3a04a673a2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91038, N''NEDP'', 1, N''6a27ad14-af8d-446c-a3b0-ed39d6836e72'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91010, N''NEDP'', 1, N''ee0356c4-3c69-45ce-adfa-a251044a269c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90012, N''NEDP'', 1, N''169201b7-d38c-4aa1-a90f-83a74ccbfeba'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91021, N''NEDP'', 1, N''a8a08a95-2aba-43eb-9bb9-903b5b14f56e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91033, N''NEDP'', 1, N''2faca628-5e8b-4659-b11c-e6a45d97fc5c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90021, N''NEDP'', 1, N''d8e08908-aa12-4ea7-aa96-4fd0a888c099'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91014, N''NEDP'', 1, N''2bc3126c-65b4-4569-9709-82670cf811f9'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90005, N''NEDP'', 1, N''f6d22251-94ca-4968-be02-3e1f2e3318a7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91036, N''NEDP'', 1, N''f5bf2690-4757-4e5f-9c41-740e5390ccad'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90013, N''NEDP'', 1, N''232c87b2-6816-46b0-af79-2c51cb3c3cd3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 90011, N''NEDP'', 1, N''ce245a6c-fde8-418f-b3d0-234a6b1c7f24'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91022, N''NEDP'', 1, N''55cd92a4-d0d7-499e-936a-e59cf9474c6b'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 5019, N''NEDP'', 1, N''6111c1da-9e56-4b95-b9b4-b6a4c9050aab'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''pay'', 91023, N''NEDP'', 1, N''86f45d50-be76-4c1d-b28c-d8e2a11bff8c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 2201, N''NEDP'', 1, N''17e5e496-9df1-4581-abff-82f40130409a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8010, N''NEDP'', 1, N''45d8fc4b-2906-49f6-8248-fabc2ee3c9d6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8005, N''NEDP'', 1, N''9b5dedb3-b75f-45f0-a3ca-19ddf916142e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8001, N''NEDP'', 1, N''9e3a3889-a231-4e1e-9364-219e799bc191'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8003, N''NEDP'', 1, N''92be04c2-3b9c-4651-8248-34e9ddf6fa92'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 2202, N''NEDP'', 1, N''6321f9d6-f7bd-4ffe-bc72-4349ed94f6dd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8004, N''NEDP'', 1, N''cc36c767-3453-4338-b94d-4fcb67d386c4'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''bgt'', 8002, N''NEDP'', 1, N''cdb18040-2229-43f6-983f-844258814ba2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''admin'', 106, N''NEDP'', 1, N''0c43b901-2386-4eb6-b08f-c606245ade2b'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''admin'', 105, N''NEDP'', 1, N''a0a26c4a-bc6e-4bfc-bb13-fdda88a62957'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''admin'', 103, N''NEDP'', 1, N''450a5134-4b59-4fda-adac-c05b093e3229'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''admin'', 104, N''NEDP'', 1, N''bea76fd6-4b76-4335-baa2-46a7c37118c8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6101, N''NEDS'', 1, N''7bf2063f-1e42-417e-b587-826b12f78d5d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6102, N''NEDS'', 1, N''d4fe7961-dc21-4376-8733-8e2bfaf4f90a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6103, N''NEDS'', 1, N''73219c66-e8bc-4905-8c34-eac33b4e071a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6100, N''NEDS'', 1, N''e0c4fb06-e6f7-44d4-b170-3f233210bdb1'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6113, N''NEDS'', 1, N''8169f9a8-e84a-433f-bf6b-67a15453f680'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6115, N''NEDS'', 1, N''4212d9dc-c528-43d0-a987-a6c0e86dd6c9'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6107, N''NEDS'', 1, N''a7eaa4d6-1409-4ee2-99b1-ae6a65bd2c91'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6111, N''NEDS'', 1, N''b179910a-4a22-48bc-b19c-d7d88b231a40'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6116, N''NEDS'', 1, N''18d02f72-dd1c-486f-b662-4dd24d6fdac1'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6104, N''NEDS'', 1, N''6d36453e-7c69-48db-9cb5-96d384e47ccf'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6106, N''NEDS'', 1, N''814b69b6-8090-4423-ae21-82367cd966f5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6105, N''NEDS'', 1, N''d4c26d34-6416-42af-9216-42feaa08ca79'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6108, N''NEDS'', 1, N''3a8b2e09-5cd0-4f05-a61e-2ce5b3f7d487'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6114, N''NEDS'', 1, N''f5e2563a-5d8b-432c-8aa9-c3fb23f642f0'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''crm'', 6112, N''NEDS'', 1, N''66a27427-bd74-47d4-a138-7f4453d9b12c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''lms'', 6201, N''NEDS'', 1, N''fc398f5b-ce1f-499e-a029-c1538846bd22'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''lms'', 6200, N''NEDS'', 1, N''4d0d3fe3-fc95-4590-9fc8-451ba742f5af'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 6, N''NEDP'', 1, N''989de57c-0cc7-4cf5-834f-3d2427e8ec3c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 31, N''NEDP'', 1, N''501f9bb7-0ab8-470a-a988-f209e0687e52'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 40, N''NEDP'', 1, N''7541a0fc-146a-4bdc-8149-893ac6cdb73e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 4001, N''NEDP'', 1, N''e40a2598-d015-4027-89e7-42accac9986e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 19, N''NEDP'', 1, N''3a3c9750-ec97-4d59-8465-fd57efa24928'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 5, N''NEDP'', 1, N''b14a2a1a-89e8-447d-a4f9-81a242789a35'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 5029, N''NEDPI'', 1, N''02a03ce6-58bc-4195-b98e-d69de96fc4c6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 2512, N''NEDP'', 1, N''a8efc62a-5562-492e-b0e7-c2d83a88396d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''accp'', 26, N''NEDP'', 1, N''4c6bab35-fbbd-4bed-b1c5-80358a8c5496'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 51, N''NEPD'', 1, N''6f8834ce-f994-4e52-b90b-b8e5e157db96'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 6008, N''NEPD'', 1, N''d8c963e3-310a-413f-9571-42b8eb722dc2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 53, N''NEPD'', 1, N''16e3397a-aa82-4c06-82dc-39ad32b0c573'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 55, N''NEPD'', 1, N''76d383d0-3513-4dc1-96b5-4b9088f75953'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 54, N''NEPD'', 1, N''040852ae-9e3a-4f7e-b14c-c81b7fdc70f2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 2012, N''NEPD'', 1, N''5e58f010-843a-4940-875c-30e7e0a1b7bb'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 56, N''NEPD'', 1, N''0972e2b5-0b8a-4f82-86ef-b164105843e6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 999, N''NEPD'', 1, N''654b58ad-bde4-4d9c-86f9-fe501c99927b'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 2021, N''NEPD'', 1, N''a3121bda-2c22-4711-98d7-c22268b416a2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 57, N''NEPD'', 1, N''284c6b21-9f8d-47ac-a8eb-aab0fe56920f'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''sacc'', 10006, N''NEPD'', 1, N''1fcc5402-635f-4dbe-a13a-5cf79f00f5e3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2004, N''NEDPU'', 1, N''ba62b29f-7cdb-4113-a3f2-c4611888ece9'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2006, N''NEDP'', 1, N''93fddefc-a5c1-4bb1-9da0-2c3a63a91af5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2005, N''NEDP'', 1, N''1a7080a2-dc46-49b5-a930-a147be9804ce'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2009, N''NEDP'', 1, N''f8a4c8d8-06a5-4861-b6cd-30bb9c65bf79'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8013, N''NEDP'', 1, N''2f8143b4-6e8a-40fc-8750-dfc918f121bb'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8012, N''NEDP'', 1, N''89c4f18e-0b7d-4b43-a77b-e6b8f88e4d9c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2007, N''NEDP'', 1, N''57777ad6-a426-44c7-85bf-b858d5379f46'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2008, N''NEDP'', 1, N''b0b7c5d3-3576-44be-897e-ae73b59b11ca'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2003, N''NEDPU'', 1, N''28e6e5aa-19f6-4796-9484-1d13ffd6859e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8032, N''NEDP'', 1, N''5e010f7c-325a-4a5a-ae56-9aea9cfa3f5e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2027, N''NEDP'', 1, N''392cc812-7e8d-44f4-aaf3-c75fcbea2a95'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2013, N''NEDP'', 1, N''8e12cdc1-27b6-4c93-82d1-81048701ca37'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2028, N''NEDP'', 1, N''c93512b5-65ec-480d-a098-06eb10cfce8a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8015, N''NEDP'', 1, N''ee818dc4-eefd-4522-ba10-f9c4f6554811'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8006, N''NEDP'', 1, N''7a52b5ac-e494-46dc-89a0-2bc863fa471d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2010, N''NEDP'', 1, N''019dfee6-711d-4c10-9634-d796d84bdb7b'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2513, N''NEDP'', 1, N''4ca592aa-b3e7-44a9-8b5d-2bc73f189d7c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2011, N''NEDP'', 1, N''2273226b-fb9e-449c-90b6-d8357f930364'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8017, N''NEDP'', 1, N''44c73dda-e9ff-499d-974d-b8d9102da883'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8014, N''NEDP'', 1, N''b7f8443a-f45c-4bef-a0e6-d504bf6d2adf'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2514, N''NEDP'', 1, N''c11fe360-2100-4fc0-adaa-35471425b4c3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8011, N''NEDP'', 1, N''41fce8ec-9158-43b7-964a-b3eee17dd70c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2001, N''NEDPAVC'', 1, N''1a7a9fd2-0e93-4a16-9c3e-35e3f629bf31'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2022, N''NEDP'', 1, N''bf0d1352-0da2-447b-a5c2-bd12a8c585c0'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2000, N''NEDPJ'', 1, N''1cce1942-6080-490b-947e-62a3576b66ca'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2015, N''NEDPU'', 1, N''f33683e2-1a62-4691-819b-11a2faffc5d4'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2002, N''NEDP'', 1, N''c0490e10-4b60-497a-bf40-285b7d0c4bf5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2016, N''NEDP'', 1, N''e9a733dd-dec1-48cb-a732-15d689a52015'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2014, N''NEDP'', 1, N''2649a5f6-d786-452d-a547-b7121062f757'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2019, N''NEDP'', 1, N''e965107b-c940-4f58-a8b2-f5f25a836b1a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2029, N''NEDP'', 1, N''db895b6f-69b0-46f3-a451-abe494e3bf52'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 8009, N''NEDP'', 1, N''5429cc71-03ad-4f8a-aa1a-dbe6db5a5199'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 92032, N''NEDP'', 1, N''b11ba05d-bf50-43ec-aa16-509252fbafa2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2030, N''NEDP'', 1, N''8a837b46-8ee7-4ece-a29a-2068f4ceed48'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 2018, N''EPIMHW'', 1, N''450cd1ce-2cc3-4f97-9f82-de8d12390b82'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 112, N''NEDP'', 1, N''19b97068-cd30-4c01-849a-c7c0a0aa5148'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 8034, N''NEDP'', 1, N''74cc8589-e282-4c18-a650-63fb71b06ab5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 34, N''NEDP'', 1, N''9401931c-0906-45c0-8693-43839d5dccf4'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 67, N''NEDP'', 1, N''13508c5f-3ae1-4286-989f-1c118bfa8336'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 75, N''NEDP'', 1, N''e6068d25-70db-45a7-a79b-bed395844b22'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 30, N''NEDP'', 1, N''724c4cef-dfb4-4b60-9a75-be1e7c24c15b'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 77, N''NEDP'', 1, N''6842e719-a589-4941-bd81-8a167e705aa8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 2, N''NEDP'', 1, N''ca2418a4-be76-44b7-972c-78e0f6dd63d3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 16, N''NEDP'', 1, N''eb24eeff-b9fb-43aa-bfc8-459d6c8908fa'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 102, N''NEDP'', 1, N''ddf33399-0253-46dd-bd57-c5c4ca4a343c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 72, N''NEDP'', 1, N''48513087-0eb7-4d84-8ee7-474fe38430fd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 70, N''NEDP'', 1, N''d973ff06-2eb6-4f7e-a305-e0a8d2000bd9'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 35, N''NEDP'', 1, N''541be6a2-6fd7-4810-9304-f089a9ec7ea8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 1, N''NEDP'', 1, N''58d6c557-250b-4731-8c27-381a63c1a419'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 4, N''NEDP'', 1, N''49195391-f442-4836-b926-a35c10be5a63'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7, N''NEDP'', 1, N''fc4749d6-54b5-4ab0-9d6c-7cdcfd0c3638'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 65, N''NEDP'', 1, N''fee9230d-7b9d-4ead-8413-a1da56bc6658'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 14, N''NEDP'', 1, N''81221c8d-c3b9-4358-89d8-5e28365c9ef2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 3, N''NEDP'', 1, N''76cd3f35-246c-4571-aa15-7e53789dd4f2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92024, N''NEDP'', 1, N''0958c0fd-bb64-44fa-87b6-75fb6d0d832c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92019, N''NEDP'', 1, N''a223ef36-3f10-4cb7-84af-c2a8ca0eab06'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92021, N''NEDP'', 1, N''0d5d6961-644f-4b0d-8406-259ee91b16cf'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92017, N''NEDP'', 1, N''468c8030-76c4-4a9f-81ec-af3c2714bdd6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92018, N''NEDP'', 1, N''06c551b9-1659-4426-854f-d6a8b6e15de8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 33, N''NEDP'', 1, N''ab49fe33-f6bd-43c1-a304-82cfa6f5eaec'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 107, N''NEDP'', 1, N''e4574b40-58fe-46dc-abdf-d2913ed2353c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 78, N''NEDP'', 1, N''c350450c-b600-4838-82fb-e9f126d84dbe'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92007, N''NEDP'', 1, N''44ec9622-6162-4c4c-b639-31f477670854'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92008, N''NEDP'', 1, N''7b87f72b-f106-4ae0-bb81-2cfff8514489'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 9, N''NEDP'', 1, N''43c10bfc-391b-49f1-a700-e106256b1091'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7509, N''NEDP'', 1, N''2c17eb03-170e-45d9-8004-d603228c68de'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7505, N''NEDP'', 1, N''8f311896-e612-4839-8e61-278f525b48d8'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7513, N''NEDP'', 1, N''c434a083-7bf6-4f5e-ae0d-5092e27c8201'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7514, N''NEDP'', 1, N''dbe9609f-63ca-41b9-ad9e-6bde5d808461'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7506, N''NEDP'', 1, N''81f58189-7cd7-4848-a4b9-4c83a2be2b04'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7510, N''NEDP'', 1, N''f094f42d-3025-4667-9b85-791f89130380'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 7500, N''NEDP'', 1, N''2540a8a0-0bc5-4b00-92dc-097d41ae5afd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 11, N''NEDF'', 1, N''453bd9c9-cced-42ea-85aa-0654f77a64ca'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 13, N''NEDP'', 1, N''cf8995c2-58ce-44ef-be48-59233153abbf'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 69, N''NEDP'', 1, N''94e99eaa-57bd-4cb7-b63d-cc131dcf2b04'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 114, N''NEDP'', 1, N''696cdd7c-d559-4665-819f-5ab917892af7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 8023, N''NEDP'', 1, N''1e92e7d3-5a9e-4133-a93a-e78dd5cbd426'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 62, N''NEDP'', 1, N''488adbfd-a1d7-4909-a07f-ff25b8961d67'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 8022, N''NEDP'', 1, N''fc137d31-cfa7-4c4a-9692-0f69949a76d6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 12, N''NEDP'', 1, N''d0940771-5308-4438-b74b-8747dd7280b1'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 20, N''NEDP'', 1, N''28e2f163-0178-4557-a0a1-51918c4b5223'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 68, N''NEDP'', 1, N''5d6a8a41-c6d6-485e-a7bf-79b19a76d2a5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 8031, N''NEDP'', 1, N''2d08c66d-df6f-4ea6-a5b7-edf71dbc4efa'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 73, N''NEDP'', 1, N''f7d4cfb7-1e09-484b-9742-5c09968cd397'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 1902, N''NEDP'', 1, N''79b49914-e475-4ea9-83d1-29acdf8308c1'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 109, N''NEDP'', 1, N''895eb2dd-39f6-476f-b5a3-7c3cbcdc75fd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92020, N''NEDP'', 1, N''3550bb0f-cef1-498d-a15e-fe96db0be534'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 32, N''NEDP'', 1, N''4f1bdd2d-c243-4fde-93ca-22d711b1bd7f'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 61, N''NEDP'', 1, N''7d342c27-7423-437e-9b33-b84f5dee676c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 27, N''NEDP'', 1, N''f5c15258-302f-495e-a9e4-0b1b4d254a68'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92025, N''NEDP'', 1, N''0779b34f-269e-47b9-9668-b9a8a0bb5afb'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 100, N''NEDP'', 1, N''245192d2-f5e0-4618-a6cd-451a4c24cb1c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 101, N''NEDP'', 1, N''fd128a96-e6cd-4965-aae5-267aea7b0b22'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 110, N''NEDP'', 1, N''8b6d27ce-cf4f-463e-a1be-eeaf0d280369'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 116, N''NEDP'', 1, N''169764e0-8308-49d4-8135-d57f867a8396'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 36, N''NEDP'', 1, N''a6bac06e-ae01-4f7a-b1f6-99e35386f5b6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 10, N''NEDP'', 1, N''dd8b3cc8-acda-4dee-a4e5-e76b8a11bc14'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 76, N''NEDP'', 1, N''50e603c8-1725-44ba-828e-b722d469ce92'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 17, N''NEDP'', 1, N''c0effd43-6efe-4376-b18c-167e53ff9cab'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92030, N''NEDP'', 1, N''155a17cc-5b01-4c50-b858-d5c10e5cf219'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 200, N''NEDP'', 1, N''4a630a6b-7231-4831-bfb6-599113de681e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 15, N''NEDP'', 1, N''3aac1473-4dbb-4f37-9b7e-0f9cf7f09004'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 115, N''NEDP'', 1, N''163354be-22d3-46ef-8731-4ae469a97107'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 108, N''NEDP'', 1, N''8150c378-48d4-4f09-8324-cb4e0066b3f7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 8, N''NEDP'', 1, N''432ef017-a3cf-4b1d-b388-2f0a282c6c3a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 66, N''NEDP'', 1, N''4bbf8da0-7f8c-41ba-be86-a0542f02b9e6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 71, N''NEDP'', 1, N''26b55c22-b66a-4156-9baa-c5f194cd62fe'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 92022, N''NEDP'', 1, N''eb9a0ba7-2182-435a-a4f3-d0b305c8110f'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''hqadm'', 74, N''EPIMHW'', 1, N''589915b4-7c3b-4b92-8708-c9a1b8b3e9c7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''p&c'', 10003, N''W'', 1, N''49764c7f-9764-4cab-831e-ed9728ce6f3c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5014, N''NEDPU'', 1, N''70990888-11ba-45dc-ab0e-c750c4ef73da'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 3016, N''NEDPU'', 1, N''e98d5548-9e63-416e-8501-51da4b89b943'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 60, N''NEDPU'', 1, N''cd93180a-c28b-4635-a118-70530f7eac92'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5018, N''NEDPU'', 1, N''ad8ec150-e756-47be-8078-baab5cf36e79'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5017, N''NEDPU'', 1, N''bef659cf-a901-4986-857f-1cbfcf6c6689'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5001, N''NEDPU'', 1, N''333e20f3-728d-467b-903a-3001f25b8085'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 10004, N''NEDPU'', 1, N''70945942-f465-40f0-8272-9f53653ce51c'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5002, N''NEDPU'', 1, N''10681821-9318-4796-8473-138a4015d338'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 8021, N''NEDPU'', 1, N''3fba2eff-9838-4af9-9c57-a8b49a3d6972'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5011, N''NEDPU'', 1, N''06760795-6781-46be-9397-c836ce1d1d2e'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5010, N''NEDPUI'', 1, N''cf4616d8-5e62-4bce-835a-9fde0a90fd54'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5015, N''NEDPU'', 1, N''2dedd9c0-7009-407d-8fb3-9f1b88b7c7db'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5003, N''NEDPU'', 1, N''4fec8158-cc75-4ca3-a29d-6c23b79196b3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5022, N''NEDPU'', 1, N''6802f34e-090c-478a-ac89-4ea556f90640'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7518, N''NEDPU'', 1, N''777f829f-ea7a-4cf5-80d5-46aaf3da4adb'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7519, N''NEDPU'', 1, N''4e1e6285-ad73-4a71-b8ff-ae508c29066a'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7511, N''NEDPU'', 1, N''e07ff082-f13e-49a9-919f-7ae2644e04c3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7503, N''NEDPU'', 1, N''4620688d-e76f-4784-bc9c-beea7f7eade6'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7512, N''NEDPU'', 1, N''462f8937-5595-402f-b162-12cea6c69394'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5030, N''NEDPU'', 1, N''a2b93648-7f18-490e-89a7-636876755cb0'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5004, N''NEDPUI'', 1, N''07091acf-3160-4309-bc84-e7ab2ecfffa1'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 10001, N''NEDPU'', 1, N''3b8a4af8-0fbb-4627-b880-886b2b601185'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 6001, N''NEDPU'', 1, N''d5dffceb-7468-45b3-af33-204b32d17214'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 6005, N''NEDPU'', 1, N''90deff82-d610-405b-81d2-45491d9f90e3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 6006, N''NEDPU'', 1, N''421bdd41-936e-49a8-90c3-b315bd295fbc'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 6007, N''NEDPU'', 1, N''f11f12d4-428f-4d00-b6b0-7c318a525587'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5005, N''NEDPUI'', 1, N''b5bf8a4e-2d9e-4c9b-8702-485a42dc8015'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 7517, N''NEDPU'', 1, N''b42cbafa-2bb6-4c67-8eff-e53ed1baff2d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 8018, N''NEDPU'', 1, N''56aae6d9-2efb-4b79-9958-43ca234601a5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 50, N''NEDPU'', 1, N''612c56ef-c551-4039-a3f5-2d96d34edf44'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 63, N''NEDPU'', 1, N''27c9e705-b870-42c4-ba6d-b51531ff79c7'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5006, N''NEDPUI'', 1, N''447a974f-c8fa-408e-b4a7-2d6defca0acd'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 8020, N''NEDPU'', 1, N''851a8dfd-063b-428b-9e34-1861dc0c27c4'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 52, N''NEDPU'', 1, N''2a716b97-1d38-408b-a605-5238406b8138'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 10000, N''NEDPU'', 1, N''b4a6be85-c3d6-4235-9c4a-96484e3b6f7d'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5020, N''NEDPU'', 1, N''77208bb4-76f9-4233-83e5-329ddb4ef4c5'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5016, N''NEDPU'', 1, N''62d19ad4-2e2c-4eec-9ab9-f7314a7aedc3'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5007, N''NEDPUG'', 1, N''4ef9fc96-3e6e-44f1-9bc6-b209d3c79ba2'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5013, N''NEDPU'', 1, N''7589f877-8f32-4846-a770-84b1ee18c991'')
INSERT [dbo].[aUserGroupRights] ([UsergroupID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (1, N''acc'', 5012, N''NEDPU'', 1, N''245a242a-a436-4f40-85c7-dd31c2c9c7af'')
/****** Object:  Table [dbo].[aUserGroupreportrights]    Script Date: 04/12/2012 15:18:14 ******/
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7027, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7026, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7025, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7024, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7023, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7022, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7020, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7019, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7018, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7017, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7016, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7015, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7014, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7011, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7010, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7009, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7008, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7007, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7006, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7054, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7051, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7013, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7012, N''Acc'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7005, N''P&C'', 1)
INSERT [dbo].[aUserGroupreportrights] ([userGroupid], [reportid], [modulecode], [Companyid]) VALUES (1, 7004, N''P&C'', 1)
/****** Object:  Table [dbo].[AUserMasterGridSettings]    Script Date: 04/12/2012 15:18:14 ******/
INSERT [dbo].[AUserMasterGridSettings] ([CompanyID], [UserID], [BackColor], [ForeColor], [GridColor], [HeaderColor], [FontName], [FontSize]) VALUES (1, 2, N''&H80000005'', N''&H80000008'', N''&H80000012'', N''&H8000000F'', N''MS Sans Serif'', 8)
/****** Object:  Table [dbo].[aUserRights]    Script Date: 04/12/2012 15:18:14 ******/
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 4, N''NEDP'', 1, N''5d09f7bf-29fc-4bcf-9304-cb307ba5e50f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7, N''NEDP'', 1, N''98b5b757-9ec0-4d6c-a059-23b6172bf2fb'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 65, N''NEDP'', 1, N''39bd8aa9-377a-4041-bdcd-e39d32c6ce3d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 14, N''NEDP'', 1, N''07770ae7-7ccc-48b7-88bf-d287a26ca2c4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 3, N''NEDP'', 1, N''ee2c25e2-5e59-4b09-9580-c9859882b2d6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92024, N''NEDP'', 1, N''8455b4ea-d839-44c4-b5b9-7fabbdae11b2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92019, N''NEDP'', 1, N''663dc166-a365-4139-8d8d-9b83a7ee1db7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92021, N''NEDP'', 1, N''cf0a2daf-34c6-4302-8d0e-b8a4fb5a9996'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92017, N''NEDP'', 1, N''ab985998-d6f7-4182-afdc-223179cab008'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92018, N''NEDP'', 1, N''810c2e0d-2f3a-4a00-856e-9230bb12f431'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 33, N''NEDP'', 1, N''8077d70e-545e-4b00-811e-44749368c5db'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 107, N''NEDP'', 1, N''b8fff728-a13a-468e-8374-ee0a90760ff7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 78, N''NEDP'', 1, N''90edefc7-18f3-46a7-b826-2c955334ea24'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92007, N''NEDP'', 1, N''f7d5dcf2-63d7-4150-9cb2-f9f0f8e2fd6a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92008, N''NEDP'', 1, N''6d000f65-5a12-42e5-a3ff-4ad049485b72'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 9, N''NEDP'', 1, N''e29cea99-875e-49cc-a868-1d26a7cdafcf'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7509, N''NEDP'', 1, N''53f1af0b-18fa-429b-90c1-6f554bd73302'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7505, N''NEDP'', 1, N''9b717053-7903-439a-8e5f-bffb1d9f6c0e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7513, N''NEDP'', 1, N''bc548258-1203-4cad-8c61-929a7f0ac702'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7514, N''NEDP'', 1, N''817b5bb3-4d78-4ad2-8814-8ab381dffefa'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7506, N''NEDP'', 1, N''ea688a81-75e2-4658-8fd7-72b44e54b841'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7510, N''NEDP'', 1, N''5c372b75-2654-40bd-a785-6c98fbc1b607'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 7500, N''NEDP'', 1, N''f95f4f6f-9257-4955-a643-844d46893db2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 11, N''NEDF'', 1, N''8643d803-d3f2-4add-a8b0-18fb0e6f6e67'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 13, N''NEDP'', 1, N''9bc6e3ba-2b3f-41c2-8ec3-27ef9c17f953'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 69, N''NEDP'', 1, N''748b232d-6135-47b3-9771-734d454604b8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 114, N''NEDP'', 1, N''98c3aaa4-81bf-45b1-96d3-d6b05766a3e3'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 8023, N''NEDP'', 1, N''1f811f1f-eda8-486c-8b27-df757a19bffb'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 62, N''NEDP'', 1, N''4d33e6be-f860-4d77-8e1f-54b28a739d39'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 8022, N''NEDP'', 1, N''db1b5876-e071-4071-86fb-fbe468c3296e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 12, N''NEDP'', 1, N''79d59767-e7e3-446b-8f2b-3fde17153829'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 20, N''NEDP'', 1, N''0b528574-b748-49df-9c5e-a9c64ec8b97d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 68, N''NEDP'', 1, N''d6b1c51d-e63b-4283-acdb-27f36e7e6a59'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 8031, N''NEDP'', 1, N''b6ca8803-57b6-4423-ae70-645dc02a6116'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 73, N''NEDP'', 1, N''bf13168b-96d3-48e5-b9d4-bd217b73b9bc'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 1902, N''NEDP'', 1, N''7c4716ef-0ac8-4904-b856-fe6b84aafe4a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 109, N''NEDP'', 1, N''d89e3af3-ceb2-4dcd-88dd-d22ac6a6ff9d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92020, N''NEDP'', 1, N''c2e9c8d6-1226-4f0e-9bec-dd0374d518be'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 32, N''NEDP'', 1, N''fbf3790b-d173-48fd-b397-50eb427f43c0'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 61, N''NEDP'', 1, N''d6c674ce-f62a-42d7-90e3-55ec9604a527'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 27, N''NEDP'', 1, N''4ac8953c-b7fb-4f30-a3d1-9f05fc9959e2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92025, N''NEDP'', 1, N''64a5d041-8aaf-4f81-a5e9-8277fd393451'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 100, N''NEDP'', 1, N''cf410433-f4a8-4a4d-9354-eb6097e644c7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 101, N''NEDP'', 1, N''5988a17e-7296-4bc5-84ab-8a0800916813'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 110, N''NEDP'', 1, N''c9364c85-2d24-479c-b4a3-b6415af55228'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 116, N''NEDP'', 1, N''9012dd0e-f004-417e-9b32-9635070cdd50'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 36, N''NEDP'', 1, N''55803c28-385b-4afd-b0ef-22fa28d6bf17'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 10, N''NEDP'', 1, N''6f8a4cf4-1434-4e79-ad80-7f0fdab68583'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 76, N''NEDP'', 1, N''f03ba8c7-1b09-4f9f-80e7-b5d36d12a7d6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 17, N''NEDP'', 1, N''015dca8a-bf41-4dbb-ac8d-abb06ea4de14'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92030, N''NEDP'', 1, N''7e0232ce-549b-41d9-8a5d-9877a8fb5115'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 200, N''NEDP'', 1, N''35b30ac7-dc16-42ac-b19e-5134c922cac5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 15, N''NEDP'', 1, N''e24c18cd-35f7-498f-85ce-d81f6cc2691f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 115, N''NEDP'', 1, N''1017f9e1-997f-4074-96c3-e9eeceae69ce'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 108, N''NEDP'', 1, N''ac1f666a-41df-4a7d-adf6-3bf2c410cb5c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 8, N''NEDP'', 1, N''2de83ee3-be80-40ed-98a3-f51d7b52c5da'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 66, N''NEDP'', 1, N''21e05df7-f053-4dbc-b3f2-ffa6c92bff72'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 71, N''NEDP'', 1, N''8f5d757c-2984-451e-9858-cb0efd662e4c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 92022, N''NEDP'', 1, N''c35619b5-dcf4-4e94-8b0d-b8f3edfbaaef'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 74, N''EPIMHW'', 1, N''70379fe1-ea8a-4620-bc64-e16227a0bdb7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 10003, N''W'', 1, N''4afa2572-bdfc-4ee5-97ee-c7ab216e1033'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5014, N''NEDPU'', 1, N''6a85f53c-e53d-4645-9a9c-263c4ad6c9b7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 3016, N''NEDPU'', 1, N''ade79615-8dba-4851-995a-a759345d7c43'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 60, N''NEDPU'', 1, N''08e4c550-548a-4500-b6d7-b9c6eb6c4cbd'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5018, N''NEDPU'', 1, N''35254f39-a4cb-46fc-b269-81fb355026d3'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5017, N''NEDPU'', 1, N''4573a3c2-9cb4-418e-9d16-6e4c2b654398'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5001, N''NEDPU'', 1, N''9d6a5f94-18be-4435-8f45-ba92c2af31a9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 10004, N''NEDPU'', 1, N''00c4ebed-7a0f-4080-bb78-54b163b9e31c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5002, N''NEDPU'', 1, N''708bfe86-0b8a-4b65-a2a5-f0f67820a2da'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 8021, N''NEDPU'', 1, N''826054d6-142e-4982-9fb8-c5fac0e74ca9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5011, N''NEDPU'', 1, N''37a9d5ba-2f0e-41f1-a720-e4900aadcf98'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5010, N''NEDPUI'', 1, N''afd277e1-fe42-4911-92fb-d96e45f6ab82'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5015, N''NEDPU'', 1, N''8ea38f13-1200-45ea-813c-de559fe5bfa9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5003, N''NEDPU'', 1, N''45ed472e-0c3e-4e01-8702-b78926d6d113'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5022, N''NEDPU'', 1, N''c6048a94-329f-4fed-80f4-c4ffd4aa3c63'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7518, N''NEDPU'', 1, N''0c6bb969-1851-41a8-a245-d571c41c9de4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7519, N''NEDPU'', 1, N''81d819c3-c1a2-4ad2-9c8c-bb3e1e19256c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7511, N''NEDPU'', 1, N''49b7f721-ad46-42f4-ac57-57103b2e2c40'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7503, N''NEDPU'', 1, N''9c316e4c-8a4d-43bb-bf41-1375a97d8ebe'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7512, N''NEDPU'', 1, N''2c804bb4-fd07-41fa-9143-88e29f8d1d6b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5030, N''NEDPU'', 1, N''4d3b877b-ab85-494d-9977-6bc32bb0a78d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5004, N''NEDPUI'', 1, N''9d74aa31-197e-496a-9ef5-918513f4e9a9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 10001, N''NEDPU'', 1, N''fb547dd6-a1fe-4e90-afb0-517b8bc8bea9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 6001, N''NEDPU'', 1, N''2ca7848a-de7f-48fa-97af-cf58f847572a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 6005, N''NEDPU'', 1, N''aae577f7-ad80-4dac-a376-bf727adf96d3'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 6006, N''NEDPU'', 1, N''7877ae3a-49c1-4bb0-987c-47b9f3434d83'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 6007, N''NEDPU'', 1, N''6b0261d9-bc51-42c1-902a-45ca357f7682'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5005, N''NEDPUI'', 1, N''0465efa4-43a5-435d-9eb9-028cccb1aee7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 7517, N''NEDPU'', 1, N''e332c959-37e8-4a5a-9efe-a553fdb0d24d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 8018, N''NEDPU'', 1, N''fc0e9c8e-ca0f-4a67-abb0-d7092291a7c4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 50, N''NEDPU'', 1, N''645c49e4-401d-43a6-baa5-d56dbb4061ef'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 63, N''NEDPU'', 1, N''7ea9a5ca-54b1-41dc-819e-92b5c581a2e1'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5006, N''NEDPUI'', 1, N''9a376f8a-4a2c-4f6b-92d4-5a29e2317ef2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 8020, N''NEDPU'', 1, N''85dd1d6b-7ddb-424c-a374-4822cf1b7951'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 52, N''NEDPU'', 1, N''177aabdc-bf29-4b55-8a7d-e0bccfdc348b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 10000, N''NEDPU'', 1, N''0af7801d-6898-441c-960b-7fbb26fbf744'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5020, N''NEDPU'', 1, N''3b881591-d3df-4bea-9548-d15c04445708'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5016, N''NEDPU'', 1, N''66cf0bee-f9f9-42f5-a396-85a7f62139b7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5007, N''NEDPUG'', 1, N''2b63cac6-9006-49de-8cc1-e098140ac811'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5013, N''NEDPU'', 1, N''4978a142-ddba-46c4-a3ac-c416a1167011'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 5012, N''NEDPU'', 1, N''af79668c-d004-4acb-87a0-9069f23c43af'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 8019, N''NEDPU'', 1, N''536fd774-a16c-4d71-84fa-b8ba1fec757c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''acc'', 22, N''NEDPU'', 1, N''4d64f5f0-3260-4cc8-aec5-ad8d6f363bb8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91028, N''NEDP'', 1, N''fc80a699-0b62-4fa5-9a89-71abcd753fce'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91035, N''NEDP'', 1, N''8ab6b151-dd88-4336-8351-75478980121a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90002, N''NEDP'', 1, N''9f7e5042-3a8a-4dcd-b04d-4cb5f9fce594'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91019, N''NEDP'', 1, N''a8d6056f-0328-4cff-b3fe-1e35d7ffbb86'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90019, N''NEDP'', 1, N''2ea3154d-9268-40ec-bffa-0dceb2549bb8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90010, N''NEDP'', 1, N''67e96263-447d-408b-9698-aae89090124c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90020, N''NEDP'', 1, N''699d2b17-c142-4259-b6fc-47d4e70bb85c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91034, N''NEDP'', 1, N''d2467531-225e-45bd-866d-43fcd0ccb078'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90016, N''NEDP'', 1, N''13a8dc64-0a03-41b1-a881-4c820c91661d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90017, N''NEDP'', 1, N''ca886865-36ff-4818-9792-b6143e87310f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91029, N''NEDP'', 1, N''3ea3d807-6caf-48ea-989e-a0037d6b4a03'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90003, N''NEDP'', 1, N''06bc7506-315c-49be-ab92-1b2643262f9f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 92000, N''NEDP'', 1, N''5e16c3c7-961a-441a-bf8d-36c9004a222f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90001, N''NEDP'', 1, N''2322c698-0c67-45d1-92fb-11abecbd64a6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91003, N''NEDP'', 1, N''7d434145-d77f-469d-bb10-92ae280bd52b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90008, N''NEDP'', 1, N''e7c97bd3-45df-4159-b722-9a269218f95b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91027, N''NEDP'', 1, N''e0bdf799-cc2f-4faf-822f-a25de885b49f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90009, N''NEDP'', 1, N''0b0570a1-d153-4fe8-b54f-530eb30eb077'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91030, N''NEDP'', 1, N''e730245b-5523-4bde-819c-0c9f64b2773a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90023, N''NEDP'', 1, N''4abc96cf-175e-4328-bcf9-d86ab104113f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 3000, N''NEDP'', 1, N''7f95ef75-042e-4d3b-a65b-c4134b71e417'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91025, N''NEDP'', 1, N''c75e1f35-ef37-42c4-9612-bf3c34ce5c3a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91031, N''NEDP'', 1, N''b942c604-fba3-42ea-a5e6-ab115bf3c827'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90018, N''NEDP'', 1, N''9e9824be-2ad1-4f50-9494-6f20cfaf0a8d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91017, N''NEDP'', 1, N''61b5bdc2-e354-4f7e-865b-6639a98229cd'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90015, N''NEDP'', 1, N''9e42962f-6e39-4a1d-9c5f-b4088d5ea10d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90007, N''NEDP'', 1, N''6ca34aba-759f-4f9f-a284-e7560a9d8e13'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91004, N''NEDP'', 1, N''718ce3fb-cf1c-472a-bdb7-6afd17a6dcab'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91032, N''NEDP'', 1, N''7f521d6d-c09c-475c-9abd-926ae9889fd5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90022, N''NEDP'', 1, N''e13ef7e6-4cb4-4051-ac6c-376f4289219a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91016, N''NEDP'', 1, N''84073d7a-7f95-40c4-b5c6-2934f4597364'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91018, N''NEDP'', 1, N''4250d5b3-d7c0-4f5f-a280-92da1a38cf12'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91005, N''NEDP'', 1, N''73c33587-503e-4b85-a048-e5d0a2093ee2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91006, N''NEDP'', 1, N''026a868b-a249-419f-9c63-8cc31eba012a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91020, N''NEDP'', 1, N''0262006b-fe25-430d-b9bb-419bca051501'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90006, N''NEDP'', 1, N''88885bfd-6d0d-49a4-9f47-2cf330d2bbf8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91026, N''NEDP'', 1, N''06288385-2d9c-472a-bc6d-bf7ed4b46d23'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91011, N''NEDP'', 1, N''be0b9828-92c5-45ea-af83-b481f613ad28'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90004, N''NEDP'', 1, N''8dda776c-4869-433c-802c-b97fdaa666ce'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91001, N''NEDP'', 1, N''fd4302bc-9935-4341-b7ac-69d4d44cbbfc'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90014, N''NEDP'', 1, N''3ce1204b-cb96-40d8-9ba9-9803e0b2c947'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91013, N''NEDP'', 1, N''fb4ff975-6f55-477d-89cd-dbe13da9ec5c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91007, N''NEDP'', 1, N''7bc1fed2-fdf7-4ab5-9537-277c65d9150a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91002, N''NEDP'', 1, N''9273ced2-8b9c-46cd-984b-817437b60dec'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91024, N''NEDP'', 1, N''3bc1ca2f-090e-441b-971c-1d69bfdc9201'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91037, N''NEDP'', 1, N''f7a5b8fc-f037-402b-94a0-465cc865656b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91038, N''NEDP'', 1, N''94f463d6-5152-4258-964f-ef43da0c69d0'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91010, N''NEDP'', 1, N''cb813b26-aa9c-4038-911d-958655f758e9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90012, N''NEDP'', 1, N''5c382ea3-7074-4350-8ff9-da6346f9e7ea'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91021, N''NEDP'', 1, N''69315105-db06-452f-9395-c60431d8649f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91033, N''NEDP'', 1, N''ce56d953-c016-41cf-a9c8-02bac33d63eb'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90021, N''NEDP'', 1, N''d9c47ad3-8ff3-4915-a40a-58a6894d8944'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91014, N''NEDP'', 1, N''b5a848cb-b289-4dfb-bbc5-3d9799188a3d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90005, N''NEDP'', 1, N''74919fb4-64e9-453a-b1ba-a512e859b2c4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91036, N''NEDP'', 1, N''78b3772c-6991-420e-a0ba-1551f7d4399f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90013, N''NEDP'', 1, N''e8777fba-563c-4430-b396-7b5357bba683'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 90011, N''NEDP'', 1, N''522625c5-470f-4b01-a748-e4f3356b03e4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91022, N''NEDP'', 1, N''44a3a92a-fd5d-473a-b234-e05abdffe41b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 5019, N''NEDP'', 1, N''da2a827d-1085-42d5-b5e8-88fcd7274afc'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''pay'', 91023, N''NEDP'', 1, N''4d587550-7132-4784-838c-ae3dc3713d81'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 2201, N''NEDP'', 1, N''b696d7b0-d7da-4a5c-8f1f-c0baebc9afb2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8010, N''NEDP'', 1, N''bf254a57-012a-46cb-b7d7-e2d4f4d54c9e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8005, N''NEDP'', 1, N''1af71ef9-c95f-41f8-be3b-72ad4c7c555a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8001, N''NEDP'', 1, N''1da8ed4a-6bc7-43e8-bd2f-6af7081890a5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8003, N''NEDP'', 1, N''caae3f83-caed-4e6a-bae5-e8a6b7448b45'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 2202, N''NEDP'', 1, N''d9332f30-b886-4c9f-a900-230558f0e63c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8004, N''NEDP'', 1, N''ad5b44dd-e57c-4416-87be-f7668a6c9f23'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''bgt'', 8002, N''NEDP'', 1, N''89b93ed9-97d0-4c03-b4ea-b337cf66422e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''admin'', 106, N''NEDP'', 1, N''08b50b51-1a59-41dc-93bd-b1a25f477948'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''admin'', 105, N''NEDP'', 1, N''4effc918-b841-4ca2-94aa-f419dd16a38c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''admin'', 103, N''NEDP'', 1, N''350074f5-48c9-4ee8-8c96-47d80473f3e8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''admin'', 104, N''NEDP'', 1, N''bcebd16a-1cd5-40c6-9ae9-01d7884e169f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6101, N''NEDS'', 1, N''1ce6b6d0-615f-499a-ac85-2714cedb9201'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6102, N''NEDS'', 1, N''6ffa42e8-c245-493c-b398-d2fea53532a0'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6103, N''NEDS'', 1, N''eff171a1-e9e3-4bd6-a2b2-0978ce300740'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6100, N''NEDS'', 1, N''1d6688a4-8a51-42cd-911f-9e0eabf1f638'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6113, N''NEDS'', 1, N''43624154-2bbb-4cc0-bf6b-b9ef37270e40'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6115, N''NEDS'', 1, N''ee90b848-f1b0-46ad-bd3e-45939b2b47c8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6107, N''NEDS'', 1, N''3ab36b07-a0a7-4491-9ab9-53739e951d5d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6111, N''NEDS'', 1, N''802d105f-4927-46fa-8ef8-665c4b98cf5f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6116, N''NEDS'', 1, N''3b9c485f-eecc-40d0-8e4b-eccbcb7a0031'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6104, N''NEDS'', 1, N''26c85564-a21a-44be-ba17-51ac4107c237'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6106, N''NEDS'', 1, N''d34cdecb-1341-48b2-ada7-de3f6a9af268'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6105, N''NEDS'', 1, N''970b1b3b-35ab-4457-a519-1e7aa0611cc4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6108, N''NEDS'', 1, N''c8b39f9b-7db5-4b09-a854-45fe78a60904'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6114, N''NEDS'', 1, N''232c4677-7bb6-4427-bed3-813d87db2d1e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''crm'', 6112, N''NEDS'', 1, N''c2d7876d-3852-4b97-9bd4-54b4cd7ddea2'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''lms'', 6201, N''NEDS'', 1, N''d3b47583-0d34-43e8-8b3f-3e02cfe425a6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''lms'', 6200, N''NEDS'', 1, N''96ee4b57-195b-4e28-8c05-c46c64651407'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 6, N''NEDP'', 1, N''c1e1b08d-cb4f-4b7b-a89d-6ab822f2e501'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 31, N''NEDP'', 1, N''aaaa46e6-b83f-4c7c-a17d-feaad88c0dc5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 40, N''NEDP'', 1, N''3b4739b0-4963-4a5d-b782-48d764425869'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 4001, N''NEDP'', 1, N''1eff182c-1138-425c-b2b6-7dbefba1b97a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 19, N''NEDP'', 1, N''a8c8c3b2-ccf6-483b-b01a-c88aaee0762b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 5, N''NEDP'', 1, N''d8ed9b70-5f5c-4fe1-ba17-6eef5ab98fd6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 5029, N''NEDPI'', 1, N''e9ea28ff-c450-4647-9ec5-dd02521b3a63'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 2512, N''NEDP'', 1, N''bed66e16-e266-4ecc-9248-5772eae59799'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''accp'', 26, N''NEDP'', 1, N''7b609301-31ea-4da7-865d-ce20d065b0a6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 51, N''NEPD'', 1, N''50efd2a1-6b1d-4342-9da5-4e03f3e7a341'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 6008, N''NEPD'', 1, N''0f40f26a-6269-47e3-bd2f-4194f41033b7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 53, N''NEPD'', 1, N''3562b043-708f-4edc-b8fb-ad11ef792d69'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 55, N''NEPD'', 1, N''47f24c52-f7a1-487d-abaf-f613b340a119'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 54, N''NEPD'', 1, N''432fcbe2-0bac-4a82-94f2-4b5947567bac'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 2012, N''NEPD'', 1, N''41024972-928d-4fd8-b226-106654032cac'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 56, N''NEPD'', 1, N''643e7744-a54f-420e-b01d-05a14d9e0d94'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 999, N''NEPD'', 1, N''7ff5c868-ac7a-4a30-a044-81b303b29452'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 2021, N''NEPD'', 1, N''0a2c8eea-a93d-481e-aca8-0170c95d363a'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 57, N''NEPD'', 1, N''52b0d0b0-3e1a-4fe3-a269-eebcbe5d6096'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''sacc'', 10006, N''NEPD'', 1, N''feef8141-5912-47c6-816a-f92c0d65b1fb'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2004, N''NEDPU'', 1, N''8d7292a2-74c7-4d8f-baae-ff99882201e1'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2006, N''NEDP'', 1, N''7566bd97-f2ea-47f8-9279-db7af62b7655'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2005, N''NEDP'', 1, N''c659152b-dc35-459d-b044-07c1fa241728'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2009, N''NEDP'', 1, N''d37317d2-5600-47fb-afef-f94597d6f4f5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8013, N''NEDP'', 1, N''256547c5-ff5e-40ad-af33-ce4c05ba55c4'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8012, N''NEDP'', 1, N''e873faae-8d8e-41f7-a362-aa5388270b84'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2007, N''NEDP'', 1, N''1c12527f-db50-4145-b20b-529e90b7e72d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2008, N''NEDP'', 1, N''3a01102d-5190-46ee-aa40-fc4939d276cf'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2003, N''NEDPU'', 1, N''b868028f-5994-4ff5-a57b-b2f313351cf6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8032, N''NEDP'', 1, N''c172279e-c317-4602-aff9-5db5479c131f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2027, N''NEDP'', 1, N''dff0a0ba-b1bc-4adb-96f1-23b461be17e8'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2013, N''NEDP'', 1, N''236b8a79-c060-4b4c-be00-1b3d6e92be63'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2028, N''NEDP'', 1, N''a5c0694e-e85b-44b0-8bea-5a21767b51e3'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8015, N''NEDP'', 1, N''361fb1f6-9853-4309-bee4-2d258b6bb71c'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8006, N''NEDP'', 1, N''04a1d7a9-045d-4747-9b38-46c989158606'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2010, N''NEDP'', 1, N''326ecd88-0c25-46e5-8af9-c5a94ee55416'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2513, N''NEDP'', 1, N''257ea0ad-bd4c-48ed-a5b1-140d2a1ac6da'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2011, N''NEDP'', 1, N''ca9274e5-0cec-4d34-9f67-b403b443ba36'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8017, N''NEDP'', 1, N''d3579e88-5eee-4725-8712-737c7fdfe0ea'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8014, N''NEDP'', 1, N''d9caa74f-15eb-430d-a82e-47f002755b8b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2514, N''NEDP'', 1, N''ead6641f-77f0-4cbe-8564-7002fd51a6b5'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8011, N''NEDP'', 1, N''8fc00a40-28b9-4994-876d-b97440676c72'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2001, N''NEDPAVC'', 1, N''e523dbdd-f407-41db-b92b-2b16508613df'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2022, N''NEDP'', 1, N''795afebf-548d-4798-8f8f-0b280e4970a9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2000, N''NEDPJ'', 1, N''1eb5df69-dcd5-4377-b177-7aefc25335ff'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2015, N''NEDPU'', 1, N''9b3a389a-cf26-4cb4-8e61-d6181f1911c3'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2002, N''NEDP'', 1, N''989c97e5-b7c1-4125-a0c8-6807076ac26e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2016, N''NEDP'', 1, N''a25e21fc-b6d3-4859-8dca-1c81da3bb38b'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2014, N''NEDP'', 1, N''fef48c81-12d5-4461-9988-0158886d47e9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2019, N''NEDP'', 1, N''6db7af54-912b-442a-ba1d-f45cebdc3b5e'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2029, N''NEDP'', 1, N''36c30abe-2920-48ca-ad54-885dc0150c54'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 8009, N''NEDP'', 1, N''f40cf4c4-3ee0-4f22-8908-7754c0d2b3d0'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 92032, N''NEDP'', 1, N''03c574ed-91d9-4f9c-9951-94f3fc772c91'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2030, N''NEDP'', 1, N''3626abbf-978a-4179-af18-258d3bcc31b9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''p&c'', 2018, N''EPIMHW'', 1, N''197291c3-99ac-434d-8af7-e763557a0630'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 112, N''NEDP'', 1, N''eeac547c-9188-446c-bb4d-562ca4515b22'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 8034, N''NEDP'', 1, N''cc8fd4ba-852c-4ff1-a592-c532d7df2e98'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 34, N''NEDP'', 1, N''7739c5bc-7d51-4371-bf09-8f4b1c93769f'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 67, N''NEDP'', 1, N''df0a88a4-522e-48db-a283-4021b677d2cb'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 75, N''NEDP'', 1, N''92c1b829-9be2-4044-865d-cfcfdc9268e6'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 30, N''NEDP'', 1, N''4c24a54e-6b34-45c7-a1ad-8f0ce6ccc2e9'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 77, N''NEDP'', 1, N''8a6e305f-0d5a-4c0e-90d4-f7da9e925f47'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 2, N''NEDP'', 1, N''bfadc8f6-8488-43a1-9021-89be878c18d7'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 16, N''NEDP'', 1, N''193879b5-c0ac-4eb2-9650-dc4b4a0fe872'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 102, N''NEDP'', 1, N''f0d82db4-36f6-4d71-8de7-1986fbbe4169'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 72, N''NEDP'', 1, N''3ad1d8fe-1b21-4c3d-94b9-7e610d187678'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 70, N''NEDP'', 1, N''e049980b-481c-4a76-81fb-e7ab205f510d'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 35, N''NEDP'', 1, N''2e661ad5-8b03-48aa-badc-af94cb7ee942'')
INSERT [dbo].[aUserRights] ([UserID], [ModuleCode], [InterfaceID], [FunctionRights], [CompanyID], [rowguid]) VALUES (2, N''hqadm'', 1, N''NEDP'', 1, N''09013f12-8327-4128-aae4-f0882561ce8c'')
end' 
END
GO
/****** Object:  View [dbo].[gmlevelthree]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelthree]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gmlevelthree    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[gmlevelthree] as
select gm.groupid, gm.parentgroupid, gm2.levelgm + 1 levelgm from agroupmaster gm,
gmleveltwo gm2
where gm.parentgroupid = gm2.groupid'
GO
/****** Object:  View [dbo].[vwshopstockout]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopstockout]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopstockout    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
--commnets   " 130803 added brand name venki
--Modified By :Nidheesh
--Modified on :16-09-09
--Comments : included the condition while stock is equal to itemreorderlevel
CREATE  view [dbo].[vwshopstockout] as
select stockout.itemid, stockout.itemcode, stockout.itemdescription, stockout.itemreorderlevel,
stockout.reorderquantity, stockout.shopid,stockout.categorynamedescription,
stockout.itemcategoryid, isnull(stockout.colorname,'''') colorname,
isnull(stockout.sizename,'''') sizename, stock,stockout.brand
from
(select d.itemid, itemcode, itemdescription, d.itemreorderlevel, d.reorderquantity, d.shopid,
ic.categorynamedescription, ic.itemcategoryid, isnull(c.colorname,'''') colorname, a.brand,
isnull(z.sizename,'''') sizename,  isnull(Stock,0) stock  from
aitem  a left outer join acolor c on
a.colorid=c.colorid left outer join asize z on a.sizeid=z.sizeid,
aShopItemDetail d left outer join vwinquiryshopstock ss on d.shopid = ss.shopid
and d.itemid = ss.itemid , aitemcategory ic where a.itemid=d.itemid and
a.itemcategoryid= ic.itemcategoryid ) stockout where stockout.itemreorderlevel>=stockout.stock'
GO
/****** Object:  View [dbo].[vwgodownstockitem]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownstockitem]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 11/12/02  06/07/2007
--Modified by   : leo  ,Shinu
--Comments  : v3
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies)),Removed moigodownstock and added  vwInquiryGodownstock
CREATE view [dbo].[vwgodownstockitem] as
select ''G'' as type, i.itemcategoryid, gsitemid as itemid,
convert(numeric(18,3), sum(gsstock)) as stock,
convert(numeric(18,3), sum(gsbadstock)) badstock from vwInquiryGodownstock gs, aitem i,
aitemcategory ic where gs.gsitemid = i.itemid and i.itemcategoryid = ic.itemcategoryid
group by i.itemcategoryid, gsitemid --having sum(gs.gsstock) > 0'
GO
/****** Object:  View [dbo].[vwsellingtotalstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsellingtotalstock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwsellingtotalstock    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on  : 13/12/02
--Modified by  : leo
--Comments  : v3
CREATE view [dbo].[vwsellingtotalstock] as
select v.itemcategoryid, v.itemid, convert(numeric(18,3), sum(v.stock)) stock,
convert(numeric(18,3), sum(v.badstock)) badstock  from
(select itemcategoryid,itemid, convert(numeric(18,3), stock) stock,
convert(numeric(18,3), badstock) badstock from vwshopstockitem
union all
select itemcategoryid,itemid, convert(numeric(18,3), stock) stock,
convert(numeric(18,3), badstock) badstock from vwgodownstockitem) v
group by v.itemcategoryid, v.itemid'
GO
/****** Object:  View [dbo].[vwSellingFixAtShops]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingFixAtShops]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified on  : 09/12/02
-- Modified by : leo
-- Comments : v3
---------------------------------------------------
-- Modified on  : 26/06/2003, 25/12/2003
-- Modified by  : Kishore, hariharan
-- Comments     : Added the checking ''aItemPackingDetail.Active = 1''
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--RefNo:01
-- Modified by          : Nidheesh P V
-- Modified on          : 24/02/2011
-- Comments             : check the condition segmentid is null
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwSellingFixAtShops] AS
select a.shopid, a.itemid,pd.packingtypeid, pd.packingtypename,
b.ItemCode, b.itemcategoryid,
vid.ItemDescription, a.currencyid, max(a.sellingPrice) sellingPrice,
max(a.WholesalePrice) WholesalePrice,
max(a.discountprice) discountprice
from losShopItemShipmentdetail a, aitem b,
vwItemDescription vid, apackingtype pd, aItemPackingDetail ipd
where a.itemid = b.itemid
and b.itemid = vid.itemid
and b.pricefixedatHQ = 0
and pd.packingtypeid = a.packingtypeid
and a.itemid = ipd.itemid
and a.packingtypeid = ipd.packingtypeid
and ipd.active = 1  and segmentid is null   --RefNo:01
group by a.shopid, b.itemcategoryid, a.itemid, b.itemcode,
vid.ItemDescription, pd.packingtypeid,
pd.packingtypename, a.currencyid
union all
select distinct a.shopid, a.itemid, pd.packingtypeid, pd.packingtypename,
i.itemcode , i.itemcategoryid, vi.itemdescription, null,
0 sellingprice, 0 wholesaleprice, 0 discountprice
from ashopitemdetail a,aitem i,
vwsellingtotalstock vw, vwitemdescription vi,
apackingtype pd, aitempackingdetail ipd
where vw.itemid = a.itemid
--and vw.stock > 0
and vi.itemid=ipd.itemid
and ipd.packingtypeid = pd.packingtypeid
and vw.itemcategoryid = i.itemcategoryid
and i.pricefixedathq = 0
and ipd.active = 1
and a.itemid not in (select b.itemid from losShopitemShipmentDetail b
where b.shopid = a.shopid
and b.packingtypeid = ipd.packingtypeid )
and a.itemid=i.itemid
and vi.itemid=a.itemid'
GO
/****** Object:  View [dbo].[vwshops]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshops]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshops    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshops] as
select ShopID, shopname,
case when activeshop =1 then ''yes''
else ''no'' end activeshop,
case when selected  = 1 then ''yes''
else ''no'' end selected,
case when truncatecheck  = 1 then ''yes''
else ''no'' end truncatecheck,
case when fifo =1 then ''yes''
else ''no'' end fifo,
case when dayclosed =1 then ''yes''
else ''no'' end dayclosed
from ashops'
GO
/****** Object:  View [dbo].[vwPurchaseOrderStatus]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderStatus]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Shinu
--Created Date :20-06-2007
--Purpose : For Purchase Order status report
CREATE View [dbo].[vwPurchaseOrderStatus] as
select pohpoid,pohpono ,pohpodate,pohdepartmentid,Vendorid,VendorName,ContainerDesc,CountryName,'''' VesselDes,StatusDate,Remarks
from loPurchaseOrderHeader,aHQPurchaseOrderStatus s,acontainermaster ac,acountrymaster cm,aVendorMaster av
where pohpoid=s.poid and s.countryid=cm.countryid and s.containerid=ac.containerid and pohvendorid=av.VendorID
and statustype=1 and pohtype=''P''  and pohCancel=0
union all
select pohpoid,pohpono ,pohpodate,pohdepartmentid,VendorID,VendorName,ContainerDesc,'''',VesselDes,StatusDate,Remarks
from loPurchaseOrderHeader,aHQPurchaseOrderStatus s,acontainermaster ac,aVesselMaster Vm,aVendorMaster av
where pohpoid=s.poid and s.Vesselid=Vm.Vesselid and s.containerid=ac.containerid and pohvendorid=av.VendorID
and statustype=0 and pohtype=''P'' and pohCancel=0
Union All
select pohpoid,pohpono ,pohpodate,pohdepartmentid,VendorID,VendorName,'''','''','''','''',''Bill Generated''
from loPurchaseOrderHeader,aVendorMaster av
where pohvendorid=av.VendorID and pohtype=''P'' and pohbillgenerated=1 and pohCancel=0
Union All
select pohpoid,pohpono ,pohpodate,pohdepartmentid,VendorID,VendorName,'''','''','''','''',''PO Cancelled'' + ''  ''+ pohcancelRemarks
from loPurchaseOrderHeader,aVendorMaster av
where pohvendorid=av.VendorID and pohtype=''P'' and pohCancel=1'
GO
/****** Object:  View [dbo].[vwPurchaseOrderReportHdr]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderReportHdr]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwPurchaseOrderReportHdr] AS
	SELECT PoHdr.pohPoid,PoHdr.pohDepartmentid,PS.CompanyId,PS.ReportLogo
	FROM lopurchaseorderheader PoHdr,aPackageSettings PS'
GO
/****** Object:  View [dbo].[vwNonControlsGroupAccounts]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNonControlsGroupAccounts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 17/11/2001 9:21:13 PM ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwNonControlsGroupAccounts    Script Date: 09/03/2001 02:32:26 ******/
CREATE view [dbo].[vwNonControlsGroupAccounts] as
select agroupmaster.* from agroupmaster,asettings where groupid<>isnull(FixedAssetGroupID,0) and
groupid <>isnull(CashGroupID,0) and groupid<>isnull(BankGroupID,0) and
groupid<>isnull(TradeDebtorAcID,0) and groupid<>isnull(TradeCreditorAcID,0) and
groupid<>isnull(SalesGroupID,0) and groupid<>isnull(PurchaseGroupID,0) and
agroupmaster.companyid=asettings.companyid'
GO
/****** Object:  View [dbo].[vwNonControlAccounts]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNonControlAccounts]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- modified on  : 12/01/03
-- modified by  : leo
-------------------------------------------------------------------------------------------
-- Modified on  : 28/08/2003
-- Modified by  : Kishore
-- Comments     : Replaced the equi join to aPackageSettings
--                with inner query for better performance
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwNonControlAccounts] AS
select a.CompanyId, a.AccountId,
isnull(da.daDepartmentId,0) daDepartmentId
from aAccountMaster a
left outer join aDeptAccounts da
on a.AccountId = da.daAccountId
and a.CompanyId = da.daCompanyId
where a.AccountId <> (Select isnull(p.CustomsAccId, 0)
			From aPackageSettings p
			Where p.CompanyId = a.CompanyId)'
GO
/****** Object:  View [dbo].[vwNewJournalDetails_GST]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNewJournalDetails_GST]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwNewJournalDetails_GST] AS
-- Last Modified on  : 22-11-2011
---Jyothish . S R
-- Comments  : Separate qyery added credit invoice
SELECT jd.companyid, jd.journalid,
case when jd.journalcredit =1 then ''Cr''
when jd.journalcredit =0 then ''Dr'' end as Posting,
case when jd.accountid is not null then acc.accountdesc
when jd.customerid is not null then c.customername
when jd.vendorid is not null then v.vendorname end as particulars,
jd.PostGroup, jd.JournalCredit
FROM moajournaldetails jd left outer join aaccountmaster acc
ON jd.companyid = acc.companyid and jd.accountid = acc.accountid
LEFT OUTER JOIN avendormaster v ON jd.companyid = v.companyid
AND  jd.vendorid = v.vendorid LEFT OUTER JOIN acustomermaster c
ON jd.companyid = c.companyid
AND jd.customerid = c.customerid, moajournalheader jh
WHERE jh.companyid = jd.companyid
AND jh.journalid = jd.journalid
AND jh.cancel = 0
AND jd.PostGroup IS NOT NULL and TYPE = ''SCI''  and PostGroup in (1,2) and jd.journalcredit =0
union
SELECT jd.companyid, jd.journalid,
case when jd.journalcredit =1 then ''Cr''
when jd.journalcredit =0 then ''Dr'' end as Posting,
case when jd.accountid is not null then acc.accountdesc
when jd.customerid is not null then c.customername
when jd.vendorid is not null then v.vendorname end as particulars,
jd.PostGroup, jd.JournalCredit
FROM moajournaldetails jd left outer join aaccountmaster acc
ON jd.companyid = acc.companyid and jd.accountid = acc.accountid
LEFT OUTER JOIN avendormaster v ON jd.companyid = v.companyid
AND  jd.vendorid = v.vendorid LEFT OUTER JOIN acustomermaster c
ON jd.companyid = c.companyid
AND jd.customerid = c.customerid, moajournalheader jh
WHERE jh.companyid = jd.companyid
AND jh.journalid = jd.journalid
AND jh.cancel = 0
AND jd.PostGroup IS NOT NULL and TYPE = ''POSGRN''  and PostGroup in (1) and jd.journalcredit =1'
GO
/****** Object:  View [dbo].[vwNewJournalDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwNewJournalDetails]'))
EXEC dbo.sp_executesql @statement = N'
CREATE  VIEW [dbo].[vwNewJournalDetails] AS
-- Last Modified on  : 22-11-2011,24-11-2011
---Jyothish . S R
-- Comments  : Separate qyery added credit invoice
SELECT jd.companyid, jd.journalid,
case when jd.journalcredit =1 then ''Cr''
when jd.journalcredit =0 then ''Dr'' end as Posting,
case when jd.accountid is not null then acc.accountdesc
when jd.customerid is not null then c.customername
when jd.vendorid is not null then v.vendorname end as particulars,
jd.PostGroup, jd.JournalCredit
FROM moajournaldetails jd left outer join aaccountmaster acc
ON jd.companyid = acc.companyid and jd.accountid = acc.accountid
LEFT OUTER JOIN avendormaster v ON jd.companyid = v.companyid
AND  jd.vendorid = v.vendorid LEFT OUTER JOIN acustomermaster c
ON jd.companyid = c.companyid
AND jd.customerid = c.customerid, moajournalheader jh
WHERE jh.companyid = jd.companyid
AND jh.journalid = jd.journalid
AND jh.cancel = 0 and  TYPE <> ''SCI''  and TYPE<>''POSGRN''
AND jd.PostGroup IS NOT NULL
union all
SELECT jd.companyid, jd.journalid,
case when jd.journalcredit =1 then ''Cr''
when jd.journalcredit =0 then ''Dr'' end as Posting,
case when jd.accountid is not null then acc.accountdesc
when jd.customerid is not null then c.customername
when jd.vendorid is not null then v.vendorname end as particulars,
jd.PostGroup, jd.JournalCredit
FROM moajournaldetails jd left outer join aaccountmaster acc
ON jd.companyid = acc.companyid and jd.accountid = acc.accountid
LEFT OUTER JOIN avendormaster v ON jd.companyid = v.companyid
AND  jd.vendorid = v.vendorid LEFT OUTER JOIN acustomermaster c
ON jd.companyid = c.companyid
AND jd.customerid = c.customerid, moajournalheader jh
WHERE jh.companyid = jd.companyid
AND jh.journalid = jd.journalid
AND jh.cancel = 0 and  TYPE in (''SCI'',''POSGRN'')
AND jd.PostGroup IS NOT NULL  and isnull(jd.accountid,0) not in(select TaxAccountId from aTaxCategoryMaster )'
GO
/****** Object:  View [dbo].[vwReceiptDetailsCredit]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptDetailsCredit]'))
EXEC dbo.sp_executesql @statement = N'
create  View [dbo].[vwReceiptDetailsCredit]
as
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 15/07/2008
-- Created by      : Jyothish
-- Comments        :
-------------------------------------------------------------------------------------------------------------------------
-- Modified on      :
-- Modified by      :
-- Comments         :
-------------------------------------------------------------------------------------------------------------------------
select rcd.CompanyID ,rcd.ReceiptID,acc.accountId,acc.AccountDesc,rcd.Amount from ReceiptVoucherCreditDetails rcd inner join aaccountMaster acc
on rcd.companyid =  acc.companyid and rcd.AccountID=acc.AccountID'
GO
/****** Object:  View [dbo].[vwContraCheckList]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwContraCheckList]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 28/12/2002
-- Modified by 		: dheena
-- COMMENTS		: add deparmentid
-------------------------------------------------------------------------------
-- Modified on          : 29/08/2003
-- Modified by          : Kishore
-- Comments             : Added UpdateTime field for check list report
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwContraCheckList] AS
select ContraID, c.CompanyID, ContraNo, ContraDate,
case when contratype=''wdw'' then "WithDrawel"
when contratype=''wdd'' then "Deposit" when contratype=''ibt'' then "Inter Bank Transfer" end
Type, facc.accountdesc frombank, tacc.accountdesc tobank,
contraamount, remarks, cancelled,
posted, exchangerate,dm.departmentname,
depexrate, c.departmentid, c.UpdateTime
from contra c left outer join aaccountmaster facc
on c.companyid = facc.companyid
and c.fromaccountid = facc.accountid
left outer join aaccountmaster tacc
on c.companyid = tacc.companyid
and c.toaccountid = tacc.accountid, adepartmentmaster dm
where c.companyid = dm.companyid
and c.departmentid = dm.departmentid'
GO
/****** Object:  View [dbo].[vwMergeCompleteDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMergeCompleteDetails]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------
-- Created by 	: Kishore
-- Created on   : 23/08/2003
-- Comments     : Taken from v2 for Item merging
----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwMergeCompleteDetails] AS
select lgdGodownID LocationID, GodownName LocationName,
mghId, mghNo, MghDate, lgdItemID, mghItemId,
mghItemCostprice, mghOldCostPrice, mgdCostPrice,
i1.ItemCode lgdItemCode, vw1.ItemDescription lgdItemDescription, u1.UnitCode lgdUnitCode,
i2.ItemCode mghItemCode, vw2.ItemDescription mghItemDescription, u2.UnitCode mghUnitCode,
mghCancelled, lgsdQty Quantity
from ahqMergingHeader, LoiMergeHeader, LoiMergeDetails,
agodown, ahqMergingDetails, aItem i1, aItem i2,
vwItemDescription vw1, vwItemDescription vw2, aUnit u1, aUnit u2
where lghRefMergeid = mghId
and lghCompanyId = mghCompanyId
and lghID = lgdId
and lghCompanyId = lgdCompanyId
and lghGodownId = lgdGodownid
and lghGodownId = GodownID
and mghId = mgdId
and mghCompanyid = mgdCompanyId
and lgdItemId = mgdItemId
and lgdItemId = i1.ItemId
and i1.ItemId = vw1.ItemId
and i1.UnitsId = u1.UnitId
and mghItemId = i2.ItemId
and i2.ItemId = vw2.ItemId
and i2.UnitsId = u2.UnitId
and lghCancelled = 0
and lghTransFinished = 1
union all
select lsdShopid LocationID, ShopName LocationName, mghId,
mghNo, MghDate, lsdItemID, mghItemid, mghItemCostprice,
mghOldCostPrice, mgdCostPrice,
i1.ItemCode lgdItemCode, vw1.ItemDescription lgdItemDescription, u1.UnitCode lgdUnitCode,
i2.ItemCode mghItemCode, vw2.ItemDescription mghItemDescription, u2.UnitCode mghUnitCode,
mghCancelled, lsdQty Quantity
from ahqMergingHeader, LosMergeHeader, LosMergeDetails, aShops,
ahqMergingDetails, aItem i1, aItem i2, vwItemDescription vw1, vwItemDescription vw2,
aUnit u1, aUnit u2
where lshRefMergeid = mghId
and lshCompanyId = mghCompanyId
and lshID = lsdId
and lshCompanyId = lsdCompanyId
and lshShopId	= lsdShopid
and lshCancelled = 0
and lshTransFinished = 1
and lshShopid = shopid
and lsdItemid = mgdItemid
and lsdItemId = i1.ItemId
and i1.ItemId = vw1.ItemId
and i1.UnitsId = u1.UnitId
and mghItemId = i2.ItemId
and i2.ItemId = vw2.ItemId
and i2.UnitsId = u2.UnitId
---------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwBudgetAllocationDetails]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetAllocationDetails]'))
EXEC dbo.sp_executesql @statement = N'
--Created By	: Hariharan R
--Created Date	: 02/01/2003
--For budget allocation details
CREATE view [dbo].[vwBudgetAllocationDetails] as
select bahCompanyID, bahBudgetAllocID, BudgetCode, BudgetHead, bahBudgetNo, bahBudgetDate,
bahFromdate, bahToDate,
bahBudgetPanel, bahReviewPanel, bahReviewDate, bahSanctionedBy, bahSanctionedDate,
bahRemarks, badfromdate budgetfromdate, badtodate budgettodate, badamount, baddetailid,
BudgetID from BudgetMaster bm, BudgetAllocationHeader bal, BudgetAllocationDetail bdt where
bal.bahcompanyid = badCompanyID and bal.bahBudgetAllocID = bdt.badBudgetAllocID and
bdt.badBudgetHeadID = bm.BudgetID and bdt.badcompanyid = bm.companyid and bal.bahcancelled=0'
GO
/****** Object:  View [dbo].[vwpcpaymentsDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpcpaymentsDetails]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwpcpaymentsDetails] as
select vwh.* ,vwd.accountDesc as DetailAccountDec,vwd.pdExRate,vwd.pdamount from vwpcpaymentvoucherdetails vwd, vwPCPaymentCheckList vwh where
vwh.phpaymentID=vwd.pdPaymentID and vwh.phCompanyId=vwd.pdCompanyID and phcancel=0'
GO
/****** Object:  View [dbo].[vwhpfeePaymentdetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpfeePaymentdetails]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by            Prasanth Joseph
Created For           To HP FeePaymentRepaort
Created on            23-01-2007
Modified on
Modified by
*/
CREATE view [dbo].[vwhpfeePaymentdetails] as
select vwh.* ,vwd.accountDesc as DetailAccountDec,vwd.hpdExRate,vwd.hpdamount,vwd.Feename,vwd.IRFrameNo from vwHPFeePaymentVoucherdetails vwd, vwHPFeePaymentCheckList vwh where
vwh.hphpaymentID=vwd.hpdPaymentID and vwh.hphCompanyId=vwd.hpdCompanyID and hphcancel=0'
GO
/****** Object:  View [dbo].[vwHPinvoices]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPinvoices]'))
EXEC dbo.sp_executesql @statement = N'
/*
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 [dbo].[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
/****** Object:  View [dbo].[vwBudget]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudget]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwBudget    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwBudget    Script Date: 14/09/2002 12:48:04 AM ******/
/****** Object:  View dbo.vwBudget    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwBudget    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.vwBudget    Script Date: 17/11/2001 9:21:18 PM ******/
/****** Object:  View dbo.vwBudget    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwBudget    Script Date: 09/03/2001 02:32:26 ******/
CREATE view [dbo].[vwBudget] as
select acc.*, jd.departmentid, jd.JournalDetailID, jd.journalid, jd.journalcredit,
jd.customerid, jd.vendorid, jd.amount ,gm.accounttype
from agroupmaster gm, aaccountmaster acc
left outer join MOajournaldetails jd on (acc.accountid = jd.accountid and
acc.companyid = jd.companyid)
left outer join MOajournalheader jh on jd.companyid= jh.companyid and
jd.journalid = jh.journalid
where gm.companyid = acc.companyid and acc.groupid = gm.groupid and acc.budgetamount > 0'
GO
/****** Object:  View [dbo].[vwbillvendorcurrency]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillvendorcurrency]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 17/11/2001 9:21:18 PM ******/
/****** Object:  View dbo.vwbillvendorcurrency    Script Date: 16/06/2001 15:36:30 ******/
CREATE view [dbo].[vwbillvendorcurrency] as
select b.companyid, b.billsid, v.vendorid, v.currencyid, b.ExchangeRate
from bills b, avendormaster v
where b.companyid = v.companyid and b.vendorid = v.vendorid'
GO
/****** Object:  StoredProcedure [dbo].[spSalesAndCostValue]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesAndCostValue]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by   : Kishore
-- Created on  : 12/06/2003
-- Comments  : Created from view vwSalesAndCostValue
--                        (On comparison with v2)
--------------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 02/01/2004
-- Comments             : Added intDepartmentId parameter
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSalesAndCostValue] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@strBrand as varchar(100),
@strCategoryId as varchar(250),
@intDepartmentId as int = 0) AS
Begin
declare @strQry as nvarchar(2000)
-- create temporary table to hold sub depts names
Create table #SubDepts1 (DepartmentId int primary key)
-- get sub departments
insert into #SubDepts1 exec spSelectAllSubDepartments @intDepartmentId, 1
set @strQry = N''
select yearsale.yearname, ai.itemcategoryid,
ic.CategoryNameDescription,
sum(yearsale.quantity) totqty,
sum(yearsale.salesvalitem) salesvalcate,
sum(yearsale.dSalesvalitem) dsalesvalcate,
sum(yearsale.csalesvalitem) csalesvalcate,
cast(sum(yearsale.quantity)as varchar) +
space(20-len(cast(sum(yearsale.quantity)as varchar)))+'''' | ''''+
cast(sum(yearsale.salesvalitem) as varchar)+
space(20-len(cast(sum(yearsale.salesvalitem) as varchar))) qtysales,
sum(yearsale.costvalitem) costvalcate,
sum(yearsale.dcostvalitem) dcostvalcate,
sum(yearsale.ccostvalitem) ccostvalcate
from aitem ai,
(select year(poshbilldate) yearname, posdItemId,
sum(amount) SalesValItem,
sum(damount) dSalesValItem,
sum(cAmount) cSalesValItem,
sum(posdquantity) Quantity, poshShopId,
sum(posdquantity * costprice) CostValItem,
sum(posdquantity * ccostprice) cCostValItem,
sum(posdquantity * dcostprice) dCostValItem
from vwshopitemsales
where poshbilldate >='''''' + @strfromdate + '''''' and  poshbilldate <='''''' + @strtodate + ''''''
group by  poshshopid, posditemid, year(poshbilldate), poshbilldate) yearsale,
aitemcategory ic, aShops s
where ai.itemcategoryid = ic.ItemCategoryID
and ai.itemid = yearsale.posditemid
and YearSale.poshShopId = s.ShopId''
if @intDepartmentId <> 0
Begin
Set @strQry = @strQry + '' and s.DepartmentId IN (Select DepartmentId from #SubDepts1)''
End
if (ltrim(rtrim(@strbrand)) <> '''')
Begin
set @strQry = @strQry + N'' and ai.brand ='''''' + @strbrand +''''''''
End
if (ltrim(rtrim(@strcategoryid)) <> '''')
Begin
set @strQry = @strQry + N'' and ai.itemcategoryid in('' + @strcategoryid + '')''
End
set @strQry = @strQry + N''  group by yearsale.yearname, ai.itemcategoryid,ic.CategoryNameDescription''
--print @strQry
exec sp_executesql @strQry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_GetShopItemPrice]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GetShopItemPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH P V
--CREATED ON : 01/08/2011
--COMMENTES : TO GET SHOP ITEM DETAILS INCLUDING PRICE LIST(CAN MODIFY FOR MORE DETAILS)
--MODIFIED AREA : RPTITEMPRICELIST
----------------------------------------------------------------------
--REF.NO:1
--MODIFIED BY : AADYAKUMAR.D.V
--MODIFIED ON : 17/04/2012
--COMMENTES : FILTER ITEMS WITH SEGMENT PREICE
--spMag_GetShopItemPrice 1,1,2,'''',0,'''',0,0,1
CREATE proc [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)
as
(
select asd.ShopID,s.shopname,asd.ItemID,ItemCode,vsd.itemdescri,Part_code,vsd.brand,vsd.PackingTypeName,ssd.PackingTypeid,
convert(numeric(18,2),(vsd.ItemRate*vsd.Quantity)) as costprice,ssd.sellingPrice,ssd.WholesalePrice,ssd.DiscountPrice,cm.Symbol,
row_number()over(partition by ssd.PackingTypeid,ssd.itemid,asd.ShopID order by ssd.shopid desc) as selectorder
FROM
ashopitemdetail asd
INNER JOIN vwShopItemStockitemsItemDtls vsd ON asd.itemid = vsd.ItemID
AND (asd.shopid=@IntShopId OR @IntShopId=0) AND (ItemCategoryID in (@strItemCate) OR @strItemCate='''')
AND (vsd.ItemID=@IntItemID OR @IntItemID=0) AND (brand in (@strBrand) or @strBrand='''') and ((@Intactive=0 and 0=0) or (@Intactive=1 and vsd.active=1))
INNER JOIN losShopItemShipmentDetail ssd ON ssd.itemid=asd.itemid AND ssd.PackingTypeid=vsd.packingtypeid AND companyid=@IntCompId
AND ((ssd.shopid is null AND 0=0) OR (ssd.shopid is not null AND ssd.shopid=asd.shopid))
and ( ssd.segmentid = @IntSegmentid or @IntSegmentid=0 ) --REF.NO:1
INNER JOIN acurrencymaster cm on cm.currencyid=ssd.currencyid
INNER JOIN  aShops s ON asd.shopid = s.ShopID
LEFT OUTER JOIN vwInquiryShopStock vs ON  @IntStock=1 and vs.shopid=asd.shopid and vs.itemid=asd.itemid and vs.stock>0
)
select * from cteShopItems where selectORder=1 ORder by shopname
SET NOCOUNT OFF
END
-------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTargetAchievement]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTargetAchievement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Version	: MV3
--Done By	: Nishad modified by Santhosh on 02042003
--Done on	: 13.11.02
--Purpose	: This Sp Calculates the Acual usage of Amounts
--		  Allocated for the Budget Period
--mODIFIED BY	: Hariharan
--Modified Date : 28/09/2003
CREATE  Procedure [dbo].[spTargetAchievement]
	@intTargetFixationID as int,
	@intcompanyid as int,
	@ToDatePassed as varchar(50) ,@strexrate as varchar (250)
	
	As
	
	set nocount on
	-- Declarations
	declare @maxdetailid as int,
	@TargetHeadID as int,
	 	@AccountID as int,
	 	@DepartmentID as int,
		@NewCredAmount as numeric(18,2),
		@NewDebAmount as numeric(18,2),
		@intCount as int,
		@dtfromdate as datetime,
		@dttodate as datetime,
		@DetailCount as int,
@amt as numeric(18,2),
		@MaxDetailIDforSecond as int,
		@targetcurrencyid as int,
		@numaccamt as numeric (18,2)
	set @amt=0
	-- Create Temporary Table
	create table #temp1 (
	DetailID int,
		TargetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2) )
	create table #temp2 (	DetailID int,
				AccountID int,
		             	DepartmentID int)
	
	create table #temp3 (
	DetailID int,
		TargetHeadID int,
	        FromDate  datetime,
	ToDate datetime,
		Amount numeric(18,2))
	-- Select The Allocated Details from the Budget Allocation Details
	insert into #temp1
	select tfdDetailID,tfdTargetID,tfdFromDate,tfdToDate ,0.0
	from TargetFixationDetail
	where tfdCompanyId=@intcompanyid and
	tfdFixationID= @intTargetFixationID order by tfdDetailID
	select @intcount=count(*) from #temp1
	
	while @intcount <>0
		begin
	-- Select the Max DetailID from the Temp1
		select @maxdetailid= max(DetailID) from #temp1
		-- Select BudgetHeadID,fromDate,Todate from the Temp1 Table
	Select @TargetHeadID=TargetHeadID, @dtfromdate = fromdate,
		@dttodate = todate from #temp1 where DetailID= @maxDetailID     		
		select @targetcurrencyid=tarcurid from TargetMaster where TargetID=@TargetHeadID
		-- Change the ToDate with Respect to Actual As On Date
		--if @dttodate > @ToDatePassed
			-- @dttodate = @ToDatePassed
		-- Delete Data from the Temp2 table if some data exists
		delete from #temp2
		--To Insert into The Temp2 from the BudgetAccounts Link for the BudgetHead
		Insert #temp2
		Select tacdetailid, tacAccountID,tacDepartmentID from TargetAccountsLink where
		tacCompanyId=@intcompanyid and tacTargetID = @TargetHeadID
		
		select @DetailCount=count(*) from #temp2   -- Select the Check Count
	 	while @DetailCount <>0
		 	begin
		  	-- Select the Max DetailID from the Second Table to Check for the Amount
		  	select @MaxDetailIDforSecond= max(DetailID) from #temp2
		  	select @AccountID=AccountId from #temp2 where detailID=@MaxDetailIDforSecond
		  	select @DepartmentID=isnull(DepartmentID,0) from #temp2 where detailID=@MaxDetailIDforSecond
		
			--Print 	@dtFromDAte
			--print	@dtToDate
			--print	@AccountID
			--print	@DepartmentID
		  	-- Select Amount from the Journal Header and Journal Details
		  	if @DepartmentID > 0
				Begin
				select @NewCredAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
				where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
				moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
				And moaJournaldetails.DepartmentID=@DepartmentID And
				moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
				>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
				and JournalCredit = 1
				select @NewDebAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
				where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
				moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
				And moaJournaldetails.DepartmentID=@DepartmentID And
				moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
				>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate	
				and JournalCredit = 0
				End
		  	else
				Begin
				Select @NewCredAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
				where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
				moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
				And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
				>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate
				and JournalCredit = 1
				Select @NewDebAmount = isnull(Sum(isnull(actualAmount,0)),0.0) from moaJournalHeader, moaJournalDetails
				where moaJournalHeader.JournalID=moaJournalDetails.JournalID And
				moaJournalHeader.Cancel=0 And moajournaldetails.CompanyID= @intCompanyID
				And moajournaldetails.AccountID=@AccountID and moaJournalHeader.journaldate
				>= @dtfromdate and moaJournalHeader.journaldate <=@dttodate 	
				and JournalCredit = 0
				End
		  	-- To Insert into Temp3 Table with the Selected Values			
		  	--Insert into #temp3
		 	-- Select * from #temp1 where detailid = @maxdetailid
		 	-- to Update the Temp Table with the New Amount	
		  	--update #temp3 set Amount = isnull(amount,0.0) + @NewCredAmount where detailid = @maxdetailid
	        	set @NewCredAmount = @NewCredAmount - @NewDebAmount
		  	-- Delete MaxID from the TempTable2 to take the Next Max DetailID
		  	delete from #temp2 where DetailID= @MaxDetailIDforSecond
			exec spConvertequiamounttemp @AccountID, ''a'', @targetcurrencyid, ''m'', @strexrate,
			@NewCredAmount,@numaccamt  output
					
		  	-- Set the Count from the Temp2
		  	select  @DetailCount=count(*) from #temp2
--set @amt=@amt+@NewCredAmount
			set @amt=@amt+@numaccamt
			end
		Insert into #temp3
		Select * from #temp1 where detailid = @maxdetailid
		-- to Update the Temp Table with the New Amount	
		update #temp3 set Amount = isnull(amount,0.0) + @amt where detailid = @maxdetailid
		-- MaxDetailID row from temp1 to get the next max DetailID row
	  	delete from #temp1 where detailID = @maxdetailid
		-- To get the Row Count from the Temp1 Table
		select @intcount=count(*) from #temp1
		SET @amt = 0.0
	        end
	drop table #temp2
	--To Select the resultant rows from the temp3 table
	select  DetailID,TargetHeadID,FromDate,ToDate,Amount from #temp3 order by TargetHeadID,DetailID
	set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GeneratePosBill]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GeneratePosBill]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spMagnolia_GeneratePosBill 8,3
------------------------------------------------------------
--CREATED BY: Nidheesh
--CREATED ON: 06-04-2011
--COMMENTS: TO GENERATE THE POS BILLID,BILLNO FOR ALL SHOPS
--THE LOGIC TO GENERATE BILLID,BILLNO IS DONE AS LIKE IN THE FRONT END CODE.
------------------------------------------------------------
-- RefNo.1
-- Modified By : Bijesh.B
-- Modified on : 09-08-2011
-- Ticket id   : OCB-808128 (Pos Bill No. repeating)
------------------------------------------------------------
-- RefNo.2
-- Modified By : Shine Das
-- Modified on : 17-04-2012
-- Ticket id   : M_002 (Magnolia_Issue Tracking System)
------------------------------------------------------------
CREATE PROC [dbo].[spMagnolia_GeneratePosBill]
(
@intshopId AS INT,
@intCounterId AS INT,
@strBillNo AS VARCHAR(30)='''' OUTPUT,
@intBillID AS INT ='''' OUTPUT
)
AS
DECLARE @Prefix as varchar(50)
DECLARE @NumberFound  AS INT
DECLARE @intNextBillID AS INT
DECLARE @intNextBillNo AS INT
BEGIN
SET NOCOUNT ON
----TO GET PREFIX OF THE SHOP-------
SELECT @Prefix=Prefix
FROM aPrefix p INNER JOIN aFinancialYear f ON p.Financialid=f.FinancialId
WHERE CurFinancialYear=1 AND InterfaceId=1502 AND ShopId=@intShopId
-------------------------------------
-----FOR NO COUNTER SHOPS-----
IF @intCounterId = 0
BEGIN
	SELECT @NumberFound = count(LastBillNo)
	FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId
	IF @NumberFound > 0
	BEGIN  ---IF LASTBILLNO IS IN losPosHeaderLastBillNo THEN IT DIRECTLY TAKES THESE FROM THE TABLE
		
	/* -- RefNo.1 start commented below
		SELECT @intNextBillNo=LastBillNo + 1
		FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId
	
	    UPDATE losPosHeaderLastBillNo
	    SET LastBillNo = @intNextBillNo WHERE ShopId=@intShopId
	
	*/
		UPDATE losPosHeaderLastBillNo SET LastBillNo = LastBillNo + 1 WHERE ShopId=@intShopId
		SELECT @intNextBillNo=LastBillNo FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId
	-- RefNo.1 ends
	
	END
	ELSE
	BEGIN ---IF LASTBILLNO IS NOT IN losPosHeaderLastBillNo THEN IT TAKES THESE FROM THE losposheader TABLE
		/*  -- RefNo.2	
	   SELECT @intNextBillNo = ISNULL(MAX(CONVERT(INT,RIGHT(poshBillNo,LEN(poshBillNo)-LEN(CONVERT(VARCHAR,@Prefix))))),0) + 1
	   FROM losposheader WHERE poshShopId=@intShopId AND LEFT(poshbillno,len(@Prefix))=@Prefix AND poshCounterId=0
	   INSERT INTO losPosHeaderLastBillNo(ShopId, LastBillNo) VALUES(@intShopId, @intNextBillNo)
	   */
	
	/*  -- RefNo.2	Altered Above section as given Below. Above Section causes Conversion error when counterwise
	    transaction has disabled after doing counterwise transactions.
	*/  --  START
	
	SELECT @intNextBillNo = ISNULL(MAX(CONVERT(INT,REVERSE(LEFT((REVERSE(poshBillNo)),(PATINDEX(''%/%'' ,(REVERSE (poshBillNo))))-1)))),0) + 1
FROM losposheader WHERE poshShopId=@intShopId AND LEFT(poshbillno,len(@Prefix))=@Prefix AND poshCounterId=0
INSERT INTO losPosHeaderLastBillNo(ShopId, LastBillNo) VALUES(@intShopId, @intNextBillNo)
-- RefNo.2	END
	END
SET @intBillID = (SELECT CASE WHEN COUNT(poshBillid)=0 THEN 1 ELSE MAX(poshBillid)+1 END FROM losposheader WHERE poshShopID=@intShopId)
SET @strBillNo = @Prefix+CONVERT(VARCHAR,@intNextBillNo)
END -----FOR NO COUNTER SHOPS-----
ELSE
BEGIN -----FOR COUNTER SHOPS-----
SELECT @NumberFound=COUNT(NextBillNo)
FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId
	IF @NumberFound >0
	BEGIN
		SELECT @intNextBillID = NextBillId,@intNextBillNo = NextBillNo
		FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId
			IF @intNextBillID IS NOT NULL
			BEGIN   ---IF NextBillId,NextBillNo IS IN aCounterMaster THEN IT DIRECTLY TAKES THESE FROM THE TABLE
				UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1
				WHERE CounterShopId=@intshopId AND counterid=@intCounterId
			END
			ELSE
			BEGIN  ---IF NextBillId IS NULL IN aCounterMaster THEN IT DIRECTLY TAKES NextBillId FROM THE TABLE aSettings
				Select @intNextBillID=RefBillId From aSettings
				IF @intNextBillID IS NOT NULL
				BEGIN
					UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1
					WHERE CounterShopId=@intshopId AND counterid=@intCounterId
				END
			END
	SET @intBillID = CONVERT(INT, CAST(100 + @intCounterId AS VARCHAR) + CAST (@intNextBillID AS VARCHAR))
	SET @strBillNo = @Prefix+''C''+CONVERT(VARCHAR,@intCounterId)+''/''+CONVERT(VARCHAR,@intNextBillNo)
	END
END -----FOR COUNTER SHOPS-----
--SELECT @strBillNo
--SELECT @intBillID
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_FetchShops]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_FetchShops]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : Rajesh Kamalakshan
-- Create date : 18/03/2010
-- Description : To check the user name and password for shops
-- =============================================
create PROCEDURE [dbo].[spMagnolia_FetchShops]--  ''fies'','''',1
-- Add the parameters for the stored procedure here
@Companyid int
AS
BEGIN
select * from dbo.ashops where Companyid=@Companyid and activeshop=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ExchangeRateHistory]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ExchangeRateHistory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spMagnolia_ExchangeRateHistory
------------------------------------------------------------------
--CREATED BY : NIDHEESH PV
--CREATED DATE : 06/06/2011
--COMMENTS : TO SAVE EXCHANGE DETAILS IN CORRESPONING EXCHNAGE HISTORY TABLES
------------------------------------------------------------------
--EXEC spMagnolia_ExchangeRateHistory 1,''2011/04/11 09:00:00''
CREATE PROC [dbo].[spMagnolia_ExchangeRateHistory](@IntCompanyId AS INT, @dtDatetime as datetime)
AS
DECLARE @IntExchangeId AS INT
DECLARE @dtPackageDate AS DATETIME  --iNSERTING PACKAGE DATE INSTEAD OF SYSTEM DATETIME
BEGIN
SET NOCOUNT ON
SELECT @dtPackageDate=CONVERT(DATETIME, CONVERT(VARCHAR(12),PAckageDate) + CONVERT(VARCHAR(12),GETDATE(),108))
FROM apackagesettings WHERE companyid=@IntCompanyId
---SELECT CONVERT(DATETIME,CONVERT(VARCHAR(12),@dtPackageDate)+ CONVERT(VARCHAR(12),CONVERT(TIME,GETDATE())))
SELECT @IntExchangeId=CASE WHEN COUNT(ExchangeID)> 0 THEN
MAX(ISNULL(ExchangeID,0))+1
ELSE 1 END
FROM [dbo].[ExchangeRateHistoryHeader]
INSERT INTO [dbo].[ExchangeRateHistoryHeader](ExchangeID,CompanyID,ExchangeDate) VALUES(@IntExchangeId,1,@dtPackageDate)
INSERT INTO [dbo].[ExchangeRateHistoryDetails](ExchangeID,CurrencyID,CompanyID,BuyingRate,SellingRate,AverageRate)
SELECT @IntExchangeId,CurrencyID,CompanyID,BuyingRate,SellingRate,AverageRate
FROM [dbo].[exchangeratedetail]
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[vwHPcustomersummaryasdate]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPcustomersummaryasdate]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created by :  Shinu
Created on : 12/12/2007
Modified by :
Modified on :
Purpose      : For Customer Summary Report
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on :29/09/10
comments : Included the case of partial settlements in the part od HP Account receipts.
Added the condition ''hprhtype is null'' to check partial settlment
Commentes  : used hpqhinstprice instead of hpqhAmount in the hp invoice part
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on : 29/09/10
comments : Included the case of partial settlements in the part od HP Account receipts.
Added the condition ''hprhtype is null'' to check partial settlment
Commentes  : used hpqhinstprice instead of hpqhAmount in the hp invoice part
--------------------------------------------------------------------------------
Modified By : Nidheesh P V
Modified on :16/11/11
comments :  corrected the HQ HP Account receipt amount
Reference: RefNo:1
*/ ------------------------------------------------------------------------------
CREATE view [dbo].[vwHPcustomersummaryasdate] as
-- Invoices Done To Customers
select c.companyid, c.customerid,hpqhshopid ShopID, rh.hpqhQuotationDate invoicedate , c.currencyid, 0 as opening, 0 as advance,
convert(numeric(18,2),isnull(sum(hpqhinstprice),0)) as invoiced, 0 as settled, 0 as paid,s.DepartmentID,
c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
loshpInvoiceheader rh, acustomermaster c,aShops s
where
rh.hpqhcompanyid = c.companyid and rh.hpqhcancel = 0 and rh.hpqhcustomerid = c.customerid And S.ShopID=hpqhshopid
And rh.hpqhType=''I''
group by
c.companyid,c.CustomerCategory, c.customerid, rh.hpqhQuotationDate,
c.currencyid ,Departmentid ,c.custgroupname,hpqhshopid
Union All
-- Shop Receipts Done By Customers (Down Payment + Settlements)
select c.companyid, c.customerid,hprhshopid, rh.hprhReceiptdate, c.currencyid, 0 as opening, 0 as advance,
0 as invoiced, convert(numeric(18,2),isnull(sum(hprhReceiptAmount),0)) as settled, 0 as paid,s.DepartmentID,
c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
loshpreceiptheader rh, acustomermaster c,aShops s
where
rh.hprhcompanyid = c.companyid and rh.hprhcancel = 0 and rh.hprhcustomerid = c.customerid And S.ShopID=hprhshopid
group by
c.companyid,c.CustomerCategory, c.customerid, rh.hprhReceiptDate,
c.currencyid ,Departmentid ,c.custgroupname,hprhshopid
Union All
-- payment done to customers
select c.companyid, c.customerid,0, ph.hphpaymentdate, c.currencyid, 0 as opening, 0 as advance,
convert(numeric(18,2),isnull(sum(hphPaymentamount/hphBankExchangeRate*hphCusExchangeRate),0)) as invoiced, 0 as settled, 0 as paid,hphDepartmentID,
c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
aHppaymentHeader ph, acustomermaster c
where
ph.hphcompanyid = c.companyid and ph.hphcancel = 0 and ph.hphcustomerid = c.customerid
group by
c.companyid,c.CustomerCategory, c.customerid, ph.hphpaymentdate,
c.currencyid ,hphdepartmentid ,c.custgroupname
union all
-- HQ Receipts Done By Customers
select c.companyid, c.customerid,0, rh.hprhReceiptdate, c.currencyid, 0 as opening, 0 as advance,
0 as invoiced,
--convert(numeric(18,2),isnull(sum(hprhAmount/hprhBankExRate*hprhCusExRate),0)) as settled,  --RefNo:1 commented and added below
convert(numeric(18,2),sum((((rh.hprhamount/rh.hprhBankExRate)*rh.hprhCusExRate)-
(case when isnull(hprhcreditaccid,0)<>0 then isnull((hprhCreditAmount/hprhcreditExRate)*rh.hprhCusExRate,0) else 0 end)))) pmtamt,
0 as paid,hprhDepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
ahpReceiptHeader rh, acustomermaster c
where
rh.hprhcompanyid = c.companyid and rh.hprhcancel = 0 and rh.hprhcustomerid = c.customerid
group by
c.companyid,c.CustomerCategory, c.customerid, rh.hprhReceiptDate,
c.currencyid ,hprhdepartmentid ,c.custgroupname'
GO
/****** Object:  View [dbo].[vwhpCustomerLedgerforReport]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpCustomerLedgerforReport]'))
EXEC dbo.sp_executesql @statement = N'
/*
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 [dbo].[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
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetPackagesettings]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetPackagesettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Rajesh Kamalakshan
-- Create date: 6-5-2008
-- Description: To get company Package Settings
-- =============================================
CREATE PROCEDURE [dbo].[spMagnolia_GetPackagesettings]
-- Add the parameters for the stored procedure here
@CompanyId int=0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
select * from aPAckageSettings where [CompanyId]=@CompanyId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sptempinsert]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptempinsert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sptempinsert    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.sptempinsert    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.sptempinsert    Script Date: 31/07/2002 2:00:34 PM ******/
/****** Object:  Stored Procedure dbo.sptempinsert    Script Date: 20/11/2001 9:59:11 AM ******/
/****** Object:  Stored Procedure dbo.sptempinsert    Script Date: 17/11/2001 9:22:21 PM ******/
CREATE proc [dbo].[sptempinsert] as
update apackagesettings set servername=''Updated''
select servername from apackagesettings' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrout]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockTrout]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateShopStockTrout    Script Date: 18/01/2003 9:45:47 PM ******/
-- Created By		 : Lawrence.J
-- Created On		 : 30-Dec-2002
-- Purpose		 : (V3) Transfer out stock updation in POS
-- Verified by hariharan : 03/01/2003
----------------------------------------------------
-- Modified by           : Kishore
-- Modified on           : 17-01-2003
-- Comments              : Added code to insert to shop stock
--                         when there is no record in shop stock
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateShopStockTrout](@despatchId int,@ShopId int,@process char(1)) as
begin
	--Altered by lawrence for removing location 19-Dec-02
	declare
	@cur_despatchId int,
	@cur_shopId int,
	@cur_ItemId int,
	@cur_shipmentId int, --Lawrence includeded shipmentId 27-Dec-02
	@cur_itembadqty numeric(18,3),
	@cur_itemgoodqty numeric(18,3),
@intCount int
	set nocount on
	declare cursor_Detail  cursor for
		select TODId,TODshopId,TODItemId,TODissuedBadQty,
		TODissuedGoodQty,TODshipmentId from mesTransferOutDetail
		where TODId=@despatchId and TODshopId= @shopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_despatchId, @cur_shopId, @cur_ItemId,
		@cur_itembadqty, @cur_itemgoodqty,@cur_shipmentId
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			update mosShopStock set Stock = Stock + @cur_itemgoodqty
				where ItemId = @cur_ItemId and ShopId = @cur_shopId
				and ShipmentId=@cur_shipmentId
		end
		if @process = ''F''
		begin
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and shopId = @ShopId
			if @intCount = 0
			begin
				insert mosShopStock(ShopId, StockDate, ShipmentId, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @ShopId, getdate(), 1, @cur_itemId, 0, 0, 0, 0
			end
			update mosShopStock set Stock = Stock - @cur_ItemGoodQty
				where ItemId = @cur_ItemId and ShopId = @cur_shopId
				and ShipmentId=@cur_shipmentId
		end
		fetch next from cursor_Detail into
			@cur_despatchId, @cur_shopId, @cur_ItemId,
			@cur_itembadqty, @cur_itemgoodqty, @cur_shipmentId
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrIN]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockTrIN]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateShopStockTrIN    Script Date: 18/01/2003 9:45:48 PM ******/
-- Created By		: Lawrence.J
-- Created On		: 30-Dec-2002
-- Purpose		: (V3) Updating Goods TransferIN Stock in POS
-- Verified by 		: Hariharan 0n 03/01/2003
----------------------------------------------------------------------------
-- Modified on          : 16/01/2003
-- Modified by          : Kishore
-- Comments             : Stock updation replaced the field
--                        TIDtransfergoodqty with TIDrecievedgoodqty
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateShopStockTrIN]( @Arrivalid int,
			@ShopId int,@Type char(1) ) as
declare
@cur_arrivalid int,
@cur_shopId int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_cost numeric(18,2),
@cur_ShipmentID int,
@recCount as int
set nocount on
	declare cursor_Detail  cursor for
	select TIDID, TIDshopid, TIDitemID, tidRecievedGoodQty, --TIDtransfergoodqty,
	TIDCostprice, 1 from LOsTransferInDetail
	where TIDID = @Arrivalid and TIDshopid = @ShopId
open cursor_Detail
fetch next from cursor_Detail into
@cur_arrivalid, @cur_shopId, @cur_itemid,
@cur_itemgoodqty,@cur_cost, @cur_ShipmentID
while @@fetch_status = 0
begin
	if @Type=''F''
begin
		select @recCount = count(*) from  mosshopstock where ItemID= @cur_itemid
		and ShopID = @cur_shopId
		if @recCount =0
			insert mosshopstock(ShopID,ShipmentID,ItemID,Stock,
			ItemCostPrice, StockDate) select @cur_shopId, 1, @cur_ItemID,
			@cur_itemgoodqty,@cur_Cost, getdate()
		else
			update mosshopstock set Stock = Stock + @cur_itemgoodqty
			where ItemID = @cur_itemid and ShopID = @cur_shopId
	 end
	fetch next from cursor_Detail into
	@cur_arrivalid, @cur_shopId, @cur_itemid,
	@cur_itemgoodqty,@cur_cost,@cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingShopWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingShopWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[spStockBalancingShopWise] @intShopId as Int,@strFromDate as Varchar(10),@strToDate as Varchar(10),@intActive as int  AS
--declare  @strsql as nvarchar(4000)
--set @strFromDate = convert(datetime,@strFromDate,101)
--set @strToDate = convert(datetime,@strToDate,101)
if @intActive=0
Begin
	if @intShopId=0
		 select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
			 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
			 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
			 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
			 from mosshopstock  group By itemid
			 union All
			 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0, 0, 0 from
			 vwshopbincardaudit where sDate < @strFromDate group by itemid
			 union All
			 select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type in (''Local Purchase'')
			 group by itemid
			 Union All
			 select itemid,0, 0, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type in (''Cash Sales'',''Credit Sales'',
			 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'')
			 group by itemid
			 union All
			 select itemid,0, 0,0, convert(numeric(18,3), sum(transqty * mode)) stock , 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type not in (''Cash Sales'',''Credit Sales'',
			 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'',''Local Purchase'')
			 group by itemid
			 ) inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
	else
		 select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
			 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
			 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
			 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
			 from mosshopstock where ShopID=@intShopId  group By itemid
			 union All
			 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0, 0 from
			 vwshopbincardaudit  where ShopID=@intShopId AND sDate < @strFromDate group by itemid
			 union All
			      select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock,0 , 0 , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type in (''Local Purchase'')
			 group by itemid
			 union All
			      select itemid,0, 0,convert(numeric(18,3), sum(transqty * mode)) stock, 0 , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type in (''Cash Sales'',''Credit Sales'',''Exchanged In'',''Exchange Out'',''Special Invoice Return'')
			 group by itemid
			 union All
			      select itemid,0, 0,0, convert(numeric(18,3), sum(transqty * mode)) stock , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type not in (''Cash Sales'',''Credit Sales'',''Exchanged In'',''Exchange Out'',''Special Invoice Return''
			 ,''Local Purchase'') group by itemid
			 ) inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
end
else
Begin
	if @intShopId=0
		 select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
			 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
			 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
			 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
			 from mosshopstock  group By itemid
			 union All
			 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0, 0, 0 from
			 vwshopbincardaudit where sDate < @strFromDate group by itemid
			 union All
			 select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type in (''Local Purchase'')
			 group by itemid
			 Union All
			 select itemid,0, 0, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type in (''Cash Sales'',''Credit Sales'',
			 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'')
			 group by itemid
			 union All
			 select itemid,0, 0,0, convert(numeric(18,3), sum(transqty * mode)) stock , 0 from
			 vwshopbincardaudit where sDate between @strFromDate And @strToDate and Type not in (''Cash Sales'',''Credit Sales'',
			 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'',''Local Purchase'')
			 group by itemid
			 ) inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
			 AND ai.Active=1
	else
		 select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
			 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
			 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
			 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
			 from mosshopstock where ShopID=@intShopId  group By itemid
			 union All
			 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0, 0 from
			 vwshopbincardaudit  where ShopID=@intShopId AND sDate < @strFromDate group by itemid
			 union All
			      select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock,0 , 0 , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type in (''Local Purchase'')
			 group by itemid
			 union All
			      select itemid,0, 0,convert(numeric(18,3), sum(transqty * mode)) stock, 0 , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type in (''Cash Sales'',''Credit Sales'',''Exchanged In'',''Exchange Out'',''Special Invoice Return'')
			 group by itemid
			 union All
			      select itemid,0, 0,0, convert(numeric(18,3), sum(transqty * mode)) stock , 0 from
			 vwshopbincardaudit where ShopID=@intShopId AND sDate between @strFromDate And @strToDate and
			 Type not in (''Cash Sales'',''Credit Sales'',''Exchanged In'',''Exchange Out'',''Special Invoice Return''
			 ,''Local Purchase'') group by itemid
			 ) inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
			 AND ai.Active=1
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGodownLocationStock]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownLocationStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on    : 19/01/2004
-- Modified by    : Kishore
-- Comments       : Modified so that this sp can be used rptGodownLocationStock report (17/11/2003)
--                : Added unit code (19/01/2004)
-- dheena modifed by as per hari suggestion add code part code
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified by Sreejith G A
--Modified on 20100628
--excluded some space from the dynamic query
--spGodownLocationStock 6,0,0,'''',''Archie'',1,1
CREATE PROCEDURE [dbo].[spGodownLocationStock]
@intGodownId   as int = 0,
@intLocationID   as int = 0,
@intItemID   as int = 0,
@strItemCategoryIDs as varchar(600) = '''',
@strBrandName   as Varchar(100) = '''',
@OpeningStockYesNO  as bit,
@NegativeStockYesNo  as bit AS
Begin
Set ansi_warnings off
Set NoCount on
declare @strSql as nvarchar(max)
Declare @strGodownName as Varchar(250)
SELECT @strGodownName = GodownName FROM aGodown
WHERE GodownId = @intGodownId
set @strSql=N''select ladgodownid, ladlocationid, laditemid, sum(quantity) quantity,
itemDescription,Brand,lLocationName, CategoryNameDescription,
avg(itemRate) CostPrice, ItemCode, '' + Char(39) + @strGodownName + Char(39) + '' GodownName,
Min(lg.lgGroupName) lgGroupName, Min(UnitCode) UnitCode,part_code
from (select la.ladgodownid, la.ladlocationid, la.laditemid, sum(la.laditemqty) quantity,
case when coalesce(cl.ColorName,'''''''') + coalesce(sz.SizeName,'''''''')='''''''' then it.ItemDescription
when coalesce(cl.ColorName,'''''''') ='''''''' then it.ItemDescription + '''' - '''' + sz.SizeName
when coalesce(sz.SizeName,'''''''') ='''''''' then it.ItemDescription + '''' - '''' + cl.ColorName
else it.ItemDescription + '''' - '''' + cl.ColorName + '''' - '''' + sz.SizeName
end  ItemDescription, it.itemRate, it.Brand, lc.lLocationName, itc.CategoryNameDescription,
sz.SizeName, cl.ColorName, ItemCode, lGroupId, Min(UnitCode) UnitCode,part_code
from loilocationarrivaldetails la,aItem it,LOiLocation lc, aColor cl,aSize sz,aItemCategory itc, aUnit u
where la.ladgodownid = lc.lGodownID and la.ladlocationid = lc.lLocationID and
la.laditemid = it.ItemID and it.ItemCategoryID = itc.ItemCategoryID and
it.ColorId *= cl.ColorID and it.SizeID *= sz.SizeID and la.ladcancel = 0 And it.UnitsId = u.UnitId''
if @intGodownId<>0
set @strSql =  @strSql + N'' and la.ladgodownid = '' + convert(varchar(10),@intGodownId)
if @OpeningStockYesNO = 1
set @strSql = @strSql+ N'' and la.ladinterfaceid = 506''
if @intLocationID <> 0
set @strSql = @strSql+ N'' and la.ladlocationid = '' + convert(varchar(10),@intLocationID)
if @intItemID<>0
set @strSql = @strSql+ N'' and la.laditemid = '' + convert(varchar(10),@intItemID)
if @strBrandName <> ''''
set @strSql = @strSql+ N'' and it.Brand = '''''' + @strBrandName + ''''''''
if @strItemCategoryIDs <> ''''
set @strSql = @strSql+ N'' and it.ItemCategoryID in('' + @strItemCategoryIDs +'')''
set @strSql = @strSql+ N'' group by la.ladgodownid, la.ladlocationid, la.laditemid,it.ItemDescription,
it.itemRate,it.Brand, lc.lLocationName, itc.CategoryNameDescription,sz.SizeName, cl.ColorName,
ItemCode, lGroupId,part_code
union all ''
set @strSql = @strSql +N''select li.lidgodownid, li.lidlocationid, li.liditemid, - sum(li.liditemqty) quantity,
case  when coalesce(cl.ColorName,'''''''') + coalesce(sz.SizeName,'''''''')='''''''' then it.ItemDescription
when coalesce(cl.ColorName,'''''''') ='''''''' then it.ItemDescription + '''' - '''' + sz.SizeName
when coalesce(sz.SizeName,'''''''') ='''''''' then it.ItemDescription + '''' - '''' + cl.ColorName
else it.ItemDescription + '''' - '''' + cl.ColorName + '''' - '''' + sz.SizeName
end  ItemDescription, it.itemRate, it.Brand, lc.lLocationName, itc.CategoryNameDescription,
sz.SizeName, cl.ColorName, ItemCode, lGroupId, Min(UnitCode) UnitCode,part_code
from
loilocationIssuedetails li,aItem it, LOiLocation lc,aColor cl, aSize sz, aItemCategory itc, aUnit u
where
li.lidgodownid = lc.lGodownID
And li.lidlocationid = lc.lLocationID
And li.liditemid = it.ItemID
And it.ItemCategoryID = itc.ItemCategoryID
And it.ColorId *= cl.ColorID
And it.SizeID *= sz.SizeID
And li.lidcancel = 0
And it.UnitsId = u.UnitId''
if @intGodownId <> 0
set @strSql = @strSql + N'' and li.lidgodownid='' + convert(varchar(10),@intGodownId)
if @OpeningStockYesNO = 1
set @strSql = @strSql + N'' and li.lidinterfaceid = 506''
if @intLocationID <> 0
set @strSql = @strSql + N'' and li.lidlocationid='' + convert(varchar(10),@intLocationID)
if @intItemID <> 0
set @strSql = @strSql+ N'' and li.liditemid='' + convert(varchar(10),@intItemID)
if @strBrandName <> ''''
set @strSql = @strSql+ N'' and it.Brand='''''' + @strBrandName + ''''''''
if @strItemCategoryIDs <> ''''
set @strSql = @strSql+ N'' and it.ItemCategoryID in ('' + @strItemCategoryIDs + '')''
set @strSql = @strSql+ N'' group by
lc.lLocationName, it.ItemDescription, it.itemRate, li.lidgodownid,li.lidlocationid, li.liditemid,
it.Brand, itc.CategoryNameDescription, sz.SizeName,cl.ColorName, ItemCode, lGroupId,part_code) s, loiLocationGroup lg
Where s.lGroupId = lgGroupId And lgGodownId = '' + convert(varchar(10), @intGodownId) +
'' group by itemDescription, lLocationName, Brand, laditemid,ladgodownid, ladlocationid,
CategoryNameDescription, ItemCode,part_code''
if @NegativeStockYesNo=1
Begin
set @strSql = @strSql+ N'' having sum(quantity) < 0''
End
Else
Begin
set @strSql = @strSql+ N'' having sum(quantity) <> 0''
End
exec sp_executesql @strSql
Set ansi_warnings on
Set NoCount off
End' 
END
GO
/****** Object:  View [dbo].[vwjournaldetails]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwjournaldetails    Script Date: 18/01/2003 9:45:34 PM ******/
--Last Modified on 	: 04/12/2002
--Modified by		: leo
--Comments		: as per new concept of exchange rate
CREATE view [dbo].[vwjournaldetails] as
select jd.companyid, jd.journalid, jd.journaldetailid, jd.journalcredit,
case when jd.accountid is not null then jd.accountid
when jd.customerid is not null then cm.debtoraccid
when jd.vendorid is not null then vm.creditoraccid end accountid,
jd.Amount, jd.ActualAmount, jd.departmentid, jd.depamount, jd.PostGroup  from
moajournaldetails jd left outer join  acustomermaster cm on
jd.companyid = cm.companyid and jd.customerid = cm.customerid
left outer join  avendormaster vm on jd.companyid = vm.companyid
and jd.vendorid = vm.vendorid'
GO
/****** Object:  StoredProcedure [dbo].[spCrEDitDebitOpeningCur]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCrEDitDebitOpeningCur]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 28/12/2002 4:26:49 AM ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 14/09/2002 12:48:15 AM ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 20/11/2001 9:59:13 AM ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 17/11/2001 9:22:21 PM ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 16/06/2001 15:36:36 ******/
/****** Object:  Stored Procedure dbo.spCrEDitDebitOpeningCur    Script Date: 09/03/2001 02:32:29 ******/
CREATE proc [dbo].[spCrEDitDebitOpeningCur] @intCompanyID as int, @intAccID as int,@FROMDate as smalldatetime
as
begin
	Declare @OpeningCrEDit as numeric(18,2)
	Declare @OpeningDebit as numeric(18,2)
	Declare @intTransCurID as int
	Declare @numBuyingRate as numeric(18,2)
	Declare @numAverageRate  as numeric (18,2)
	Declare @numTransRate as numeric(18,2)
	
set nocount on
	
	SELECT @intTransCurID = CurrencyID
	FROM aAccountMaster
	WHERE CompanyID = @intCompanyID and AccountID = @intAccID
	SELECT @OpeningCrEDit = isnull(Openingamount,0)
	FROM aAccountMaster
	WHERE CompanyID = @intCompanyID and AccountID = @intAccID
	SELECT @numBuyingRate = BuyingRate, @numAverageRate = AverageRate
	FROM ExchangeRate EH, ExchangeRatEDetail ED
	WHERE EH.CompanyID = ED.CompanyID and EH.ExchangeID = ED.ExchangeID and
		EH.CompanyID = @intCompanyID and EH.exchangEDate =
	(SELECT min(JournalDate) FROM moaJournalHeader WHERE CompanyID =@intCompanyID)
	and ED.CurrencyID = @intTransCurID
	if (@numBuyingRate is not null)
		set @numTransRate = @numBuyingRate
	else
		set @numTransRate = @numAverageRate
	set @OpeningCrEDit = @OpeningCrEDit * @numTransrate
SELECT  @OpeningCrEDit = @OpeningCrEDit + isnull((SELECT sum(actualAmount)  FROM moaJournalDetails JD, moaJournalHeader JH
			WHERE JH.JournalID = JD.JournalID and
			JH.CompanyID = JD.CompanyID and JD.AccountID = @intAccID
			and JournalCrEDit = 1 and JournalDate < @FROMdate),0)
SELECT  @OpeningDebit = isnull(OpeningAmount,0) FROM aAccountMaster
			 WHERE CompanyID = @intCompanyID and AccountID = @intAccID
						
	SELECT @numBuyingRate = sellingRate, @numAverageRate = AverageRate
	FROM ExchangeRate EH, ExchangeRatEDetail ED WHERE EH.CompanyID
	= ED.CompanyID and EH.ExchangeID = ED.ExchangeID and
	EH.CompanyID = @intCompanyID and EH.exchangEDate =
	(SELECT min(JournalDate) FROM moaJournalHeader WHERE CompanyID =@intCompanyID)
	and ED.CurrencyID = @intTransCurID
	if (@numBuyingRate is not null)
		set @numTransRate = @numBuyingRate
	else
		set @numTransRate = @numAverageRate
	set @openingdebit = @openingdebit * @numTransrate
SELECT  @OpeningDebit = @OpeningDebit + isnull((SELECT sum(actualAmount)  FROM moaJournalDetails JD, moaJournalHeader JH
			WHERE JH.JournalID = JD.JournalID and
			JH.CompanyID = JD.CompanyID and JD.AccountID = @intAccID
			and JournalCrEDit = 0 and JournalDate < @FROMdate),0)
SELECT @OpeningCrEDit, @openingdebit, @intCompanyID, @intAccID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCreditController]    Script Date: 10/06/2012 14:17: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].[spCreditController]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
=======================================================================================================================================
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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCreditForOverdueCustomers]    Script Date: 10/06/2012 14:17: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].[spCreditForOverdueCustomers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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' 
END
GO
/****** Object:  View [dbo].[vwinvoiceswithcontrolaccs]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceswithcontrolaccs]'))
EXEC dbo.sp_executesql @statement = N'
--modified by 	: venki , Hariharan
--Modified Date	: 280803, 03/11/2003
--comment : corrected for refering invoice on muliple depts
CREATE view  [dbo].[vwinvoiceswithcontrolaccs] as
select h.InvoiceNo, h.InvoiceID, h.InvoiceDate, h.Remarks,dep.departmentname,otherdepid,
maindepid, h.companyid, d.accountid, d.amount,1 credit, h.CustomerID, h.exchangerates,accountdesc
from ServiceInvoiceDetails d, AccountsInvoiceHeader h ,  adepcontrolaccounts ca,
adepartmentmaster dep, aaccountmaster a where h.companyid = d.companyid and
h.Invoiceid = d.Invoiceid and ca.companyid = d.companyid and ca.companyid=a.companyid and
ca.controlaccid = d.accountid and h.cancelled =0 and ca.controlaccid = a.accountid
and h.departmentid = dep.departmentid and h.departmentid<>maindepid
and ca.maindepid  not in
(select departmentid from
Journaltransheader where Invoiceid = h.invoiceid and cancelled = 0
union all
select 0)
------------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwInvoicesWithControlAccounts]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoicesWithControlAccounts]'))
EXEC dbo.sp_executesql @statement = N'
--created on 	: 10/03/2003
--Created by 	: R Harikrishnan
--Comments	: For accounts alerts
CREATE View [dbo].[vwInvoicesWithControlAccounts] as
select
	h.InvoiceNo, h.InvoiceID, h.InvoiceDate, h.Remarks ,dep.departmentname,
	ca.maindepid, h.companyid, d.accountid, d.amount, 0 cr, a.accountdesc
from
	ServiceInvoiceDetails d, accountsInvoiceHeader h ,  adepcontrolaccounts ca,
	adepartmentmaster dep, aaccountmaster a
where
	d.companyid = h.companyid and d.InvoiceID = h.InvoiceID and d.companyid = ca.companyid and
	d.AccountID = ca.controlaccid and d.accountid = a.accountid and
	h.CompanyID =dep.CompanyID and h.departmentid = dep.departmentid and h.departmentid <> ca.maindepid
	 and h.cancelled =0 and ca.maindepid  not in
	(select departmentid from
	Journaltransheader where Invoiceid = h.invoiceid and cancelled = 0
	union all
	select 0)'
GO
/****** Object:  View [dbo].[vwInvoicedPosRequests]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoicedPosRequests]'))
EXEC dbo.sp_executesql @statement = N'
--Created By	: R Harikrishnan
--Created on	: 06/08/2003
--Comments	: This view will list all the Purchase Requests whose
--		  Invoice is made. The will list the InvoiceID,POID,
--		  QuotationID and RequestID
-------------------------------------------------------------------------
CREATE view [dbo].[vwInvoicedPosRequests] as
select
	ih.ihShopID,ih.ihInvoiceID InvoiceID,ih.ihProformaID POID,
	ph.QuotationID,ph.RequestID
from
	losInvoiceHeader ih,
	(select
		ih.ihShopID,ih.ihInvoiceID,ih.ihProformaID, qh.QuotationID,qh.RequestID
	from
		losInvoiceHeader ih,
		(select
			ih.ihShopID,ih.ihInvoiceID QuotationID,ih.ihProformaID,rh.RequestID
		from
			losInvoiceHeader ih,
			(select
				ihShopID,ihInvoiceID RequestID
			from
				losInvoiceHeader
			where
				ihType=''R'') rh
		where
			ih.ihShopID=rh.ihShopID and ih.ihProformaID=rh.RequestID and
			ihType=''Q'') qh
	where
		ih.ihShopID=qh.ihShopID and ih.ihProformaID=qh.QuotationID and
		ihType=''P'') ph
where
	ih.ihShopID=ph.ihShopID and ih.ihProformaID=ph.ihInvoiceID and
	ihType=''I'' and ih.ihCancelled=0'
GO
/****** Object:  View [dbo].[vwInvoiceQuotation]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoiceQuotation]'))
EXEC dbo.sp_executesql @statement = N'
create  view [dbo].[vwInvoiceQuotation] as
---Crested By Jothish S R
---Date 19-04-2011
--created for invoce done bit added for purcahase  QuotationReport
select Qt.ihInvoiceID QuotationID,Qt.ihShopID ShopID, Qt.ihInvoiceNo QuotationNo,pr.ihInvoiceNo PurrchaseOrderNO,iv.ihInvoiceNo,isnull(iv.ihInvoiceID,0)InvoiceID from ( select *   from LosInvoiceheader where ihType=''Q'' and ihCancelled=0 ) Qt
left outer join ( select *   from LosInvoiceheader where   ihType=''P'' and ihCancelled=0 ) Pr
on Qt.ihShopID=Pr.ihShopID and  qt.ihInvoiceID=pr.ihProformaID
left outer join ( select *   from LosInvoiceheader where   ihType=''i'' and ihCancelled=0 ) iv
on iv.ihShopID=Pr.ihShopID and  pr.ihInvoiceID=iv.ihProformaID'
GO
/****** Object:  View [dbo].[vwItemOrderedInPO]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemOrderedInPO]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwItemOrderedInPO    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 13/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwItemOrderedInPO]
as
select poditemid, sum(podqty) poqty from
(
select distinct poditemid, podQty from lopurchaseorderdetail pod , lopurchaseorderheader poh,
losppurchasebillheader pbh where poh.pohpoid=pbh.pbhpoid and pbhcancelled=0 and
pbhdespatched=0 and poh.pohpoid=pod.podpoid and poh.pohcancel=0
union all
select distinct poditemid, podQty from lopurchaseorderdetail pod , lopurchaseorderheader poh,
losppurchasebillheader pbh where poh.pohpoid=pod.podpoid and poh.pohcancel=0
and pohpoid not in(select pbhpoid from losppurchasebillheader where pbhcancelled=0)) orderpo
group by poditemid'
GO
/****** Object:  View [dbo].[vwItemDiscountList]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDiscountList]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 13/12/02
--Modified by		: leo
--Comments		: v3
CREATE VIEW [dbo].[vwItemDiscountList] AS
select case dp when 0.0 then 0.0 else round(((sp - dp)/sp) * 100,2) end as discount,
i.itemid, ItemCategoryID, case wp when 0.0 then 0.0 else round(((sp - wp)/sp) * 100,2) end
as wholesaleperc, i.itemcode, vw.itemdescription , ''Item Wise'' as type, ''>'' + '' '' +
convert(varchar(50),dpqty) as condition,  ''>'' + '' '' +
convert(varchar(50),wpqty) as wpcondition, pk.packingtypeid, pk.packingtypename,
pk.packingtypecode from aitem i, vwitemdescription vw, apackingtype pk ,
(select itemid, packingtypeid, currencyid, segmentid, max(sellingprice)  sp,
max(discountprice) dp, max(wholesaleprice) wp from losshopitemshipmentdetail
group by itemid, packingtypeid, currencyid, segmentid having max(sellingprice) >0.0 )
itemsp where itemsp.itemid = i.itemid and vw.itemid = i.itemid and
itemsp.packingtypeid=pk.packingtypeid and isnull(i.dpqty,0.0)  > 0
and isnull(i.wpqty,0.0) >0.0'
GO
/****** Object:  View [dbo].[vwItemRetailPackingPricelist]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemRetailPackingPricelist]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwItemRetailPackingPricelist    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 11/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwItemRetailPackingPricelist] as
select vw.itemid, vw.unitsid, vw.quantity, vw.packingtypeid, isnull(max(sp.sellingprice),0) sp,
isnull(max(sp.wholesaleprice),0) wp, isnull(max(sp.discountprice),0) dp  from vwItemRetailPacking vw
left outer join losshopitemshipmentdetail sp on vw.itemid = sp.itemid and vw.packingtypeid = sp.packingtypeid
group by vw.itemid, vw.unitsid, vw.quantity, vw.packingtypeid'
GO
/****** Object:  View [dbo].[vwHpItemDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHpItemDetails]'))
EXEC dbo.sp_executesql @statement = N'
--*********************************************************************************
-- Created by  :  Shinu
-- Created on  : 28/08/2007
-- Purpose     : To Populate Hire Purchase Item Details
--*********************************************************************************
-- Modified by :
-- Modified on :
-- Purpose     :
--*********************************************************************************
create View [dbo].[vwHpItemDetails] AS
select ai.ItemID,ai.ItemCode,ai.ItemDescription,asd.ShopID
from aitem ai
inner join ahpitemdetails aid on ai.ItemID=aid.ItemID
inner join aShopItemDetail asd on ai.ItemID=asd.ItemID'
GO
/****** Object:  StoredProcedure [dbo].[spTenantRegister]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTenantRegister]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------
-- Created on 	: 22/08/2003
-- Created by 	: R Harikrishnan
-- Comments	: For Tenant Register Transaction Report
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spTenantRegister]
	@intCompanyID 	AS INT,
	@intShopID 	AS INT,
	@intRegnID 	AS INT
AS
BEGIN
	DECLARE @strDepCurrSymbol AS VARCHAR(25)
	SELECT
		@strDepCurrSymbol=ISNULL(cm.Symbol,'''')
	FROM
		aShops sm,aDepartmentMaster dm,aCurrencyMaster cm
	WHERE 	
		sm.CompanyID = dm.CompanyID and sm.DepartmentID=dm.DepartmentID and
		dm.CompanyID=cm.CompanyID and dm.depCurrencyID=cm.CurrencyID and
		sm.CompanyID=@intCompanyID and sm.ShopID=@intShopID
	SELECT
		trh.trhTransno, trh.trhDate,CASE WHEN trh.trhStatus=''B'' THEN ''Billed''
		ELSE ''Not Billed'' END Status, trh.trhRemarks,
		trd.trdServiceActualRate, trd.trdServiceRate, trd.trdServiceQty,
		sm.sperName EnteredBy, ad.apdapartmentno,agh.mghAgreementNo,
		ser.sername Service,@strDepCurrSymbol DepCurrSymbol
	FROM
		losTenantServiceRegisterHeader trh, losTenantServiceRegisterDetail trd,aSalesPersonMaster sm,
		losApartmentDetail ad, losApartmentAgreementHeader agh,aServiceMaster ser
	WHERE
		trh.trhTransCompanyID=trd.trdTransCompanyID and
		trh.trhTransShopID =trd.trdTransShopID and trh.trhTransID=trd.trdTransID and
		trh.trhTransCompanyID=agh.mghCompanyId and trh.trhTransShopID=agh.mghShopId and
		trh.trhAgreementid=agh.mghAgreementid and trh.trhTransCompanyID=ad.apdcompanyid and
		trh.trhTransShopId=ad.apdShopid and 	trh.trhApartmentId =ad.apdApartmentid and
		trh.trhEnteredBy=sm.sperID and trh.trhTransCompanyID = sm.CompanyID and
		trd.trdServiceID = ser.serID and trd.trdTransCompanyID = ser.serCompanyID and
		trh.trhTransCompanyID=@intCompanyID and trh.trhTransShopID=@intShopID and
		trh.trhTransID=@intRegnID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSellpriceCurrwiseWOPriceChange]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellpriceCurrwiseWOPriceChange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By  : Aneesh
--Created Date: 31/01/2006
--Note        : This peocedure is same as spSellpriceCurrwise but, i have avoided the checking
--  pricechanged = 0 condition to fetch the already existing selling price
--       : This has been done for Redwave
------------------------------------------------------------------------
--Ref:01
--Modified By : Nidheesh P v
--Modified on :18/02/2011
--Comments : The joining was not correct in the case for  @intSelcount<>0(segment wise)& @intCash=1(cash sale).
--So the query is just copied from the case  @intSelcount<>0 & @intCash=1
--and NOCOUNT is SET ON at the start and SET OFF at the end of the proc.
------------------------------------------------------------------------
CREATE proc [dbo].[spSellpriceCurrwiseWOPriceChange] @intcompanyid as int, @intshopid as int, @intitemid as int,
@intPackid as int, @intSegmentid as int=0, @intPricefixathq as int, @intcash as int,
@intToCurrencyid as int
as
declare @intselcount as int
declare @dblExRate as numeric(18,8)
declare @intCurrencyID as int
begin
SET NOCOUNT ON
if @intSegmentid>0
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
segmentId = @intSegmentId and
currencyid = @intToCurrencyid
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and segmentId = @intSegmentId
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
begin
if @intCash=1
Select round(isnull(SellingPrice,0) * @dblExRate,2)  SP,
round(isnull(DiscountPrice,0)*@dblExRate ,2) DP,
round(Isnull(WholeSalePrice,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from      --Ref:01
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
segmentid = @intsegmentid and packingtypeid = @intpackid
and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
segmentid = @intsegmentid and packingtypeid = @intpackid
and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
end
else
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty, forsales,
itemdescription  from aitem where itemid = @intItemid
End
end
else
Begin
if @intPricefixathq = 0
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
Shopid = @intShopid and
currencyid = @intToCurrencyid
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and Shopid = @intShopid
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
Begin
if @intCash=1
Select round(isnull(SellingPrice,0) *@dblExRate,2)  SP,
round(isnull(DiscountPrice,0) * @dblExRate,2)  DP,
round(Isnull(WholeSalePrice,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid
and Shopid = @intShopid and packingtypeid = @intpackid
and ai.itemid = sd.itemid
and currencyid  = @intCurrencyid
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid
and Shopid = @intShopid and packingtypeid = @intpackid
and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
End
Else
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty,
forsales, itemdescription  from aitem
where itemid = @intItemID
End
End
Else
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
Shopid is null and
currencyid = @intToCurrencyid
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and Shopid is null
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
Begin
if @intCash=1
Select round(( isnull(sellingprice,0) * @dblExRate),2)  SP,
round((isnull(DiscountPrice,0)*@dblExRate),2)  DP,
round((Isnull(WholeSalePrice,0)*@dblExRate), 2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
Shopid is null and packingtypeid = @intpackid
and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
Shopid is null and packingtypeid = @intpackid
and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
End
Else
Begin
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty,
forsales, itemdescription  from aitem
where itemid = @intitemID
End
End
End
End
SET NOCOUNT OFF
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spsellpriceCurrwise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spsellpriceCurrwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spsellpriceCurrwise
Script Date: 18/01/2003 9:45:45 PM ******/
--Modified By  : Hariharan R
--Modified Date: 21/12/2002
------------------------------------------------------------------------
--Ref:01
--Modified By : Nidheesh P v
--Modified on :18/02/2011
--Comments : The joining was not correct in the case for  @intSelcount<>0(segment wise)& @intCash=1(cash sale).
--So the query is just copied from the case  @intSelcount<>0 & @intCash=1
--and NOCOUNT is SET ON at the start and SET OFF at the end of the proc.
------------------------------------------------------------------------
CREATE proc [dbo].[spsellpriceCurrwise] @intcompanyid as int, @intshopid as int, @intitemid as int,
@intPackid as int, @intSegmentid as int=0, @intPricefixathq as int, @intcash as int,
@intToCurrencyid as int
as
declare @intselcount as int
declare @dblExRate as numeric(18,8)
declare @intCurrencyID as int
begin
SET NOCOUNT ON     --Ref:01
if @intSegmentid>0
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
segmentId = @intSegmentId and pricechanged = 0 and
currencyid = @intToCurrencyid
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and segmentId = @intSegmentId and pricechanged = 0
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
begin
if @intCash=1
Select round(isnull(SellingPrice,0) * @dblExRate,2)  SP,
round(isnull(DiscountPrice,0)*@dblExRate ,2) DP,
round(Isnull(WholeSalePrice,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription from     --Ref:01
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
segmentid = @intsegmentid and packingtypeid = @intpackid
and pricechanged = 0 and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription   from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
segmentid = @intsegmentid and packingtypeid = @intpackid
and pricechanged = 0 and sd.itemid = ai.itemid
and currencyid = @intCurrencyid
end
else
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty, forsales,
itemdescription  from aitem where itemid = @intItemid
End
end
else
Begin
if @intPricefixathq = 0
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
Shopid = @intShopid and pricechanged = 0 and
currencyid = @intToCurrencyid and isnull(segmentid,0)=0
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and Shopid = @intShopid and pricechanged = 0 and  isnull(segmentid,0)=0
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
Begin
if @intCash=1
Select round(isnull(SellingPrice,0) *@dblExRate,2)  SP,
round(isnull(DiscountPrice,0) * @dblExRate,2)  DP,
round(Isnull(WholeSalePrice,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid
and Shopid = @intShopid and packingtypeid = @intpackid
and pricechanged = 0  and ai.itemid = sd.itemid
and currencyid  = @intCurrencyid  and isnull(segmentid,0)=0
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid
and Shopid = @intShopid and packingtypeid = @intpackid
and pricechanged = 0 and sd.itemid = ai.itemid
and currencyid = @intCurrencyid  and  isnull(segmentid,0)=0
End
Else
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty,
forsales, itemdescription  from aitem
where itemid = @intItemID
End
End
Else
Begin
select @intselcount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
Shopid is null and pricechanged = 0 and
currencyid = @intToCurrencyid  and  isnull(segmentid,0)=0
if @intSelcount = 0
Begin
select @intCurrencyid = min(isnull(currencyid,0)) from
losshopitemshipmentdetail
where itemid = @intitemid and packingtypeid = @intpackid
and Shopid is null and pricechanged = 0
Select @dblExRate = t.sellingrate/f.Sellingrate
from exchangeratedetail t, exchangeratedetail f
where t.companyid = f.companyid and
f.currencyid = @intCurrencyid and
t.Currencyid = @intToCurrencyid
End
else
Begin
Set @intCurrencyid = @intToCurrencyid
Set @dblExRate     = 1
End
if @intCurrencyid >0
Begin
if @intCash=1
Select round(( isnull(sellingprice,0) * @dblExRate),2)  SP,
round((isnull(DiscountPrice,0)*@dblExRate),2)  DP,
round((Isnull(WholeSalePrice,0)*@dblExRate), 2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
Shopid is null and packingtypeid = @intpackid
and pricechanged = 0 and sd.itemid = ai.itemid
and currencyid = @intCurrencyid and  isnull(segmentid,0)=0
else
Select round(isnull(CreditSP,0)*@dblExRate,2) SP,
round(isnull(CreditDp,0)*@dblExRate,2)  DP,
round(Isnull(CreditWp,0)*@dblExRate,2) WP, isnull(dpQty,0) DpQty,
isnull(wpqty,0) WpQty, forsales, ai.itemdescription  from
losshopitemshipmentdetail sd, aitem ai where sd.itemid = @intitemid and
Shopid is null and packingtypeid = @intpackid
and pricechanged = 0 and sd.itemid = ai.itemid
and currencyid = @intCurrencyid  and  isnull(segmentid,0)=0
End
Else
Begin
Begin
Select 0 SP, 0 DP, 0 WP, 0 DpQty, 0 WpQty,
forsales, itemdescription  from aitem
where itemid = @intitemID
End
End
End
End
SET NOCOUNT OFF
End' 
END
GO
/****** Object:  View [dbo].[Vwbookingservicespartsforprint]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Vwbookingservicespartsforprint]'))
EXEC dbo.sp_executesql @statement = N'
--created by    :- Hariharan
--created date   :- 020826
--Modifed By      :- Dheena 04072003
-- add new Estimation fields like itemname ,inspectionno,date,bookslno,receivedfrom,machine,attendtime,currencysymbol,units
--------------------------------------------------------------------
--Modified on                   : 21/08/2003, 07/10/2003 ,28/06/2009
--Modified by                   : Reji Abraham, Hariharan R ,Sebin T.S
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
--    : Modified giving serbookhid to select
--    : Added Distinct to avoid repetitions of items
----------------------------------------------------------------
--Modified By Sreejith
--Modified on 20100922
--Added left outer join of ashops into the view to get the shopname for which the service is rendered
--select * from Vwbookingservicespartsforprint where bookingid=180
------------------------------------------------------------------------------
--RefNo:01
--Modified By : VinothMurugan V.
--Date    :  05/10/2010
--Purpose   : Adding Address
------------------------------------------------------------------------------
--RefNo:02
--Modified By : MANUNADH.U
--Date    :  01.10/2011
--Purpose   : Add Tax details for GST enabled Reports
------------------------------------------------------------------------------
CREATE view [dbo].[Vwbookingservicespartsforprint] as
select distinct serbkdcompanyid companyid,serbookhid bookingid,serbkdshopid shopid,sercode code,
sername description,serbkdchargetaken rate,serbkdcharge actrate,serbkdserviceqty qty,
serbkdcomments comments,''Services'' Type,sercallbkhno serbookhno,sercallbkhrecvdfrom serbookhrecvdfrom,
sercallbkhdate serbookhdate,cast(datepart(hh,sercallbkhtime)as varchar)+'':''+
cast(datepart(mi,sercallbkhtime)as varchar) +'':''+ cast(datepart(ss,sercallbkhtime)as varchar)bookingtime,
isnull(serbookhserviceamt,0.00) + isnull(serbookhpartscost,0.00) Estamt,serbookhpreparedby,
serbookadvanceamount,spername,serbookhdeldate,serbookhInspectionNo,serbookhInspectionDate,
serbookhinspectiontime,sercallbkhfuturevc serbookhfuturevc,sercallbkhslno serbookhslno,ai.ModelNo model,
isnull(CustomerName,shopname) sercustomername,UnitName,currencySymbol,serbookhEstExpiryDate,
sercallbkrefno serbookrefno,ai.Part_code, bh.serbookhcashacc,serbkdserviceqty packqty,''Each'' Pack,
los.sercallbkhItemId ,ai.itemcode,
--------------------------------------------------------------RefNo:01
case when sercallbkhcustomerid is null then shoplocation else address1 end address1,
case when sercallbkhcustomerid is null then '''' else address2 end address2,
case when sercallbkhcustomerid is null then address else address3 end address3
-----------------------------------------------------------
---------------RefNo:02------<<START>>
,isnull(serinvhTaxamount,0) serinvhTaxamount,serinvhTaxCateID,serinvhTaxPercentage TaxPercentage,
isnull(serbkdcharge,0) RateWithoutTax
, isnull(serbkdcharge + (serinvhTaxamount/serbkdserviceqty ),0)  RateWithTax
,isnull((serinvhTaxamount/serbkdserviceqty ),0) TaxRate
,(serbkdserviceqty * (
	case when serbkdcharge > (serbkdchargetaken-serinvhTaxamount) then serbkdcharge
	else ((serbkdchargetaken-serinvhTaxamount)/serbkdserviceqty) end
	))SubTotal
,case when serbkdcharge > (serbkdchargetaken - serinvhTaxamount)/serbkdserviceqty then
	--serbkdchargetaken rate,serbkdcharge actrate
	(serbkdcharge - ( serbkdchargetaken- (serinvhTaxamount/serbkdserviceqty)))*serbkdserviceqty
Else
0 end Discount
---------------RefNo:02------<<-END->>
from losbookservicedetails,aservicemaster m,losservicebookingheader bh
inner join loscallbookingheader los on los.serCallBkhid=serbookhrefid and
	los.serCallBkhcompanyid=bh.serbookhcompanyid and bh.serbookhshopid=los.serCallBkhshopid
left outer join
(
	select distinct bookingid,scompanyid,max(Symbol) currencySymbol,serbookhShopId from
	(
	  select serbookhid bookingid,serbookhcompanyid scompanyid,CurrencyID sercurrencyid,serbookhShopid
	  from losservicebookingheader,aaccountmaster
	  where serbookadvanceacc=accountid and serbookhcompanyid=companyid
	
	  union all
	  select serbookhid bookingid,serbookhcompanyid,CurrencyID,serbookhShopid
	  from losservicebookingheader bk ,loscallbookingheader los ,acustomermaster
	  where sercallbkhcustomerid=CustomerID and serbookhcompanyid=companyid and
		los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
		bk.serbookhshopid=los.serCallBkhshopid
	  union all
	  select serbookhid bookingid,serbookhcompanyid,depcurrencyid,serbookhShopid
	  from losservicebookingheader ,ashops s
		left outer join adepartmentmaster d  on s.DepartmentID=d.DepartmentID and s.CompanyID=d.CompanyID
	  where serbookhshopid=ShopID and serbookhcompanyid=s.companyid
	) as tempcurreny , acurrencymaster
	where sercurrencyid=currencyid and scompanyid=CompanyID
	group by scompanyid, bookingid,serbookhShopId
) as tempcurrencies on  bookingid=serbookhid and serbookhcompanyid=scompanyid and tempcurrencies.bookingid = bh.serbookhid
left outer join asalespersonmaster on bh.serbookhpreparedby=sperid
left outer join acustomermaster cu on sercallbkhcustomerid=cu.CustomerID and
	serbookhcompanyid=cu.CompanyID
left outer join ashops ash on serCallBkhCallShopID=ash.shopid and serbookhcompanyid=ash.CompanyID
left outer join aitem ai on sercallbkhitemid=ai.itemid
left outer join aunit u on ai.UnitsID=u.UnitID
where serbkdserviceid = serid and sercompanyid = serbkdcompanyid
and bh.serbookhid = serbkdbookid and
bh.serbookhshopid = serbkdshopid and serbookhcompanyid = serbkdcompanyid
--and los.serCallBkhshopid=3 and bookingid=3890     --<<TO BE COMMENTED>>
union all
select distinct repbkdsercompanyid,repbkdserbookid,repbkdshopid,itemcode,itemdescription,repbkdrate,
repbkdsellrate,repbkdqty,repbkdcomments,''Parts'' type,sercallbkhno serbookhno,
sercallbkhrecvdfrom serbookhrecvdfrom,sercallbkhdate serbookhdate,cast(datepart(hh,sercallbkhtime)as
varchar)+'':''+ cast(datepart(mi,sercallbkhtime)as varchar) +'':''+ cast(datepart(ss,sercallbkhtime) as
varchar)time,isnull(serbookhserviceamt,0.00) + isnull(serbookhpartscost,0.00) Estamt,serbookhpreparedby,
serbookadvanceamount,spername,serbookhdeldate,serbookhInspectionNo,serbookhInspectionDate,
serbookhinspectiontime,sercallbkhfuturevc serbookhfuturevc,sercallbkhslno serbookhslno,ModelNo,
isnull(CustomerName,shopname),UnitName,currencySymbol,serbookhEstExpiryDate,sercallbkrefno
serbookrefno,m.Part_code,bk.serbookhcashacc,repbkdpackqty,packingtypecode,los.sercallbkhItemId,
m.itemcode,
------------------------------------------------------------  --RefNo:01
case when sercallbkhcustomerid is null then shoplocation else address1 end address1,
case when sercallbkhcustomerid is null then '''' else address2 end address2,
case when sercallbkhcustomerid is null then address else address3 end address3
-----------------------------------------------------------
---------------RefNo:02------<<START>>
,isnull(repbkinvhTaxamount,0) repbkinvhTaxamount,repbkinvhTaxCateID,isnull(repbkinvhTaxPercentage,0) TaxPercentage,
isnull(repbkdrate-(repbkinvhTaxamount/repbkdpackqty ),0) RateWithoutTax
	,isnull((repbkdsellrate/repbkdpackqty) + (repbkinvhTaxamount/repbkdpackqty ),0)  RateWithTax
	,isnull((repbkinvhTaxamount/repbkdpackqty ),0) TaxRate
	,(repbkdpackqty * (
	case when repbkdsellrate > (repbkdrate-repbkinvhTaxamount) then repbkdsellrate
	else ((repbkdrate-repbkinvhTaxamount)/repbkdpackqty) end
	))SubTotal
,case when repbkdsellrate > (repbkdrate - repbkinvhTaxamount)/repbkdpackqty then
	--repbkdrate rate, repbkdsellrate actrate,
	(repbkdsellrate - (repbkdrate - (repbkinvhTaxamount / repbkdpackqty))) * repbkdpackqty
	else 0
end Discount
---------------RefNo:02------<<-END->>
from losbookpartsreplacedetails,aPackingType pk,aitem m
left outer join aunit u on m.UnitsID=UnitID, losservicebookingheader bk
inner join loscallbookingheader los on los.serCallBkhid=serbookhrefid and
	los.serCallBkhcompanyid=bk.serbookhcompanyid and bk.serbookhshopid=los.serCallBkhshopid
left outer join
(
	select distinct bookingid,scompanyid,max(Symbol) currencySymbol,serbookhShopId from
	(
	  select serbookhid bookingid,serbookhcompanyid scompanyid,CurrencyID sercurrencyid,serbookhShopid
	  from losservicebookingheader ,aaccountmaster
	  where serbookadvanceacc=accountid and serbookhcompanyid=companyid
	  union all
	  select serbookhid bookingid,serbookhcompanyid,CurrencyID,serbookhShopid
	  from losservicebookingheader bk,loscallbookingheader los,acustomermaster
	  where sercallbkhcustomerid=CustomerID and serbookhcompanyid=companyid and
		los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
		bk.serbookhshopid=los.serCallBkhshopid
	  union all
	  select serbookhid bookingid,serbookhcompanyid,depcurrencyid, serbookhShopid
	  from losservicebookingheader ,ashops s
	    left outer join adepartmentmaster d on s.DepartmentID=d.DepartmentID and s.CompanyID=d.CompanyID
	  where serbookhshopid=ShopID and serbookhcompanyid=s.companyid
	)as tempcurreny,acurrencymaster
	where sercurrencyid=currencyid and scompanyid=CompanyID
	group by scompanyid,bookingid,serbookhShopId
)as tempcurrencies on bookingid=bk.serbookhid and serbookhcompanyid=scompanyid and
	tempcurrencies.bookingid = bk.serbookhid
left outer join asalespersonmaster on serbookhpreparedby=sperid
left outer join acustomermaster cu on sercallbkhcustomerid=cu.CustomerID and serbookhcompanyid=cu.CompanyID
left outer join ashops ash on serCallBkhCallShopID=ash.shopid and serbookhcompanyid=ash.CompanyID
where repbkdserpartsid = itemid and repbkdsercompanyid = serbookhcompanyid and repbkdshopid =
bk.serbookhshopid and repbkdserbookid = bk.serbookhid and repbkdpackid = pk.packingtypeid
--and bk.serbookhShopid=3 and repbkdserbookid=3890 --<<TO BE COMMENTED>>'
GO
/****** Object:  View [dbo].[vwbookingserviceinvoicedtls]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingserviceinvoicedtls]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwbookingserviceinvoicedtls] as
-- currency sysmbol and customername
select
	li.serinvhcompanyid companyid, li.serinvhdepartmentid, li.serinvhshopid shopid,
	h.serinvhprocno,li.serinvhid Invoiceid, li.serinvno invoiceno,
	li.serinvhdate invoicedate, li.serinvhduedate,li.serinvhCustomerId customerid
	, li.serinvhamount ,0 as settled, "SBI" as type,
	isnull(li.serinvhrefno,'''') referenceno, isnull(li.serinvhremarks,'''') remarks,
	li.serinvhupdatetime,serinvhcmpexrate, li.serinvfinancialid ,
	case
		when li.serinvhcashacc is null then cur2.Symbol else
		cur1.Symbol end currencysymbol,
	customername, d.serbookhid,sercallbkhfuturevc serbookhfuturevc,
	isnull(serbookadvanceamount,0) advance, li.serinvhpartsamt, li.serinvhserviceamt
from
	losserviceinvheader li left outer join  losserviceheader h on
	li.serinvhjobcardid=h.serinvhid and li.serinvhshopid=h.serinvhshopid
	and li.serinvhcompanyid=h.serinvhcompanyid
	left outer join losservicebookingheader d on h.serinvhbookingid = d.serbookhid and
	h.serinvhshopid = d.serbookhshopid and h.serinvhcompanyid = d.serbookhcompanyid
	left outer join loscallbookingheader los on
	los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=d.serbookhcompanyid and
	d.serbookhshopid=los.serCallBkhshopid
	left outer join aaccountmaster acc on li.serInvhCashAcc=accountid
	and h.serinvhcompanyid=acc.companyid
	left outer join acurrencymaster cur1
	on acc.currencyid=cur1.currencyid and acc.companyid=cur1.companyid
	left outer join acustomermaster cu  on li.serinvhCustomerId=cu.customerid
	and li.serinvhcompanyid=cu.companyid
	left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
	and cu.companyid=cur2.companyid
where
	li.serinvhcancelled=0'
GO
/****** Object:  View [dbo].[vwbookingpartsreplaced]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingpartsreplaced]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwbookingpartsreplaced] as
select 	li.serinvhid, li.serinvhcompanyid, li.serinvhshopid, serinvhbookingid,
serinvhCustomerId serbookhcustomerid, repinvdpartsid,
itemdescription, repinvdrate, repinvdsellrate ,repinvpackqty, packingtypecode,repinvdType
from losServiceInvHeader li
left outer join
losinvoicedpartsreplacedetails bd on  li.serinvhcompanyid =  bd.repinvcompanyid and li.serinvhshopid = bd.repinvdshopid and
li.serinvhid = bd.repinvinvoiceid
, losserviceheader bh left outer join losservicebookingheader bkh
on bh.serinvhbookingid  = bkh.serbookhid  and bh.serinvhshopid  = bkh.serbookhshopid  and
serinvhcompanyid = serbookhcompanyid
, vwitemdescription v, apackingtype p
where  v.itemid = repinvdpartsid and
repinvpackid = p.packingtypeid  and
li.SerinvHjobCardId =  bh.serinvhID and li.serinvhShopid = bh.serinvhSHopid
and li.SerinvhCompanyId = bh.SerinvhCompanyid'
GO
/****** Object:  View [dbo].[vwbookingpartsneeded]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingpartsneeded]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY   : hariharan
--modified date : 12/06/2003
--Comments : Added qty field
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE VIEW [dbo].[vwbookingpartsneeded] as
-- CREATED for giving the services needed in one booking
-- to show in service booking slip report
select 	serbookhid, serbookhcompanyid, serbookhshopid, sercallbkhcustomerid serbookhcustomerid, repbkdserpartsid,
itemdescription, repbkdrate,  repbkdsellrate, repbkdpackqty, packingtypecode from losservicebookingheader bh,
losbookpartsreplacedetails bd, vwitemdescription v, apackingtype p,loscallbookingheader los where
bh.serbookhcompanyid =  bd.repbkdsercompanyid and bh.serbookhshopid = bd.repbkdshopid and
bh.serbookhid = bd.repbkdserbookid and v.itemid = repbkdserpartsid
and repbkdpackid = p.packingtypeid and los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid'
GO
/****** Object:  View [dbo].[vwbookingdetails]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookingdetails]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY   : hariharan
--modified date : 13/06/2003
--COmments 	: MOdified to get last diagonised technician
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE VIEW [dbo].[vwbookingdetails] as
select bk.*, vw.itemdescription, a.modelno,
a.brand, cast(datepart(hh,sercallbkhtime)as varchar)+'':''+
cast(datepart(mi,sercallbkhtime)as varchar) +'':''+
cast(datepart(ss,sercallbkhtime) as varchar) bookingtime, serbookhid bookingid,
serbookhshopid shopid, sertechid,  isnull(Spername, '''') diagonisedby  from
losservicebookingheader bk left outer join
(Select sertechcompanyid, sertechbookid, sertechshopid, sertechid from
losbookservtechniciandetails d1 where d1.sertechdetailid =
(Select max(d2.sertechdetailid) from losbookservtechniciandetails d2
where d1.sertechcompanyid = d2.sertechcompanyid and d1.sertechbookid = d2.sertechbookid
and  d1.sertechshopid = d2.sertechshopid)) tech on bk.serbookhid = tech.sertechbookid
and bk.serbookhShopid = tech.sertechShopid and bk.serbookhCompanyId = tech.sertechcompanyid
left outer join  asalespersonmaster sp on
tech.sertechid = sperid
inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid
, vwitemdescription vw, aitem a
where sercallbkhitemid = vw.itemid and vw.itemid = a.itemid'
GO
/****** Object:  View [dbo].[vwBillsCheckListInterDiv]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsCheckListInterDiv]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created By : Shine Das
On		   : 26.10.2010
Purpose	   : For Interdivision Bills. View has exact structure like
vwBillsCheckList. So Description copied from the view and changed tables Bills into
interdivisionbillsheader and billsdebitdetails into interdivisionbillsdetails.
*/
CREATE VIEW [dbo].[vwBillsCheckListInterDiv] AS
select b.companyid, b.BillsID, b.billsno, b.billdate, vm.VendorID, vm.vendorname,vreferenceno as vendorrefno,
b.referenceno, dateadd(dd,b.dueperiod,billdate) as duedate, b.remarks, b.posted, b.cancelled,
b.cashpurchase, b.chequeno, bacc.accountdesc bankname, exchangerate exchangerate, dacc.accountdesc as discountacchead, discount,
--acc.accountdesc,b.departmentid, dm.departmentname, bd.amount, depexrate, b.UpdateTime
acc.accountdesc,bd.departmentid, dm.departmentname, bd.amount, depexrate, b.UpdateTime
from interdivisionbillsheader b left outer join aaccountmaster bacc
on b.companyid = bacc.companyid and b.bankcashaccid = bacc.accountid left outer join aaccountmaster dacc
on b.companyid = dacc.companyid and b.discountaccountid = dacc.accountid, aVendorMaster vm, interdivisionbillsdetails bd,
adepartmentmaster dm, aaccountmaster acc
where b.companyid = vm.companyid and b.vendorid = vm.vendorid and b.companyid = bd.companyid and b.billsid = bd.billsid
and bd.companyid = acc.companyid and bd.accountid = acc.accountid and dm.companyid = bd.companyid and dm.departmentid = bd.departmentid
--and bd.companyid = acc.companyid and bd.accountid = acc.accountid and dm.companyid = bd.companyid and dm.departmentid = b.departmentid'
GO
/****** Object:  View [dbo].[vwBillsCheckList]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsCheckList]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on 	: 28/12/2002
-- Modified by 		: dheena
-- COMMENTS		: add departmentid
-----------------------------------------------------------
-- Modified on		: 21/06/2003
-- Modified by          : Kishore
-- Comments             : Added UpdateTime
-----------------------------------------------------------
CREATE VIEW [dbo].[vwBillsCheckList] AS
select b.companyid, b.BillsID, b.billsno, b.billdate,
vm.vendorname,vreferenceno as vendorrefno,
b.referenceno, dateadd(dd,b.dueperiod,billdate) as duedate,
b.remarks, b.posted, b.cancelled,
b.cashpurchase, b.chequeno, bacc.accountdesc bankname,
exchangerate exchangerate,
dacc.accountdesc as discountacchead, discount,
acc.accountdesc,b.departmentid, dm.departmentname, bd.amount,
depexrate, b.UpdateTime
from bills b left outer join aaccountmaster bacc
on b.companyid = bacc.companyid
and b.bankcashaccid = bacc.accountid
left outer join aaccountmaster dacc
on b.companyid = dacc.companyid
and b.discountaccountid = dacc.accountid, aVendorMaster vm,
billsdebitdetails bd,
adepartmentmaster dm, aaccountmaster acc
where b.companyid = vm.companyid
and b.vendorid = vm.vendorid
and b.companyid = bd.companyid
and b.billsid = bd.billsid
and bd.companyid = acc.companyid
and bd.accountid = acc.accountid
and dm.companyid = bd.companyid
and dm.departmentid = b.departmentid'
GO
/****** Object:  View [dbo].[vwbillswithcontrolaccs]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillswithcontrolaccs]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY  	: HARIHARAN
--MODIFIED DATE	: 24/01/2004
--COMMENTS	: modified to allow the population of bills in all dep corresponding
--		: to controlaccount removing the refjournalId check
CREATE view  [dbo].[vwbillswithcontrolaccs] as
--modified by venki 230603
--coment :-adding refjournalid condition
select h.BillsNo, h.BillsID, h.BillDate, h.Remarks,dep.departmentname,otherdepid,
maindepid, h.companyid, d.accountid, d.amount,0 credit, accountdesc  ,vendorid,exchangerates
from BillsDebitDetails d, bills h ,  adepcontrolaccounts ca,
adepartmentmaster dep, aaccountmaster a where h.companyid = d.companyid and
h.BillsID = d.BillsID and ca.companyid = d.companyid and ca.companyid=a.companyid and
ca.controlaccid = d.accountid and h.cancelled =0 and ca.controlaccid = a.accountid
and h.departmentid = dep.departmentid and h.departmentid<>maindepid
and ca.maindepid  not in
(select departmentid from
Journaltransheader where billid = h.billsid and cancelled = 0)'
GO
/****** Object:  View [dbo].[vwBillsWithControlAccounts]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillsWithControlAccounts]'))
EXEC dbo.sp_executesql @statement = N'
--created on 	: 10/03/2003, 03/11/2003
--Created by 	: R Harikrishnan, Hariharan
--Comments	: For accounts alerts, allowed to populate in mulitple depts
CREATE View [dbo].[vwBillsWithControlAccounts] as
select
	h.BillsNo, h.BillsID, h.BillDate, h.Remarks ,dep.departmentname,
	ca.maindepid, h.companyid, d.accountid, d.amount, 0 cr, a.accountdesc
from
	BillsDebitDetails d, Bills h ,  adepcontrolaccounts ca,
	adepartmentmaster dep, aaccountmaster a
where
	d.companyid = h.companyid and d.BillsID = h.BillsID and d.companyid = ca.companyid and
	d.AccountID = ca.controlaccid and d.accountid = a.accountid and
	h.CompanyID =dep.CompanyID and h.departmentid = dep.departmentid and h.departmentid <>
	ca.maindepid and h.cancelled =0
	--and h.RefJournalID is null
	and ca.maindepid  not in
	(select departmentid from
	Journaltransheader where billid = h.billsid and cancelled = 0
	union all
	select 0)'
GO
/****** Object:  View [dbo].[vwbookservicesneeded]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesneeded]'))
EXEC dbo.sp_executesql @statement = N'
--MODIEIFED BY : HARIHARAN
--modified date ; 12/06/2003
--Comments 	: quantity added
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE VIEW [dbo].[vwbookservicesneeded] as
-- CREATED for giving the services needed in one booking
-- to show in service booking slip report
select 	serbookhid, serbookhcompanyid, serbookhshopid, sercallbkhcustomerid serbookhcustomerid, serbkdserviceid,
sername, serbkdcharge, serbkdchargetaken,serbkdserviceqty from losservicebookingheader bh, loscallbookingheader los,
losbookservicedetails bd, aservicemaster v where bh.serbookhcompanyid =  bd.serbkdcompanyid
and bh.serbookhshopid = bd.serbkdshopid and bh.serbookhid = bd.serbkdbookid and
serbkdserviceid = serid and los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid'
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysis]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBudgetActualAnalysis]'))
EXEC dbo.sp_executesql @statement = N'
--Modified by : Hariharan
--Modifieed Date : 28/09/2003
CREATE view      [dbo].[vwBudgetActualAnalysis] as
select v.BudgetHead BudgetHead,v.badamount
BudgetAmount,d.bcdActualAmount UtilizedAmount,isnull((v.badamount-d.bcdActualAmount),0)
Variance,h.bchCheckNo,bchActualAsonDate VerPeriod,h.bchCheckDate VerDate,h.bchCheckedBy,
bchRemarks,h.bchCheckID,v.bahFromdate, v.bahToDate,v.budgetfromdate,v.budgettodate,
v.bahBudgetNo,v.bahBudgetAllocID,h.bchCompanyId, BudgetID  from vwBudgetAllocationDetails v,BudgetCheckHeader h,BudgetCheckDetail d
where v.bahCompanyID=h.bchCompanyId and v.bahBudgetAllocID=h.bchBudgetAllocID
and h.bchCompanyId=d.bcdCompanyID and h.bchCheckID=d.bcdCheckID and
v.badDetailID=d.bcdBudgetAllocdetailID and h.bchCancelled=0'
GO
/****** Object:  View [dbo].[vwbookservicesdone]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesdone]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwbookservicesdone] as
select 	li.serinvhid, li.serinvhcompanyid, li.serinvhshopid,
serinvhCustomerId serbookhcustomerid , serinvdserviceid,
sername, serinvdcharge, serinvdchargetaken,serinvdqty,serinvdType from LOsServiceInvHeader li,
losserviceheader bh
left outer join losservicebookingheader bkh
on bh.serinvhbookingid = bkh.serbookhid  and bh.serinvhshopid  = bkh.serbookhshopid
and bh.serinvhCompanyid = bkh.serbookhCompanyid
--- inner join loscallbookingheader los on
--los.serCallBkhid=serbookhrefid  and los.serCallBkhcompanyid=bkh.serbookhcompanyid and
--bkh.serbookhshopid=los.serCallBkhshopid,
,losinvoicedservicedetails bd, aservicemaster v where
li.serinvhcompanyid =  bd.serinvdcompanyid and li.serinvhid = bd.serinvdinvoiceid and
li.serinvhshopid = bd.serinvdshopid  and serinvdserviceid = serid
and li.SerinvHjobCardId =  bh.serinvhID and li.serinvhShopid = bh.serinvhSHopid
and li.SerinvhCompanyId = bh.SerinvhCompanyid'
GO
/****** Object:  View [dbo].[vwdatewisestockshop]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisestockshop]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 03/10/2002 5:06:32 PM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 31/07/2002 2:00:26 PM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 20/11/2001 9:58:56 AM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 17/11/2001 9:21:15 PM ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 09/03/2001 02:32:24 ******/
/****** Object:  View dbo.vwdatewisestockshop    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwdatewisestockshop] as
select shopid,itemid,stockdate,sum(openingstock) as openingstock, sum(stock) as closestock
from mosshopstock group by shopid,stockdate,itemid'
GO
/****** Object:  View [dbo].[vwdatewisestock]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisestock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwdatewisestock    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 03/10/2002 5:06:32 PM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 17/11/2001 9:21:19 PM ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 16/06/2001 15:36:31 ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 09/03/2001 02:32:24 ******/
/****** Object:  View dbo.vwdatewisestock    Script Date: 12/05/00 1:40:14 PM ******/
CREATE view [dbo].[vwdatewisestock] as
select gsgodownid,gsitemid,gsstockdate,sum(gsopeningstock) as openingstock, sum(gsstock) as closestock
from moigodownstock group by gsgodownid,gsstockdate,gsitemid'
GO
/****** Object:  View [dbo].[vwitemdesc]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemdesc]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwitemdesc] as
select a.pohpono,a.pohvendorid,b.poditemid,c.itemcode,c.itemdescription,1 ''type''
from lopurchaseorderheader a,lopurchaseorderdetail b ,aitem c
where a.pohpoid=b.podpoid and b.poditemid=c.itemid
union
select a.pohpono,a.pohvendorid,b.poditemid,d.vendoritemcode,d.vendoritemdesc,0 ''type''
from lopurchaseorderheader a,lopurchaseorderdetail b ,avendoritem d
where a.pohpoid=b.podpoid and (b.poditemid=d.itemid and a.pohvendorid=d.vendorid)'
GO
/****** Object:  View [dbo].[vwHPProcessingWithAllDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHPProcessingWithAllDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- View
------------
/*
Created by :  Shinu
Created on : 30/05/2008
Modified by : Regin
Modified on : 19-12-2008
Purpose      : To Get the Hire Purchase Processing Details (Invocie,Quotation,ItemRegistration,Processing)
	-- Regin added hphAmended field
*/
CREATE View [dbo].[vwHPProcessingWithAllDetails] As
select hpqhShopId,ShopName,InvoiceID,InvoiceNo,InvoiceDate,QuotationID,QuotationNo,QuotationDate,hpqdItemID,
ItemDescription,hpqdFrameNo,hpqdItemRegistrationID,hpAgreementID,hpAgreementNo,hpAgreementDate,IRShipment,
ColorName,SoldColor,IRFrameNo,IREngineNo,IRModelNo,IRCase,RegNo,IRRoadWorthiness,hpCustID,hpCustName,
hphDepartmentID,DepartmentName,hphProceSsingID,hphProcessingNo,hphProcessingDate,hphAmended,hphInvoiceID,hphFinancialID,
hphCancel,hphCashPrice,hphDownPayment,hphBalance,hphNoOfRentals,hphInterestRate,
hphInstallmentPrice,hphRentalAmount,hpdDetailID,hpdChequeDate,hpdCapital,hpdRental,hpdInterest,
hpdCapitalRepayment,hpdCapitalBalance,hpdBankName,hpdChequeNo,hpdAmount,hpdSettlementAmount,hpdInterestRate
from vwHPInvoiceDetails
Left Outer Join  vwHPAgreementDetails ON hpItemRegId=hpqdItemRegistrationID And hpQuotationID=QuotationID
And hpqdItemID=IRItemID And hpCancel=0
Left Outer Join Ashops ON ShopID=hpqhShopId
Left Outer Join vwHPProcessingDetails ON hphinvoiceID=InvoiceID And hphCancel=0'
GO
/****** Object:  View [dbo].[gdnstockout1]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gdnstockout1]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gdnstockout1    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 03/10/2002 5:06:31 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 17/11/2001 9:21:17 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 09/03/2001 02:32:26 ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 12/05/00 1:40:14 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 10/17/00 2:19:50 PM ******/
/****** Object:  View dbo.gdnstockout1    Script Date: 10/7/00 11:07:56 AM ******/
CREATE  view [dbo].[gdnstockout1] as
	select DISTINCT a.itemid,a.ItemReorderLevel,a.ReorderQuantity,
b.ItemDescription, b.itemrate,b.itemcode from agodowndetail a,aitem b
Where a.itemid = b.itemid and ItemReorderLevel >
	
	(select isnull(sum(gsstock),0) as stock from moigodownstock s left outer join
aGodowndetail c on c.itemid=s.gsitemid and s.gsstockdate=getdate())'
GO
/****** Object:  View [dbo].[gdnstockout]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gdnstockout]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gdnstockout    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 03/10/2002 5:06:31 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 20/11/2001 9:58:57 AM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 17/11/2001 9:21:17 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.gdnstockout    Script Date: 09/03/2001 02:32:26 ******/
/****** Object:  View dbo.gdnstockout    Script Date: 12/05/00 1:40:14 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 10/17/00 2:19:50 PM ******/
/****** Object:  View dbo.gdnstockout    Script Date: 10/7/00 11:07:56 AM ******/
CREATE  view [dbo].[gdnstockout] as
	select DISTINCT a.itemid,a.ItemReorderLevel,a.ReorderQuantity,
b.ItemDescription, b.itemrate,b.itemcode from agodowndetail a,aitem b
Where a.itemid = b.itemid and ItemReorderLevel >
	
	(select isnull(sum(gsstock),0) as stock from moigodownstock s left outer join
aGodowndetail c on c.itemid=s.gsitemid and s.gsstockdate=getdate())'
GO
/****** Object:  UserDefinedFunction [dbo].[fnHQPurchaseorder]    Script Date: 10/06/2012 14:17: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].[fnHQPurchaseorder]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
/*
Created By Sreejith
Created on 20100724
Purpose : To find the last done PO before each Purchase requests item wise
*/
--    select * from [dbo].[fnHQPurchaseorder]()
CREATE function [dbo].[fnHQPurchaseorder]()
returns @output  table
(
PurReqNo varchar(30),
itemid int,
PreviousPO varchar(30),
SupplierName  varchar(100),
LastItemRate numeric(18,2)
)
as
begin
declare @PO as varchar(30)
declare @itemID as numeric(18,2)
declare @intDepID as int
declare cur1 cursor for select  pohpoid,poditemid,pohdepartmentid from
(select d.poditemid,h.pohtype,h.pohPoid  , h.pohpono  , h.pohPodate ,d.podUnitPrice,h.pohdepartmentid
FROM lopurchaseorderdetail d inner join lopurchaseorderheader h
on h.pohpoid=podpoid) v
where v.pohtype=''R''
open  cur1
fetch next from cur1 into @PO,@itemID,@intDepID
while @@FETCH_STATUS = 0
begin
insert into @output select top 1.@PO,poditemid,pohpono,vendorname,podUnitPrice from
(select v.VendorName,d.poditemid, h.pohtype,h.pohPoid  , h.pohpono  , h.pohPodate ,d.podUnitPrice,h.pohdepartmentid
FROM lopurchaseorderdetail d
inner join lopurchaseorderheader h on h.pohpoid=podpoid
inner join avendormaster v on  v.VendorID=h.pohVendorID) v
where v.pohpoid<@PO and v.pohtype=''P'' and v.poditemid=@itemID
and (v.pohdepartmentid=@intDepID  or v.pohdepartmentid is null)
order by v.pohpoid desc
fetch next from cur1 into @PO,@itemID,@intDepID
end
close cur1
deallocate cur1
return
end' 
END
GO
/****** Object:  View [dbo].[vwposposamount]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposposamount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwposposamount    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwposposamount    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwposposamount    Script Date: 31/07/2002 2:00:29 PM ******/
/****** Object:  View dbo.vwposposamount    Script Date: 20/11/2001 9:59:00 AM ******/
/****** Object:  View dbo.vwposposamount    Script Date: 17/11/2001 9:21:33 PM ******/
/****** Object:  View dbo.vwposposamount    Script Date: 16/06/2001 15:36:32 ******/
/****** Object:  View dbo.vwposposamount    Script Date: 09/03/2001 02:32:27 ******/
/****** Object:  View dbo.vwposposamount    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwposposamount] as
select posh.poshcompanyid, posh.poshbillid,posh.poshShopID, sum(posd.posidunitprice) as itemamt
, isnull(sum(isnull(posoc.posoAmount,0)),0) as otheramt
from LOsPosHeader posh left outer join LOsPosSubItemDetail posd on
posh.poshBillID = posd.posidbillid and posh.poshShopID= posd.posidshopid
left outer join LOsPosOthercharges posoc on posh.poshBillID = posoc.posoBillID
and posh.poshShopID= posoc.posoShopID
group by posh.poshcompanyid, posh.poshbillid, posh.poshShopID'
GO
/****** Object:  View [dbo].[vwposout]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposout]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwposout    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwposout    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwposout    Script Date: 31/07/2002 2:00:29 PM ******/
CREATE view [dbo].[vwposout] as
select posidshopid,posidsubitemid,poshbilldate,sum(posidquantity) as posqtyout from losposheader,lospossubitemdetail
where poshshopid=posidshopid and poshbillid=posidbillid and poshcancelled=0
group by posidshopid,poshbilldate,posidsubitemid'
GO
/****** Object:  View [dbo].[vwfacilitytracking]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfacilitytracking]'))
EXEC dbo.sp_executesql @statement = N'
--created by dheena
--create date 21082003
--purpose :facility tracking details
CREATE view [dbo].[vwfacilitytracking] as
select ftTrackId,ftTrackNo,asp.spername checkinenterby,spm.spername checkoutenterby,
sername,Customername,ac.Address1+ac.Address2+ac.Address3 address,
ftCheckInTime,ftCheckOutTime,ftChectoutdate,ftTrackDate,ftcheckinRemark,ftcheckoutRemark from losfacilitytracking  a left outer join asalespersonmaster asp on
a.ftcheckinEnteredBy=asp.Sperid and a.ftCompanyId=asp.Companyid
left outer join asalespersonmaster spm on
a.ftcheckoutEnteredBy=spm.Sperid and a.ftCompanyId=spm.Companyid
left outer join aservicemaster  on a.ftFaclityID=serid
and a.ftCompanyId=sercompanyid
left outer join losapartmentagreementheader on
a.ftAgreementid=mghAgreementid and a.ftCompanyId=mghCompanyId
and a.ftShopid=mghShopId left outer join LosReservationHeader
on mghReservationID=rhreservationid and a.ftCompanyId=rhCompanyId
and a.ftShopid=rhShopId left outer join acustomermaster ac on rhcustomerid=ac.CustomerID
and rhcompanyid=ac.companyid  where ftcheckinCancelled=0'
GO
/****** Object:  View [dbo].[vwpendingbilldetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingbilldetails]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------
--created by dheena
--create date 04092003
--purpose pending bills details
--registered but not prepare Bill
CREATE view [dbo].[vwpendingbilldetails] as
select trhTransNo TransNo,trhDate Transdate,trhTransShopId shopid,
trhTransCompanyid companyid ,trhAgreementID agreementid,trhApartmentId apartmentid
,apdApartmentno apartmentNo,mghAgreementno agreementNo, ''Tenant Service'' type
from losapartmentagreementheader,losTenantServiceRegisterHeader
left outer join LosTenantServiceBilldetail on
trhTransCompanyid=tbdCompanyId and trhTransShopId=tbdShopId  and
tbdUtilityTransID is null,losapartmentdetail
where trhTransCompanyid=mghCompanyId and apdcompanyid=mghCompanyId
and apdShopid=mghShopId and trhApartmentId=apdApartmentid and
trhTransShopId=mghShopId and trhAgreementID=mghAgreementId and trhCancelled=0'
GO
/****** Object:  View [dbo].[vwpdcpayments]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpdcpayments]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 09/03/2003
--Modified by 		: R Harikrishnan
--Comments 		: v3
--Added Department ID
CREATE view [dbo].[vwpdcpayments] as
select
	jh.companyid, journaldate paymentdate, referenceno paymentno, ''op'' cbreferenceno,
	''opening'' payee, left(remarks,patindex(''%;%'',remarks)-1) as chequedetails,
	jd.amount , chequedate, jd.accountid bankcashid, case cancel when 1 then ''Yes'' else ''No'' end
	cancelled ,jd.DepartmentID
from
	moajournalheader jh, moajournaldetails jd
where
	jh.companyid = jd.companyid and jh.journalid = jd.journalid and
	financialid =0 and type =''p'' and journaldate <> chequedate and jd.journalcredit = 1
union all
select
	phCompanyID, phpaymentDate, phpaymentNo, phcbreferenceno, phpayee, phchequedetails,
	phamount, phchequedate, phbankcashid, case phcancelled when 1 then ''Yes'' else ''No'' end cancelled,
	phDepartmentID
from
	ahqpaymentvoucherheader
where
	phchequedate > phpaymentdate'
GO
/****** Object:  View [dbo].[vwpendingpoitems]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingpoitems]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on 	: 26/10/2002
--Modified by 		: leo
--Created  as second batch 0n 09/11/2002 by hariharan from fi-es10
--Modified by 		: venki 11/06/03 added department
CREATE view [dbo].[vwpendingpoitems] as
--for finding the items under waiting list to be received in the next shipment.
--only those items which are not processed in any bill should come here.
select podpoid, pohpono, pohpodate, itemcode, vw.itemdescription, podpackingtypeid,
packingtypename, poditemid, podUnitPrice, pohvendorid, podQty, poddescription, podstatusinfo,pohdepartmentid  from
lopurchaseorderheader, lopurchaseorderdetail, vwitemdescription vw,
apackingtype pk, aitem a where pohpoid = podpoid and pohcancel=0 and poditemid = vw.itemid
and podpackingtypeid = pk.packingtypeid and podstatus=''W'' and vw.itemid = a.itemid
and pohtype=''p'''
GO
/****** Object:  View [dbo].[vwpendingorderstilldate]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpendingorderstilldate]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwpendingorderstilldate    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--Last Modified on  : 10/06/03
--Modified by  : venki
--Comments  : v3 ,added department id also
-- jyothish added check poid exist in Bill 27-04-2010
CREATE view [dbo].[vwpendingorderstilldate] as
--for finding the items under waiting list to be received in the next shipment.
--only those items which are not processed in any bill should come here.
select case podstatus when ''w''  then ''Old Order'' else ''New Order'' end Type , vendorname,
podpoid, pohpono, pohpodate, itemcode, vw.itemdescription, podpackingtypeid,
packingtypename, poditemid, podUnitPrice, pohvendorid, podQty, poddescription,
podstatusinfo,pohdepartmentid
from lopurchaseorderheader, lopurchaseorderdetail, vwitemdescription vw,
apackingtype pk, aitem a, avendormaster v where pohpoid = podpoid and pohcancel=0 and
poditemid = vw.itemid and podpackingtypeid = pk.packingtypeid and
(podstatus=''W'' or podstatus is null) and vw.itemid = a.itemid and pohvendorid = v.vendorid
and pohtype = ''p''  and  podpoid   not in (  select pbhPOID  from losppurchasebillheader where pbhCancelled=0)'
GO
/****** Object:  View [dbo].[vwSellingFixAtHq]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingFixAtHq]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--------------------------------------------------------------------------------
-- Modified on   : 09/12/02
-- Modified by  : leo
--------------------------------------------------------------------------------
-- Modified on          : 26/06/2003
-- Modified by          : Kishore
-- Comments             : Added the checking ''aItemPackingDetail.Active = 1''
--------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 24/11/2003
-- Comments             : Removed the condition stock > 0
--------------------------------------------------------------------------------
-- Modified by          : Regin
-- Modified on          : 13-01-2010
-- Modification         : View was fine tuned to improve speed.
--                        1. join statement was used here.
--                        2. Not In was replaced by "left join"
--------------------------------------------------------------------------------
-- Modified by          : Regin
-- Modified on          : 13-01-2010
-- Comments             : Since checking stock is not a must, it was removed
--                        to speed up the process.
--------------------------------------------------------------------------------
--RefNo:01
-- Modified by          : Nidheesh P V
-- Modified on          : 24/02/2011
-- Comments             : check the condition segmentid is null
--------------------------------------------------------------------------------
CREATE view [dbo].[vwSellingFixAtHq] AS
select  a.itemid, p.Packingtypeid, p.PackingTypename,
b.ItemCode, b.itemcategoryid,
vid.ItemDescription, a.currencyid, max(a.sellingPrice) sellingPrice,
max(a.WholesalePrice) WholesalePrice,
max(a.discountPrice) discountprice
from losShopItemShipmentdetail a
inner join aitem b on a.itemid = b.itemid
inner join vwItemDescription vid on b.itemid = vid.itemid
inner join aitempackingdetail pd on a.itemid = pd.itemid
and a.packingtypeid = pd.packingtypeid
inner join apackingtype p on a.packingtypeid = p.packingtypeid
where
b.pricefixedatHQ = 1 and pd.active = 1 and segmentid is null   --RefNo:01
group by b.itemcategoryid, a.itemid,
b.itemcode, vid.ItemDescription ,p.Packingtypeid,
p.PackingTypename, a.currencyid
union all
select distinct a.itemid, p.PackingTypeID, p.PackingTypename,
i.itemcode , i.itemcategoryid,
vi.itemdescription, null, 0 sellingprice, 0 wholesaleprice, 0 discountprice
from ashopitemdetail a
inner join aitem i on a.itemid = i.itemid
--inner join vwsellingtotalstock vw on a.itemid=vw.itemid
inner join vwitemdescription vi on a.itemid=vi.itemid
inner join aitempackingdetail ipd on a.itemid=ipd.itemid
inner join apackingtype p on ipd.packingtypeid = p.packingtypeid
left join losShopitemShipmentDetail b on b.itemid = a.itemid
and (b.shopid = a.shopid or b.shopid is null)
and b.packingtypeid = ipd.packingtypeid
where
i.pricefixedathq = 1 and ipd.Active = 1
and b.itemid is null -- To select items not in losShopitemShipmentDetail'
GO
/****** Object:  View [dbo].[vwserbookconditions]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserbookconditions]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY 	: HARIHARAN
--MODIFIED DATE : 13/06/2003
CREATE VIEW [dbo].[vwserbookconditions] as
-- hari created for the booking slip report
select  cndserbookdid, cndserdshopid, cndserdcompanyid, prodcndcode, prodcndname,
prodcndcompanyid, prodcndid, prodcndsercatid, prodcnddetails, cndserbookdcomments
from losserconditiondetails scd, aproductconditionmaster pcm
where prodcndid = cndserid and prodcndcompanyid = cndserdcompanyid'
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking1]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking1]'))
EXEC dbo.sp_executesql @statement = N'
CREATE  view [dbo].[vwPurchaseOrderTracking1] as
select a.pohpoid,
case when a.pohrequestid is not null then mos.Grhrequestno end as ShopRequetNO,
case when a.pohquotationid is not null then ab.pohpono end as QuotationNo,case when a.pohprepurchaseid is not null then bc.pohpono end as PrePurchaseNo,ab.pohquotationid,a.pohprepurchaseid,ab.pohrequestid as PoRequestid,
case when a.pohshopid is not null then a.pohshopid else ab.pohshopid end as pohshopid
from loPurchaseOrderHeader a left outer join mosgoodsrequestheader mos on a.pohrequestid=mos.grhrequestid and a.pohshopid =mos.grhshopid
left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
left outer join loprePurchaseOrderHeader bc on a.pohprepurchaseid=bc.pohpoid
where  a.pohtype=''P'''
GO
/****** Object:  View [dbo].[vwMonthlyTenantutilityBills]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMonthlyTenantutilityBills]'))
EXEC dbo.sp_executesql @statement = N'
--created by dheena
--date 10012003
--purpose "Montly wise utility bill
CREATE view [dbo].[vwMonthlyTenantutilityBills] as
select
	tbhBillNo,tbhBillDate,datename(month,tbhBillDate) monthname,customername,mghAgreementno,mghAgreementDate
	,apdApartmentno,case when tbhBankCashID is null then  acu1.symbol
else acu.symbol end currencysymbol ,sername,utdFromDate,
	utdToDate,utdUnits,utdRate,utdAmount ,
	tbhShopId,serid,apdApartmentid,customerid
from losTenantServiceBillHeader
left outer join aAccountMaster ac on tbhBankCashID=AccountID
left outer join acurrencymaster acu on ac.CurrencyID=acu.currencyid
,losTenantUtilityBillDetail, acustomermaster c
left outer join acurrencymaster acu1 on c.CurrencyID=acu1.currencyid
,losApartmentAgreementHeader ,LOSApartmentDetail ,aservicemaster
where tbhBillId=utdBillId and tbhShopId=utdShopId and utdCompanyId=tbhCompanyId
and tbhCancelled=0 and tbhCustomerId=c.customerid and mghCompanyId=tbhCompanyId and
mghShopId=tbhShopId and  tbhAgreementId= mghAgreementid and mghCancelled=0
and apdApartmentid=mghApartmentId and mghCompanyId=apdcompanyid
and mghShopId=apdShopid and utdServiceId=serid and sercompanyid=utdCompanyId
Group by tbhBillNo,tbhBillDate,customername,mghAgreementno,mghAgreementDate
	,apdApartmentno,sername,utdFromDate,acu.symbol,acu1.symbol,
	utdToDate,utdUnits,utdRate,utdAmount ,
	tbhShopId,serid,tbhBankCashID ,apdApartmentid,customerid'
GO
/****** Object:  View [dbo].[vwCompanyExpiryAlertItems]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyExpiryAlertItems]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------
-- Created by	: Kishore
-- Created on	: 10/08/2003
-- Comments 	: This view lists items in stock which expire within
--                ExpiryNoOfDays (in aItem) from package date. Typically
--		  used to display alerts
---------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCompanyExpiryAlertItems] AS
SELECT b.itemid, vw.Code ItemCode, vw.ItemDescription,
b.ExpiryDate, b.qty Stock, vw.vwActive --, p.PackageDate, i.ExpiryNoOfDays, b.ExpiryDate
FROM (SELECT ExpiryDate, ItemId, SUM(qty) qty
	FROM (SELECT eadExpiryDate ExpiryDate,  eadGodownId GodownId,
		eadItemId ItemId , SUM(eadItemQty) qty
		FROM loiExpiryArrivalDetails
		WHERE eadCancel = 0
		GROUP BY eadExpiryDate, eadGodownId, eadItemId
		UNION ALL
		SELECT eidExpiryDate, eidGodownId, eidItemId, - SUM(eidItemQty)
		FROM loiExpiryIssueDetails
		WHERE eidCancel = 0
		GROUP BY eidExpiryDate, eidGodownId, eidItemId
		UNION ALL
		SELECT eadExpiryDate ExpiryDate,  eadShopId ShopId,
		eadItemId ItemId , SUM(eadItemQty) qty
		FROM losExpiryArrivalDetails
		WHERE eadCancel = 0
		GROUP BY eadExpiryDate, eadShopId, eadItemId
		UNION ALL
		SELECT eidExpiryDate, eidShopId, eidItemId, - SUM(eidItemQty)
		FROM losExpiryIssueDetails
		WHERE eidCancel = 0
		GROUP BY eidExpiryDate, eidShopId, eidItemId) a
	GROUP BY ExpiryDate, ItemId
	HAVING SUM(qty) <> 0 ) b,
vwItemDescription vw, aItem i, aPackageSettings p
WHERE b.ItemId = vw.ItemId
AND vw.ItemId = i.ItemId
AND p.PackageDate + i.ExpiryNoOfDays >= b.ExpiryDate
---------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwquotationtracking1]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking1]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwquotationtracking1] as
select a.pohpoid,
case when a.pohrequestid is not null then mos.Grhrequestno end as ShopRequetNO,
case when a.pohquotationid is not null then ab.pohpono end as HQRequestNo,ab.pohrequestid,ab.pohshopid
from loPurchaseOrderHeader a left outer join mosgoodsrequestheader mos on a.pohrequestid=mos.grhrequestid and a.pohshopid =mos.grhshopid
left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
where  a.pohtype=''Q'''
GO
/****** Object:  View [dbo].[vwQuotationBaseUnit]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuotationBaseUnit]'))
EXEC dbo.sp_executesql @statement = N'
--Purpose    	: For Forward Costing
--Created on 	: 06/11/2002
--Created by 	: Harikrishnan R
--Modified on 	: 04/03/2003, 29/12/2003, 10/03/2004
--Modified By 	: Harikrishnan R, Hariharan R
--Comments	: Itemcode added
CREATE view [dbo].[vwQuotationBaseUnit]
as
select
	a.podPoid,a.poditemid,(a.podQty*d.Quantity) as Quantity,
	(a.podUnitPrice/d.Quantity/f.cmpexrate)As BasePackTypePrice,a.podQty ,b.pohcompanyID,
	c.ItemDescription,c.costingvalue,(a.podUnitPrice/f.cmpexrate/d.Quantity) CompanyPrice,
	a.podUnitPrice VenCurUnitPrice,	e.vendorname,
	coalesce(g.CustomCategoryPercent,0) as CustomCategoryPercent,
	(a.podUnitPrice/f.cmpexrate) *g.CustomCategoryPercent*(a.podQty)/100
	as customsduty,	f.invSymbol,f.venSymbol, ItemCode, pohpono QuotNo
from
	loPurchaseOrderDetail a(nolock),loPurchaseOrderHeader b(nolock), aitem c(nolock),
	aPackingTypeCapacityDetail d(nolock),aVendorMaster e(nolock),vwcurrexrateagainstInventorycurr f(nolock),
	acustomsmaster g(nolock)
where
	a.podPoid = b.pohPoid and a.poditemid=c.itemid and
	a.podpackingtypeID=d.packingtypeID and c.unitsid=d.unitsid and
	b.pohVendorID=e.vendorid and b.pohcompanyID=e.companyid and
	e.CompanyID=f.CompanyID and e.CurrencyID=f.currencyid and
	c.CustomID *= g.CustomID and
	b.pohtype in (''Q'',''QP'')'
GO
/****** Object:  View [dbo].[vwPurchaseStatus]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseStatus]'))
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : SREEJITH G A
--CREATED ON : 20101110
--PURPOSE : TO CREATE PURCHASE STATUS REPORT
CREATE VIEW [dbo].[vwPurchaseStatus]
AS
SELECT R.POHPOID TransID, R.POHDEPARTMENTID PohDepartmentid,R.pohPodate ,R.POHPONO ReqNo,
Q.POHPONO QNo,PP.POHPONO PrePNo,PO.POHPONO PONo,PB.pbhBillDate PBdate,PB.PBHBILLNO,R.Pohtype ,
case when po.pohbillgenerated=1 then ''Bill Generated''
when po.POHPONO is not null then ''Purchase Order Done''
when PP.POHPONO is not null then ''Pre - Purchase Done''
when Q.POHPONO is not null then ''Quotation Done''
else ''Not Processed'' end    Status
FROM lopurchaseorderheader R
LEFT OUTER JOIN lopurchaseorderheader Q ON
R.POHPOID = Q.POHQUOTATIONID AND Q.pohcancel=0
LEFT OUTER JOIN loPrePurchaseOrderHeader PP
ON PP.POHQUOTATIONID=Q.POHPOID   AND pp.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader PO
ON ISNULL(PP.POHPOID,Q.POHPOID)=ISNULL(PO.POHPREPURCHASEID,PO.POHQUOTATIONID)  AND po.pohcancel=0
AND ISNULL(PP.pohDepartmentid,Q.pohDepartmentid)=ISNULL(PO.pohDepartmentid,PO.pohDepartmentid)
LEFT OUTER JOIN lospPurchaseBillHeader PB
ON PB.pbhPOID=PO.POHPOID AND PB.pbhDepartmentID=PO.POHDEPARTMENTID  AND pb.pbhCancelled=0
WHERE R.POHTYPE=''R''  and R.POHCANCEL=0
UNION ALL
SELECT Q.POHPOID , Q.POHDEPARTMENTID,Q.pohPodate,R.POHPONO ReqNo,
Q.POHPONO QNo,PP.POHPONO PrePNo,PO.POHPONO PONo,PB.pbhBillDate PBdate,PB.PBHBILLNO,Q.POHTYPE ,
case when po.pohbillgenerated=1 then ''Bill Generated''
when po.POHPONO is not null then ''Purchase Order Done''
when PP.POHPONO is not null then ''Pre - Purchase Done''
else ''Not Processed'' end    Status
FROM lopurchaseorderheader Q
LEFT OUTER JOIN lopurchaseorderheader R ON
R.POHPOID = Q.POHQUOTATIONID AND R.pohcancel=0
LEFT OUTER JOIN loPrePurchaseOrderHeader PP
ON PP.POHQUOTATIONID=Q.POHPOID AND PP.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader PO
ON ISNULL(PP.POHPOID,Q.POHPOID)=ISNULL(PO.POHPREPURCHASEID,PO.POHQUOTATIONID)  AND PO.pohcancel=0
AND ISNULL(PP.pohDepartmentid,Q.pohDepartmentid)=ISNULL(PO.pohDepartmentid,PO.pohDepartmentid)
LEFT OUTER JOIN lospPurchaseBillHeader PB
ON PB.pbhPOID=PO.POHPOID AND PB.pbhDepartmentID=PO.POHDEPARTMENTID   AND PB.pbhCancelled=0
WHERE Q.POHTYPE=''Q''   and Q.POHCANCEL=0
UNION ALL
SELECT PP.POHPOID , PP.POHDEPARTMENTID,PP.pohPodate,R.POHPONO ReqNo,
Q.POHPONO QNo,PP.POHPONO PrePNo,PO.POHPONO PONo,PB.pbhBillDate PBdate,PB.PBHBILLNO,PP.POHTYPE,
case when po.pohbillgenerated=1 then ''Bill Generated''
when po.POHPONO is not null then ''Purchase Order Done''
else ''Not Processed'' end    Status
FROM loPrePurchaseOrderHeader  PP
LEFT OUTER JOIN lopurchaseorderheader Q
ON PP.POHQUOTATIONID=Q.POHPOID    AND Q.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader R ON
R.POHPOID = Q.POHQUOTATIONID    AND R.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader PO
ON ISNULL(PP.POHPOID,Q.POHPOID)=ISNULL(PO.POHPREPURCHASEID,PO.POHQUOTATIONID) AND PO.pohcancel=0
AND ISNULL(PP.pohDepartmentid,Q.pohDepartmentid)=ISNULL(PO.pohDepartmentid,PO.pohDepartmentid)
LEFT OUTER JOIN lospPurchaseBillHeader PB
ON PB.pbhPOID=PO.POHPOID AND PB.pbhDepartmentID=PO.POHDEPARTMENTID AND PB.pbhCancelled=0
WHERE PP.POHTYPE=''PP''  and PP.POHCANCEL=0
UNION ALL
SELECT PO.POHPOID , PO.POHDEPARTMENTID,PO.pohPodate,R.POHPONO ReqNo,
Q.POHPONO QNo,PP.POHPONO PrePNo,PO.POHPONO PONo,PB.pbhBillDate PBdate,PB.PBHBILLNO,PO.POHTYPE  ,
case when PO.pohbillgenerated=1 then ''Bill Generated'' else ''Pending For Bill'' end    Status
FROM  lopurchaseorderheader PO
LEFT OUTER JOIN loPrePurchaseOrderHeader  PP
ON PP.POHPOID=PO.POHPREPURCHASEID  AND PP.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader Q
ON ISNULL(PP.POHQUOTATIONID,PO.POHQUOTATIONID)=Q.POHPOID  AND Q.pohcancel=0
LEFT OUTER JOIN lopurchaseorderheader R
ON R.POHPOID = Q.POHQUOTATIONID  AND R.pohcancel=0
AND PP.pohDepartmentid=PO.pohDepartmentid
LEFT OUTER JOIN lospPurchaseBillHeader PB
ON PB.pbhPOID=PO.POHPOID AND PB.pbhDepartmentID=PO.POHDEPARTMENTID AND PB.pbhCancelled=0
WHERE PO.POHTYPE=''P''  and PO.POHCANCEL=0'
GO
/****** Object:  View [dbo].[vwCompanyOpeningStock]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyOpeningStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Shinu
-- Created on  : 02/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Opening Stock of the Company
CREATE VIEW [dbo].[vwCompanyOpeningStock] AS
select CompStock.ItemID,isnull(Sum(CompStock.OpeningStock),0)OpeningStock,max(ItemCostPrice)ItemCostPrice  FROM
(SELECT ItemID,sum(OpeningStock)OpeningStock,max(ItemCostPrice)ItemCostPrice FROM mosShopStock group By ItemID
UNION ALL
SELECT gsItemID,sum(gsOpeningStock),max(gsItemCost) FROM moiGodownStock group By gsItemID) CompStock
GROUP BY CompStock.ItemID'
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingCompWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingCompWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by  :  Shinu
-- Created on  : 03/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Stock in a Shop
CREATE Proc [dbo].[spStockBalancingCompWise] @strFromDate as Varchar(10),@strToDate as Varchar(10),@intActive as int  AS
--declare  @strsql as nvarchar(4000)
--set @strFromDate = convert(datetime,@strFromDate,101)
--set @strToDate = convert(datetime,@strToDate,101)
Create Table #vwCompanyBincard(
itemid int,
opstock numeric(18,2)
)
Create Table #vwCompanyBincardForPeriod(
itemid int,
curstock numeric(18,2),
Type varchar(20)
)
Insert into #vwCompanyBincard select ItemID ,convert(numeric(18,3), sum(transqty * mode)) from
vwCompanyBincard where sDate<  @strFromDate group by itemid
Insert into #vwCompanyBincardForPeriod select ItemID ,convert(numeric(18,3), sum(transqty * mode)),Type from
vwCompanyBincard where sDate between @strFromDate And @strToDate group by itemid,Type
if @intActive=0
	 select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
		 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
		 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
		 from vwCompanyOpeningStock  group By itemid
		 union All
		 select itemid, sum(opStock) stock,0, 0, 0, 0 from #vwCompanyBincard group by itemid
		 union All
		 select itemid,0, sum(curstock) stock, 0, 0, 0 from #vwCompanyBincardForPeriod
		 where  Type in (''Local Purchase'',''Imports'') group by itemid
		 Union All
		 select itemid,0, 0, sum(curstock) stock, 0, 0 from #vwCompanyBincardForPeriod
		 where Type in (''Cash Sales'',''Credit Sales'',
		 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'') group by itemid
		 union All
		 select itemid,0, 0,0, sum(curstock) stock , 0 from #vwCompanyBincardForPeriod
		 where Type not in (''Cash Sales'',''Credit Sales'',
		 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'',''Local Purchase'',''Imports'') group by itemid
		 ) inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
else
	select ai.ItemID,ItemCode,ItemDescription,stock,Purchases,SalesStock,Adjustments,itemcostprice from (
		 select itemid, convert(numeric(18,3), sum(stock)) stock, sum(Purchases) Purchases, sum(SalesStock) SalesStock,
		 sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select itemid, isnull(sum(openingstock),0) stock,0 Purchases,0 SalesStock,0 Adjustments ,max(itemcostprice)itemcostprice
		 from vwCompanyOpeningStock  group By itemid
		 union All
		 select itemid, sum(opStock) stock,0, 0, 0, 0 from #vwCompanyBincard group by itemid
		 union All
		 select itemid,0, sum(curstock) stock, 0, 0, 0 from #vwCompanyBincardForPeriod
		 where  Type in (''Local Purchase'',''Imports'') group by itemid
		 Union All
		 select itemid,0, 0, sum(curstock) stock, 0, 0 from #vwCompanyBincardForPeriod
		 where Type in (''Cash Sales'',''Credit Sales'',
		 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'') group by itemid
		 union All
		 select itemid,0, 0,0, sum(curstock) stock , 0 from #vwCompanyBincardForPeriod
		 where Type not in (''Cash Sales'',''Credit Sales'',
		 ''Exchanged In'',''Exchange Out'',''Special Invoice Return'',''Local Purchase'',''Imports'') group by itemid
		 )inqstock group by itemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.ItemID=ai.ItemID
AND ai.Active=1' 
END
GO
/****** Object:  View [dbo].[vwHqPurchaseReturn]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseReturn]'))
EXEC dbo.sp_executesql @statement = N'
--Created 	: 26/06/2008
--Created by 	: Shinu
--Purpose	: For Purchase Returns Preview
-----------------------------------------------------------------------------------------------------------------------
--Modified  On	:
--Modified  By	:
--Comments	:
-----------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwHqPurchaseReturn] As
select PrhCompanyID,PrhReturnID,PrhReturnNo,prhReturnDate,prhVendorID,VendorName,
av.Address1,av.Address2,av.Address3,CurrencyName,Symbol,
prhRemarks,prhDepartmentID, DepartmentName,prdDetailID,prdItemID,Code ItemCode,ItemDescription,PrdQty,PrdCostPRice,PrdSuppAmount,
Case isnull(prhGodownID,0)when 0 then ''S'' else ''G'' End as LocType,
Case isnull(prhGodownID,0) when 0 then prhShopID else prhGodownID End as  LocID,
Case isnull(prhGodownID,0)when 0 then ShopName else GodownName End as LocName,prhWriteoffID,
Case isnull(prhGodownID,0) when 0 then los.WhNo else loi.WhNo  End as  ReferenceNo
From lopurchasereturnheader
Inner Join lopurchasereturnDetail ON prhCompanyID=prdCompanyID And PrhReturnID=PrdReturnID
Inner Join vwItemDescription ON prdItemID=ItemID
Left Outer join loiWriteOffHeader loi ON whGodownID=prhGodownID And loi.whID=prhWriteoffID
Left Outer join lospurchasereturnheader los ON whshopID=prhShopID And los.whID=prhWriteoffID
Inner Join (Select VendorID,vendorName,Address1,Address2,Address3,av1.CurrencyID,CurrencyName,Symbol From
		aVendorMaster av1 Inner Join aCurrencyMaster ac ON av1.CurrencyID=ac.CurrencyID) av ON vendorID=prhVendorID
Inner Join aDepartmentMaster ON  DepartmentID=prhDepartmentID
Left Outer Join aShops ON ShopID=prhShopID
Left Outer Join aGodown ON GodownID=prhGodownID'
GO
/****** Object:  View [dbo].[vwlosshopitemshipmentdetail]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosshopitemshipmentdetail]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwlosshopitemshipmentdetail] as
select S.*,H.* ,Ai.ItemRate,AI.unitsid
from aitem AI,vwAllshops S,losshopitemshipmentdetail H where
S.sid=isnull(H.shopid,0) and H.itemid=AI.itemid'
GO
/****** Object:  View [dbo].[vwlosShopItemShipment]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosShopItemShipment]'))
EXEC dbo.sp_executesql @statement = N'
--Created By  :AADYAKUMAR.D.V
--Created Date:14/07/2011
--Comment      :As Per client requrement if Selling price is fixed in HQ(Last),No need to show SP fixed in shop(before)
--             :Also this entries want remove from item_price_list report
CREATE view [dbo].[vwlosShopItemShipment] as
select a.* from losShopItemShipmentDetail a, aItem b  where
a.itemid=b.ItemID and  b.pricefixedathq=1  and a.shopid is null
union all
select a.* from losShopItemShipmentDetail a, aItem b  where
a.itemid=b.ItemID   and b.pricefixedathq=0  and a.shopid is not null'
GO
/****** Object:  View [dbo].[vwlosDebitCreditNote]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlosDebitCreditNote]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwlosDebitCreditNote] AS
select losDCNShopID,losDcnID,losDcnNo,losDcnDate,losDcnCustomerID,losdcnDebit,losDcnAmount,losDcnDetails,
losdcnRemarks,losdcnCancelled,losdcnCancelledRemarks,losReferenceNo,losdcnDepartmentID,losdcnType,
CustomerName,Address1,Address2,Address3,CurrencyID,CurrencyName,Symbol
from losDebitCreditNote
Inner Join (
	select CustomerID,CustomerName,Address1,Address2,Address3,acur.CurrencyID,CurrencyName,Symbol from acustomerMaster ac
	Inner Join aCurrencyMaster acur ON acur.CurrencyID=ac.CurrencyID) Cus
On cus.CustomerID=losDcnCustomerID
where isNull(losDcnCustomerID,0)<>0
Union All
select losDCNShopID,losDcnID,losDcnNo,losDcnDate,losDcnVendorID,losdcnDebit,losDcnAmount,losDcnDetails,
losdcnRemarks,losdcnCancelled,losdcnCancelledRemarks,losReferenceNo,losdcnDepartmentID,losdcnType,
VendorName,Address1,Address2,Address3,CurrencyID,CurrencyName,Symbol
from losDebitCreditNote
Inner Join (
	select VendorID,VendorName,Address1,Address2,Address3,acur.CurrencyID,CurrencyName,Symbol from aVendorMaster av
	Inner Join aCurrencyMaster acur ON acur.CurrencyID=av.CurrencyID) Ven
On ven.VendorID=losDcnVendorID
where isNull(losDcnVendorID,0)<>0'
GO
/****** Object:  View [dbo].[vwMagnolia_ServiceHistoryWeb]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwMagnolia_ServiceHistoryWeb]'))
EXEC dbo.sp_executesql @statement = N'
--Created By Sreejith on 18/03/2010
--select * from vwMagnolia_ServiceHistoryWeb  where refno=''YAM/SERP/10/1''id=1
--select * from vwMagnolia_ServiceHistoryWeb  where id=1 and cancel=0
--select * from loscallbookingheader
CREATE view [dbo].[vwMagnolia_ServiceHistoryWeb]
as
select serCallBkhid as Id,serCallBkhid as Tid,isnull(ac.CustomerName,'''') as FirstName,serCallBkhaddress as Address,
serCallBkhtelephone as PhoneNo,isnull(ash.shopname,'''') as ShopName,serCallBkhslno as slno,serCallBkhshopid as shopid,
serCallBkhcompanyid as companyid,
serCallBkhno as RefNo,serCallBkhdate as Date,''B'' as type,ast.serStatusName as status,serCallBkhinformedby as Contactname ,
serCallBkhenteredby as InCharge,serCallBkhcancelled as Cancel from loscallbookingheader
left outer join ashops ash on ash.shopid=serCallBkhCallShopID
left outer join acustomermaster ac on ac.customerid=serCallBkhcustomerid
left outer join aservicestatus ast on ast.serStatusID=serCallBkhStatusId
union all
select lc.serCallBkhid  as Id,serbookhid as Tid,isnull(ac.CustomerName,'''') as FirstName,lc.serCallBkhaddress as Address,
lc.serCallBkhtelephone as PhoneNo,isnull(ash.shopname,'''') as ShopName,lc.serCallBkhslno as slno,serbookhshopid as shopid,
serbookhcompanyid as companyid,
serbookhInspectionNo as RefNo,serbookhInspectionDate as Date,''E'' as type,ast.serStatusName as status,
lc.serCallBkhinformedby as Contactname,spm.Spername as InCharge ,serbookhinpcancelled as Cancel
from losservicebookingheader l
inner join loscallbookingheader lc on lc.serCallBkhid=l.serbookhRefId and lc.serCallBkhshopid=l.serbookhshopid
left outer join ashops ash on ash.shopid=lc.serCallBkhCallShopID
left outer join acustomermaster ac on ac.customerid=lc.serCallBkhcustomerid
left outer join aservicestatus ast on ast.serStatusID=lc.serCallBkhStatusId
inner join asalespersonmaster spm on l.serbookhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and l.serbookhshopid=spd.SperShopid
union all
select lc.serCallBkhid as Id,seaAppId as Tid,isnull(ac.CustomerName,'''') as FirstName,lc.serCallBkhaddress as Address,
lc.serCallBkhtelephone as PhoneNo,isnull(ash.shopname,'''') as ShopName,lc.serCallBkhslno as slno,seaAppShopId as shopid,
seaAppcompanyID as companyid,seaAppNo as RefNo,
seaAppDate as Date,''A'' as type,ast.serStatusName as status,lc.serCallBkhinformedby as Contactname,
seaApprovedBy as InCharge,seaAppCancelled as Cancel from losserestimateapproval la
inner join losservicebookingheader l on l.serbookhid=la.seaAppbookingId and l.serbookhshopid=la.seaAppShopId
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
left outer  join ashops ash on ash.shopid=lc.serCallBkhCallShopID
left outer join acustomermaster ac on ac.customerid=lc.serCallBkhcustomerid
left outer join aservicestatus ast on ast.serStatusID=lc.serCallBkhStatusId
union all
select lc.serCallBkhid as Id,serinvhid as Tid,isnull(ac.CustomerName,'''') as FirstName,lc.serCallBkhaddress as Address,
lc.serCallBkhtelephone as PhoneNo,isnull(ash.shopname,'''') as ShopName,lc.serCallBkhslno as slno,serinvhshopid as shopid,
serinvhcompanyid as companyid,
serinvhprocno as RefNo,serinvhprocdate as Date,''J'' as type,ast.serStatusName as status,lc.serCallBkhinformedby as Contactname,
spm.Spername as InCharge,serinvhjobinvcancelled as Cancel from losserviceheader lsh
inner join losservicebookingheader l on   lsh.serinvhbookingid = l.serbookhid  and lsh.serinvhshopid=l.serbookhshopid
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
left outer join ashops ash on ash.shopid=lc.serCallBkhCallShopID
left outer join acustomermaster ac on ac.customerid=lc.serCallBkhcustomerid
left outer join aservicestatus ast on ast.serStatusID=lc.serCallBkhStatusId
inner join asalespersonmaster spm on lsh.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lsh.serinvhshopid=spd.SperShopid
union all
select lc.serCallBkhid as Id,lih.serinvhid as Tid,isnull(ac.CustomerName,'''') as FirstName,lc.serCallBkhaddress as Address,
lc.serCallBkhtelephone as PhoneNo,isnull(ash.shopname,'''') as ShopName,lc.serCallBkhslno as slno,
lih.serinvhshopid as shopid,lih.serinvhcompanyid as companyid,
serinvno as RefNo,serinvhdate as Date,''I'' as type,ast.serStatusName as status,lc.serCallBkhinformedby as Contactname,
spm.Spername as InCharge,serinvhcancelled as Cancel from losserviceinvheader lih
inner join losserviceheader lsh on lsh.serinvhid=lih.serinvhjobcardid and lsh.serinvhshopid=lih.serinvhshopid
inner join losservicebookingheader l on   lsh.serinvhbookingid = l.serbookhid and lsh.serinvhshopid=l.serbookhshopid
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
left outer join ashops ash on ash.shopid=lc.serCallBkhCallShopID
left outer join acustomermaster ac on ac.customerid=lc.serCallBkhcustomerid
left outer join aservicestatus ast on ast.serStatusID=lc.serCallBkhStatusId
inner join asalespersonmaster spm on lih.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lih.serinvhshopid=spd.SperShopid'
GO
/****** Object:  View [dbo].[vwmachinesinstalled]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmachinesinstalled]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwmachinesinstalled]
as
select  sercallbkhinformedby,sercallbkhslno,sercallbkhrecvdfrom, sercallbkhcallclass,serCallBkhtelephone,isnull(serInvhfuturevc,sercallbkhfuturevc) product ,
li.serinvhcompanyid CompanyId,  li.SerinvhId InvoiceId, li.serinvhshopid ShopId,
serCode Code, SerName Description, serinvdcharge ActRate, serinvdchargetaken Rate,
serinvdqty Qty, serinvdcomments Comments, ''Services'' Type, SerInvNo, SerInvHDate,
SerInvHProcNo, SerInvHProcDate, cu.CustomerName serinvhcustname, li.SerInvHRefNo, li.SerInvHRemarks,
SerInvHBookingId, li.SerInvHItemName, li.SerInvHItemId, SerInvHDueDate, SerInvDQty PackQty,
isnull(serbookadvanceamount,0) BookingAdvance, aUnit.UnitCode, serInvhCashAcc ,
case when serInvhCashAcc is null then cur2.Symbol else
cur1.Symbol end currencysymbol,isnull(li.serinvhamount,0.00) amount
,sercallbkhdate serbookhdate,serbookhinspectiontime,aitem.ModelNo
,serinvhPaceofWork,li.serinvhmetereading,sercallbkrefno serbookrefno,aitem.Part_code,los.sercallbkhcustomerid ,
SercallBkhInstallation  from losserviceinvheader li inner join losserviceheader     on li.serinvhjobcardid=losserviceheader.serinvhid
and li.serinvhshopid=losserviceheader.serinvhshopid
and li.serinvhcompanyid=losserviceheader.serinvhcompanyid inner join losservicebookingheader bk on
li.serinvhshopid = serbookhshopid and  serinvhbookingid = serbookhid and
li.serinvhcompanyid = serbookhcompanyid inner join  loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid and SercallBkhInstallation=1 inner join losinvoicedservicedetails
on li.serinvhcompanyid = serinvdcompanyid and  li.serinvhshopid = serinvdshopid and
li.serinvhid = serinvdinvoiceid  Left Outer Join aservicemaster m
on serinvdserviceid = serid and  serinvdcompanyid = sercompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid
left outer join acustomermaster cu on li.serinvhCustomerId= cu.customerid
and li.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
, aItem , aUnit where losserviceheader.serinvhitemid = aItem.ItemId and
aItem.UnitsId = aUnit.UnitId and (m.SerCode IS NOT NULL or m.SerCode IS NOT NULL)
union all
select sercallbkhinformedby,sercallbkhslno,sercallbkhrecvdfrom, sercallbkhcallclass,serCallBkhtelephone,isnull(serInvhfuturevc,sercallbkhfuturevc) product, repinvcompanyid,  repinvinvoiceid, repinvdshopid, n.itemcode, n.itemdescription,
repinvdsellrate, repinvdrate, repinvdqty, repinvdcomments, ''Parts Replaced'',  serinvno,
serinvhdate, serinvhprocno, serinvhprocdate, li.serinvhcustname, li.SerInvHRefNo, li.serinvhremarks,
serinvhbookingid, li.serinvhitemname, li.serinvhitemid,serinvhduedate,repinvpackqty,
isnull(serbookadvanceamount,0) bookingadvance, aUnit.UnitCode,li.serinvhcashacc,
case when li.serinvhcashacc is null then cur2.Symbol else
cur1.Symbol end currencysymbol,isnull(li.serinvhamount,0.00) amount,
sercallbkhdate,serbookhinspectiontime,m.ModelNo model_no,serinvhPaceofWork,li.serinvhmetereading
,sercallbkrefno serbookrefno,m.Part_code,cu.customerid ,SercallBkhInstallation from losinvoicedpartsreplacedetails lps inner join losserviceinvheader li
on lps.repinvinvoiceid=li.serinvhid and repinvdshopid=li.serinvhshopid and repinvcompanyid=li.serinvhcompanyid
inner join  losserviceheader     on li.serinvhjobcardid=losserviceheader.serinvhid and losserviceheader.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=losserviceheader.serinvhcompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid inner join losservicebookingheader bk on li.serinvhshopid = serbookhshopid
and serinvhbookingid = serbookhid and li.serinvhcompanyid = serbookhcompanyid
inner  join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid
left outer join acustomermaster cu on li.serinvhCustomerId= cu.customerid
and li.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
, aitem m, aItem n, aUnit
where repinvdpartsid = n.itemid and losServiceHeader.serInvhItemId = m.ItemId
and m.UnitsId = aUnit.UnitId'
GO
/****** Object:  View [dbo].[vwmachinerepairegister]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmachinerepairegister]'))
EXEC dbo.sp_executesql @statement = N'
--MOdified By	: Hariharan
--Modified Date	: 16/03/2004
CREATE view [dbo].[vwmachinerepairegister]
as
select serCallBkhcompanyid, serCallBkhshopid,serbookhInspectionDate,
c.customername,serCallBkhCallType ,serinvhprocdate,serinvhduedate,sercallbkhstatus,
serbookhinspectiontime,sercallbkhslno,isnull(serinvhcompleted,0) serinvhcompleted ,serCallBkhdate,
sercallbkhcancelled, serCallBkhNo, serbookhInspectionNo, seaAppNo, serinvhprocno, serinvno,
seaAppDate, serinvHDate, serCallBkhrecvdfrom, isnull(serinvhToInvoice,0) serinvhToInvoice
from loscallbookingheader los   left outer join losservicebookingheader bh  on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
los.serCallBkhshopid=bh.serbookhshopid and 0 = bh.serbookhinpcancelled
left outer join losserestimateapproval ap on bh.serbookhid=ap.seaAppbookingId and
bh.serbookhshopid=seaAppShopId  and bh.serbookhCompanyid = seaAppcompanyID
and 0=seaAppCancelled
left outer join losserviceheader sh on bh.serbookhid = sh.serinvhbookingid  and
bh.serbookhshopid=sh.serinvhshopid  and bh.serbookhcompanyid = sh.serinvhcompanyid
and 0 = sh.serinvhjobinvcancelled
left outer join  losserviceinvheader li on  li.serinvhjobcardid=sh.serinvhid and
li.serinvhshopid=sh.serinvhshopid and li.serinvhcompanyid=sh.serinvhcompanyid
and 0 = li.serinvhcancelled
left outer join acustomermaster c on li.serinvhCustomerId= c.customerid
and li.serinvhcompanyid = c.companyid, ashops s, aitem a, vwitemdescription v where
los.sercallbkhitemid = a.itemid and a.itemid = v.itemid and LOS.serCallbkhshopid = s.shopid
and los.sercallbkhcancelled =0'
GO
/****** Object:  View [dbo].[vwShopItemShipmentDetailSegmentWise]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemShipmentDetailSegmentWise]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created By  : Shinu
-- Created On  : 04052008
-- Comments    : For Fetching Items Based on Segment
--
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopItemShipmentDetailSegmentWise]
AS
Select currencyid, itemid, shopid,packingtypeid,
sellingprice,wholesaleprice,discountprice,SegmentID
from losshopitemshipmentdetail
where shopid is not null and SegmentId is not Null
union all
select currencyid, sd.itemid, s.shopid, sd.packingtypeid,
sd.sellingprice, sd.wholesaleprice, sd.discountprice,sd.SegmentID
from losshopitemshipmentdetail sd, ashops s
where sd.shopid is null and sd.SegmentId is not Null'
GO
/****** Object:  View [dbo].[vwshopitemshipmentdetailPU]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemshipmentdetailPU]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last modified on 	: 13/12/02, 17/12/2003
--modified by		: leo, Hariharan R
--comments 		: v3
--			: Given grouping as there is chance of same item having entry in
--			: losshopitemshipmentdetail table with shopid not null and null values
--			: which will lead to duplication of records in reports
CREATE view [dbo].[vwshopitemshipmentdetailPU]
as
select PU.itemid, PU.shopid, PU.packingtypeid, PU.currencyid, min(pu.sellingprice) sellingprice,
min(pu.wholesaleprice) wholesaleprice, min(pu.discountprice) discountprice from
(select sd.itemid, sd.shopid, sd.packingtypeid, sd.currencyid, sd.sellingprice,
sd.wholesaleprice, sd.discountprice from losshopitemshipmentdetail sd, vwitemretailpacking rp
where shopid is not null and sd.itemid = rp.itemid and sd.packingtypeid = rp.packingtypeid
union all
select sd.itemid, s.shopid, sd.packingtypeid, sd.currencyid, sd.sellingprice, sd.wholesaleprice,
sd.discountprice  from losshopitemshipmentdetail sd, ashops s, vwitemretailpacking rp
where sd.shopid is null and sd.itemid = rp.itemid and sd.packingtypeid = rp.packingtypeid)
PU
group by itemid, shopid,packingtypeid, currencyid'
GO
/****** Object:  View [dbo].[vwshopwisevalue]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopwisevalue]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopwisevalue    Script Date: 18/01/2003 9:45:42 PM ******/
--Modified By	: Hariharan
--Modified Date : 16/10/2002
--included convert function and replaced mosshopstock with vwinquiryshopstock
--verified by   : leo
--verified on   : 16/10/2002
CREATE view [dbo].[vwshopwisevalue] as
select "All Outlets" as svalue, sh.shopname, s.itemid, a.itemcode, S.shopid, vw.itemdescription,
a.itemdescription itemdesc, convert(numeric(18, 3), sum(isnull(s.stock,0))) stock,
itemrate * (1+(RevisedCostPricePercent/100)) cost,
sum(isnull(s.stock,0))* itemrate * (1+(RevisedCostPricePercent/100)) as stockvalue,
convert(numeric(18, 2), avg(isnull(sd.sellingprice,0))) salesprice,
convert(numeric(18,2), avg(isnull(sd.sellingprice,0)) * sum(isnull(s.stock,0)))  salevalue,
convert(numeric(18,2), isnull(sd.wholesaleprice,0)) wholesaleprice,
convert(numeric(18,2), isnull(sd.discountprice,0) )
discountprice, max(isnull(billmessage,shopname)) shopcategory  from vwinquiryshopstock s
left outer join vwitemdescription vw on s.itemid=vw.itemid
left outer join aitem a on s.itemid=a.itemid
left outer join vwshopitemshipmentdetailpu sd on s.itemid=sd.itemid and s.shopid=sd.shopid ,
ashops sh where sh.shopid=s.shopid group by   shopname ,s.shopid,a.itemcode, vw.itemdescription,
s.itemid, a.itemdescription, itemrate, sd.sellingprice, sd.wholesaleprice, sd.discountprice,
RevisedCostPricePercent having sum(isnull(s.stock,0))>0'
GO
/****** Object:  View [dbo].[vwShopInventoryValue]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInventoryValue]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on	: 13/12/02, 26/04/2004
--Modified by		: leo, Hariharan R
--Comments		: v3, GIven stock <> 0 condition instead of Stock >0
--Verified by 	    	: Hariharan
--Verified Date     	: 04/05/2004 (verified From Dev Server(Fies))
CREATE VIEW [dbo].[vwShopInventoryValue] AS
select distinct(s.itemid), S.shopid, vw.itemdescription, a.itemdescription itemdesc,
CONVERt(numeric(18,3), sum(isnull(s.stock,0))) stock,
itemrate cost, sum(isnull(s.stock,0))* itemrate as stockvalue,
avg(isnull(sd.sellingprice,0)) salesprice, avg(isnull(sd.sellingprice,0)) * sum(isnull(s.stock,0))  salevalue,
isnull(sd.wholesaleprice,0) wholesaleprice, isnull(sd.discountprice,0)
discountprice,vw.vunitcode unitcode from vwinquiryshopstock s
left outer join vwitemdescription vw on s.itemid=vw.itemid
left outer join aitem a on s.itemid=a.itemid
left outer join vwshopitemshipmentdetailPU  sd on s.itemid=sd.itemid
and s.shopid=sd.shopid and currencyid =(select currencyid from aaccountmaster where accountid =
(select InventoryID from apackagesettings))
group by vw.itemdescription, s.itemid, a.itemdescription,s.shopid, itemrate, sd.sellingprice,
sd.wholesaleprice, sd.discountprice,vw.vunitcode having sum(isnull(s.stock,0))<>0'
GO
/****** Object:  View [dbo].[vwPandCInquiryUnprocessedStock]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryUnprocessedStock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sppandcinquiryunprocessedstock    Script Date: 18/01/2003 9:45:49 PM ******/
-- Created On : 09/06/2006
-- Created By : Aneesh
Create View [dbo].[vwPandCInquiryUnprocessedStock] As
Select s.itemid,Sum(transqty) As Totalstock,  Max(sellingprice) sellingprice,
Max(wholesaleprice) wholesaleprice, Max(discountprice) discountprice, type, fromlocation,
tolocation, processtype From vwquantityunprocessed s,  (Select Min(sellingprice) sellingprice,
Min(wholesaleprice) wholesaleprice, Min(Discountprice) Discountprice, itemid From
vwshopitemshipmentdetailpu Group By itemid) vd, aitem ai Where vd.itemid = s.itemid
and ai.itemid=s.itemid  GROUP BY s.itemid, type, fromlocation, tolocation, processtype'
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryunprocessedstock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquiryunprocessedstock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sppandcinquiryunprocessedstock    Script Date: 18/01/2003 9:45:49 PM ******/
-- created on	: 22/10/2002
-- Created by	: leo
CREATE proc [dbo].[sppandcinquiryunprocessedstock] @intitemid as int as
select sum(transqty) as Totalstock,  max(sellingprice) sellingprice,
max(wholesaleprice) wholesaleprice, max(discountprice) discountprice, type, fromlocation,
tolocation, processtype from vwquantityunprocessed s,  (select min(sellingprice) sellingprice,
min(wholesaleprice) wholesaleprice, min(Discountprice) Discountprice, itemid from
vwshopitemshipmentdetailpu group by itemid) vd, aitem ai where s.itemid= @intitemid and
vd.itemid = s.itemid and ai.itemid=s.itemid  GROUP BY s.itemid, type, fromlocation, tolocation,
processtype' 
END
GO
/****** Object:  View [dbo].[vwshopitemshipmentdetailcompany]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemshipmentdetailcompany]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopitemshipmentdetailcompany    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshopitemshipmentdetailcompany]
as
select currencyid, itemid, packingtypeid,sellingprice,wholesaleprice,discountprice from losshopitemshipmentdetail
where shopid is null
union all
select currencyid, sd.itemid, packingtypeid, max(sd.sellingprice) sellingprice, max(sd.wholesaleprice) wholesaleprice,
max(sd.discountprice ) discountprice  from losshopitemshipmentdetail sd where sd.shopid is not null
group by currencyid, sd.itemid, sd.packingtypeid'
GO
/****** Object:  View [dbo].[vwShopPendingRequestsForPo]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPendingRequestsForPo]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on 		: 04/01/2003
-- Modified by 		: Hariharan R
-- Comments		: v3
-----------------------------------------------------------------------------
-- Modified on		: 30/09/2003
-- Modified by		: Kishore
-- Comments		: Added item id in left outer join with po
-----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopPendingRequestsForPo] as
select podStatus, ShopName, grhShopId, a.ItemId, grhRequestId,
grhRequestNo, grhRequestDate, a.ItemCode,
vw.ItemDescription, grdGoodQty, grdReqComments,
grdReqOrderStat, grdExpectRemarks, grhRemarks
from mosgoodsrequestheader ,
mosgoodsrequestdetail left outer join
	(select podpoid, poditemid, podstatus, pohrequestid, pohshopid
	from lopurchaseorderheader,
	lopurchaseorderdetail
	where pohpoid = podpoid
	and pohcancel=0) po
on grdrequestid = po.pohrequestid
and grdshopid = po.pohshopid
and grdItemId = po.podItemId, aitem a,
vwitemdescription vw, ashops s
where grhrequestid = grdrequestid
and grhshopid = grdshopid
and grhcancel = 0
and grhrequesttype = ''p''
and grditemid = a.itemid
and a.itemid = vw.itemid
and grhshopid = s.shopid
and isnull(po.podstatus, '''') <> ''r''
--order by grhShopId, grhRequestNo, a.ItemId'
GO
/****** Object:  StoredProcedure [dbo].[spcustomerwiseservices]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomerwiseservices]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spcustomerwiseservices] ( @fromdate as varchar(12), @todate as varchar(12)) as
declare @dtfromdate as datetime
declare @dttodate as datetime
set @dtfromdate = convert(datetime, @fromdate,101 )
set @dttodate =  convert(datetime, @todate,101 )
--view created for taking the total quantity of items serviced
--customer wise
/*select count(sercallbkhcustomerid) nooftimes, serbookhshopid, serbookhcompanyid,
c.customername, customercardno from losservicebookingheader bh , ashops s,
acustomermaster c, losserviceheader sh , loscallbookingheader los,losserviceinvheader li   where
los.sercallbkhcustomerid = c.customerid and bh.serbookhshopid = s.shopid
and bh.serbookhinvoiced=1 and los.sercallbkhcancelled=0 and sh.serinvhbookingid = bh.serbookhid
and sh.serinvhshopid = bh.serbookhshopid and sh.serinvhcompanyid = bh.serbookhcompanyid
and serinvhdate >= @dtfromdate and serinvhdate <= @dttodate and  los.serCallBkhid=serbookhrefid
and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid  and sh.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=sh.serinvhcompanyid where
group by serbookhshopid,
serbookhcompanyid,sercallbkhcustomerid ,serbookhcompanyid, c.customername, customercardno*/
select count(serinvhCustomerId)nooftimes,lih.serinvhcompanyid serbookhcompanyid,
lih.serinvhshopid serbookhshopid,c.customername,customercardno   from losserviceinvheader lih,ashops s ,
acustomermaster c,losserviceheader lsh where
serinvhCustomerId= c.customerid and lih.serinvhshopid=lsh.serinvhshopid and
lih.serinvhcompanyid=lsh.serinvhcompanyid and lih.serinvhshopid=s.shopid
and lih.serinvhjobcardid=lsh.serinvhid and lih.serinvhcancelled=0 and
lih.serinvhdate >= @dtfromdate and lih.serinvhdate <= @dttodate
group by lih.serinvhcompanyid,lih.serinvhshopid,c.customername ,customercardno' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerCreditLimitExceeds]    Script Date: 10/06/2012 14:17: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].[spCustomerCreditLimitExceeds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------
--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' 
END
GO
/****** Object:  View [dbo].[vwHqPurchaseBills]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseBills]'))
EXEC dbo.sp_executesql @statement = N'
-- modified by   : Hariharan
-- modified Date : 18/09/2002
----------------------------------------------------------------------------------
-- Modified by   : Kishore
-- Modified on   : 22/09/2003
-- Comments      : Changed pbhAmountCalculation to pbhbillamount + pbhLcAmount
----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwHqPurchaseBills] AS
SELECT pbhCompanyId, pbhDepartmentID, pbhBillId,
pbhBillNo, pbhVendorRefNo, pbhBillDate,
pbhDueDateForPayment pbhDueDate, pbhVendorId,
pbhBillAmount /* + pbhLcAmount */ pbhAmount,
0 AS PaidAmount
FROM lospPurchaseBillHeader
WHERE pbhcancelled = 0
AND pbhsettled = 0
AND pbhCashpurchase = 0'
GO
/****** Object:  View [dbo].[vwHqprePurchaseOrder]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqprePurchaseOrder]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------
--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
/****** Object:  View [dbo].[vwHQSerinvoice]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQSerinvoice]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------
--Ref.No.1
--Modified on :22-11-2011
--Modified by :AADYAKUMAR D V
--Added tax to Account service invoice a condition to solve duplication in reports
----------------------------------------------------------------------------------------
CREATE view [dbo].[vwHQSerinvoice] as
select h.companyid companyid,h.invoiceid invoiceid, h.departmentid,
h.invoiceno invoiceno, h.invoicedate invoicedate, dateadd(day,dueperiod,invoicedate) duedate,
h.customerid customerid,
sum(d.serviceqty*d.amount)- h.discount+isnull(h.TaxAmount,0) Amount ,0 as settled, ''HQ'' as type  ,ReferenceNo
from accountsinvoiceheader h , serviceinvoicedetails d where
h.invoiceid = d.invoiceid and h.cancelled=0 and proforma=0 and cashinvoice =0
group by h.companyid, h.departmentid, h.invoiceid, h.invoiceno, h.invoicedate,
h.customerid, h.dueperiod, h.discount,ReferenceNo,h.TaxAmount'
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder1]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder1]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwHqPurchaseOrder1] 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,h.pohshipmentmode,h.pohpaymentmode,
convert(varchar(250),h.pohDeliveryTerms)pohdeliveryterms, pohProjectStartDate,
pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel
FROM lopurchaseorderheader h,lopurchaseorderdetail 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 vw.vendorid=h.pohvendorid'
GO
/****** Object:  View [dbo].[vwAllUsers]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAllUsers]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwAllUsers]
as
select ausers.userid,ausers.username,ausers.companyid,ausers.userpwd,ausers.shopid,ausers.godownid from ausers union
select lousers.userid,lousers.username,lousers.companyid,lousers.userpwd,lousers.shopid,lousers.godownid from lousers'
GO
/****** Object:  View [dbo].[gmlevelfour]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[gmlevelfour]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.gmlevelfour    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
CREATE view [dbo].[gmlevelfour] as
select gm.groupid, gm.parentgroupid, gm3.levelgm + 1 levelgm from agroupmaster gm,
gmlevelthree gm3
where gm.parentgroupid = gm3.groupid'
GO
/****** Object:  StoredProcedure [dbo].[sphpCustomerReconcilation]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpCustomerReconcilation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec sphpCustomerReconcilation ''20090209'',''1399''--,859,855,562,852''
--------------------------------------------------
--Created BY  : Prasanth Joseph
--Created on  : 24-01-2009
--Created For : To get Customer balnce against processing
--Modified By :
--Modified on :
---------------------------------------------------
CREATE   Procedure [dbo].[sphpCustomerReconcilation] @asondate as varchar(25),
@strCustomerID as varchar(8000) as
set nocount on
--drop table #tempCustomer
CREATE table #tempCustomer
(
CustomerID int
)
--drop table #tempData
CREATE table #tempData(
CustomerID  int,
Customername nvarchar(200),
ProcessingID int,
status nvarchar(10),
ProcessingNo nvarchar(200),
AgreementNO  nvarchar(200),
CustomerBalance numeric(20),
AdvanceAmount  numeric(20),
ReturnChequeAmount numeric(20),
SettledAmount  numeric(20),
PaymentAmount numeric(20),
UnernedFinIncome numeric(18),
AdjustmentAmount numeric(18))
--declare  @asondate as nvarchar(20),
--@strCustomerID as nvarchar(200)
--set @asondate=''20070501''
--set @strCustomerID=''759,859,855,562,852''
DECLARE @intProcessingID as int
DECLARE @intCustomerid as int
DECLARE @strSql as nvarchar(1000)
DECLARE @CustomerBalance as numeric(20)
Begin
insert into #tempCustomer select cid from fnSplit(@strCustomerID,'','')
--set @strSql=''declare opcurt cursor for
--       select hphProcessingID,hphCustomerID from ahpPRocessingHEader where hphCustomerID in (''+ @strCustomerID +'' ) and hphCancel=0  open opcurt''
--print @strSql
DECLARE opcurt cursor for
-- exec sp_executesql @strSql
select hphProcessingID,hphCustomerID from #tempCustomer inner join ahpPRocessingHEader on  CustomerID=hphCustomerid  and hphCancel=0 and hphProcessingDate<=@asondate
end
--select hphProcessingID,hphCustomerID from ahpPRocessingHEader where hphCustomerID in (759) and hphCancel=0
open opcurt
fetch next from opcurt into  @intProcessingID,@intCustomerid
while @@fetch_status =0
begin
----Finding Customer Balance
---set @InvID=select hphInvoiceID from ahpProcessingHEader where hphProcessingID
select @CustomerBalance=sum(invamt-cpmtamt) from vwhpCustomerledger where CustomerID=@intCustomerid
--Insert Processing Details to TempTAble
insert into #tempData select hphCustomerID,hpCustName,hphProcessingID,
case when hphAmended=0 then ''O'' else ''A'' end Status,
hphProcessingNo,hpAgreementNO,@CustomerBalance,
Null,null,null,null,null,null
from ahpprocessingheader inner join loshpCustomerdetails on hphCustomerID=hpCustID
inner join (loshpInvoiceheader inner join ahpAgreementdetail on hpqhReferenceid=hpQuotationID and hpCancel=0 )
on hphInvoiceID=hpqhQuotationID
where hphProcessingID=@intProcessingID and hphCancel=0
--Find adavnce paid on that asondate and update #temptable
update #tempData  set AdvanceAmount=(
select sum(hpdSettlementamount-hpdAmount) Amount from  ahpProcessingdetail
left outer join ahpProcessingHEader on hpdProcessingId=hphProcessingID and hpdDepartmentID=hphDepartmentID              and hphAmended=0 and hphCancel=0 where hphProcessingID=@intProcessingID
and hphCustomerid=@intCustomerid and hpdChequeDate<=@asondate  having  sum(hpdSettlementamount-hpdAmount)>0 )
where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
/*
select sum(hpdSettlementamount-hpdAmount) Amount from  ahpProcessingdetail
left outer join ahpProcessingHEader on hpdProcessingId=hphProcessingID and hpdDepartmentID=hphDepartmentID
and hphAmended=0 and hphCancel=0 where hphProcessingID=354
and hphCustomerid=1399 and hpdChequeDate<=''20090408'' having  sum(hpdSettlementamount-hpdAmount)>0
*/
update #tempData  set ReturnChequeAmount=(
select sum(hphPaymentAmount) from ahpReceiptdetail pd inner join
(select hpdPAymenTID,hphPaymentAmount from ahppaymentdetail inner join ahpPaymentHEader
on hpdPaymentID=hphPaymentID and hphCancel=0
where  hpdReceiptID in
(select rd.hprdReceiptID from loshpreceiptdetail rd inner join loshpReceiptHEader rh
on rd.hprdReceiptID=rh.hprhReceiptID and hprhCancel=0 where rd.hprdProcessingId=@intProcessingID and rh.hprhCustomerid=@intCustomerid)) a
on pd.hprdPaymentID=a.hpdPAymenTID
)where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
/*
select * from ahpreceiptheader where hprhCustomerID=1399
select * from loshpreceiptdetail where  hprdProcessing
select sum(hphPaymentAmount) from ahpreceiptheader rh
inner join (ahpreceiptdetail rd
left outer join (ahppaymentheader ph
inner join (ahppaymentdetail pd
inner join loshpreceiptdetail srd on pd.hpdReceiptID=srd.hprdReceiptID
and  pd.hpdProcessingDetailID=srd.hprdProcessingDetailId)
on ph.hphPaymentID=pd.hpdPaymentID and ph.hphDepartmentID=pd.hpdDepartmentID
and ph.hphCompanyID=pd.hpdCompanyID)
on rd.hprdPaymentID=ph.hphPaymentID
and rd.hprdDepartmentID=ph.hphDepartmentID and rd.hprdCompanyID=ph.hphCompanyID )
on rh.hprhReceiptID=rd.hprdReceiptID
and rh.hprhCompanyId=rd.hprdCompanyID and rh.hprhCancel=1
where rh.hprhCustomerID=1399 and srd.hprdProcessingId=355
select * from ahpPaymenTHEader where hphCustomerID=1399
select * from ahpPaymentDetail where hpdPaymentID=189
select sum(hphPaymentAmount) from ahpReceiptdetail pd inner join
(select hpdPAymenTID,hphPaymentAmount from ahppaymentdetail inner join ahpPaymentHEader
on hpdPaymentID=hphPaymentID and hphCancel=0
where  hpdReceiptID in
(select rd.hprdReceiptID from loshpreceiptdetail rd inner join loshpReceiptHEader rh
on rd.hprdReceiptID=rh.hprhReceiptID and hprhCancel=0 where rd.hprdProcessingId=355 and rh.hprhCustomerid=1399)) a
on pd.hprdPaymentID=a.hpdPAymenTID
select * from loshpreceiptdetail where hprdReceiptID= 2795
*/
update #tempData  set SettledAmount=(
select sum(hpdSettlementamount) Amount from  ahpProcessingdetail
left outer join ahpProcessingHEader on hpdProcessingId=hphProcessingID and hpdDepartmentID=hphDepartmentID
and hphAmended=0 and hphCancel=0 where hphProcessingID=@intProcessingID and hphCustomerid=@intCustomerid and hpdChequeDate<=@asondate)
where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
update #tempData  set PaymentAmount=(
select sum(hphPaymentAmount) from
ahppaymentheader ph inner join ahppaymentdetail pd on ph.hphPaymentID=pd.hpdPaymentID
and ph.hphDepartmentID=pd.hpdDepartmentID and ph.hphCompanyID=pd.hpdCompanyID  and hphCancel=0
inner join loshpreceiptdetail srd on pd.hpdReceiptID=srd.hprdReceiptID and  pd.hpdProcessingDetailID=srd.hprdProcessingDetailId
where ph.hphCustomerID=@intCustomerid and srd.hprdProcessingId=@intProcessingID )
where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
update #tempData  set UnernedFinIncome=(
select sum(hpdInterest) Amount from  ahpProcessingdetail
left outer join ahpProcessingHEader on hpdProcessingId=hphProcessingID and hpdDepartmentID=hphDepartmentID
and hphAmended=0 and hphCancel=0 where hphProcessingID=@intProcessingID and hphCustomerid=@intCustomerid and hpdChequeDate<=@asondate)
where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
update #tempData  set AdjustmentAmount=(
select hphAdjustmentAmount from ahpProcessingHEader where  hphCancel=0 and  hphProcessingID=@intProcessingID and hphCustomerid=@intCustomerid)
where ProcessingId=@intProcessingID and CustomerID=@intCustomerid
fetch next from opcurt into  @intProcessingID,@intCustomerid
end
--close opcurt
deallocate opcurt
--end
select * from #tempData
drop table #tempData
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHpCustomerLedger]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHpCustomerLedger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
------------------------------------------------------------------------------------------------------------------------------------------------------------
----Created By         : Shinu Vaman
----Created On         : 18-12-2007
----Created For        : To get Customer Ledger
----Modified By        : Prasanth Joseph  Put order by for geting Invoice first
----Modified On        :  12-01-2008
-------------------------------------------------------------------------------------------------------------------------
---Modified By Nidheesh P V
---Modified on : 26-04-2010
---Comments : Removed the  @strCatName , @strGroupName  variables
CREATE proc [dbo].[spHpCustomerLedger] @intCompanyID as int,
@strFromdate as varchar(8),
@strToDate as varchar(8),
@strcustomerid as varchar(2000),
@intdepartmentid as int,
@intShopID as int=0  as
begin
set nocount on
Set ansi_warnings off
create table #temp(
companyid  int,
customerid  int,
opdebitamt  numeric(18,2),
opcreditamt  numeric(18,2)
)
declare @dtFromdate as datetime,
@dtTodate as datetime,
@intcustid as int,
@dtfinstartdate as datetime,
@numopeningcredit as numeric(18,2),
@numopeningdebit as numeric(18,2),
@strsql as nvarchar(4000),
@bitason as bit
if @strcustomerid <> '''' -- hari included to handle all customers
set @strcustomerid = '' and vw.customerid in ('' + @strcustomerid + '') ''
if (@strfromdate <>'''')
begin
set @dtfromdate = convert(datetime,@strfromdate,101)
set @bitason =0
end
else
begin
set @bitason =1
end
set @dttodate = convert(datetime,@strtodate,101)
if (@bitason =0)
begin -- if the statement is for a period   b1
set @strsql =N''declare opcur cursor for
SELECT customerid FROM vwhpcustomerledger vw
WHERE vw.companyid ='' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and
vw.tdate <='''''' + convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid
+ '' group by customerid''
exec sp_executesql @strsql
open opcur
fetch next from opcur into @intcustid
while @@fetch_status =0
begin  -------------------------------b2
set @numOpeningCredit =0.0
set @numOpeningDebit  =0.0
if @intdepartmentid<>0
begin
SELECT  @numOpeningCredit = (SELECT isnull(sum(pmtamt),0)  FROM
vwhpcustomerledger vw
WHERE vw.departmentid=@intdepartmentid and vw.companyid = @intcompanyid
and tdate < @dtfromdate and customerid = @intcustid )
SELECT  @numOpeningDebit = (SELECT isnull(sum(invamt),0)  FROM
vwhpcustomerledger c
WHERE c.departmentid=@intdepartmentid and c.companyid = @intcompanyid
and c.customerid = @intcustid and tdate < @dtfromdate)
end
else
begin
SELECT  @numOpeningCredit = (SELECT isnull(sum(pmtamt),0)  FROM
vwhpcustomerledger vw
WHERE vw.companyid = @intcompanyid and tdate < @dtFROMDate and
customerid = @intcustid )
SELECT  @numOpeningDebit = (SELECT isnull(sum(invamt),0)  FROM
vwhpcustomerledger c
WHERE c.companyid = @intcompanyid and c.customerid = @intcustid
and tdate < @dtfromdate)
end
insert into #temp values (@intcompanyid, @intcustid, @numopeningdebit,
@numopeningcredit)
fetch next from opcur into @intcustid
end -- end for while  b2
close opcur
deallocate opcur
end -- end for opening balance calculation  b1
if (@intdepartmentid = 0)  and @intShopId = 0
Begin
if (@bitason =0)
begin
set @strsql = N''select cu.CustomerName, cu.Address1, cu.Address2, cu.Address3,
cu.CreditLimit,vw.*,  0.0 OpCreditAmt, 0.0 OpDebitAmt  from vwhpCustomerLedger vw
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) cu on vw.CompanyId=cu.CompanyId and
vw.CustomerID=cu.CustomerID
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid
end
----For with out from date
else
begin
set @strsql = N''select cu.CustomerName, cu.Address1, cu.Address2, cu.Address3,
cu.CreditLimit,vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt from vwhpCustomerLedger vw
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) cu on vw.CompanyId=cu.CompanyId and
vw.CustomerID=cu.CustomerID
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid
end
end
else if @intdepartmentid <> 0
Begin
if (@bitason =0)
begin
set @strsql = N''select cu.CustomerName, cu.Address1, cu.Address2, cu.Address3,
cu.CreditLimit,vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt  from vwhpCustomerLedger vw
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) cu on vw.CompanyId=cu.CompanyId and
vw.CustomerID=cu.CustomerID
where vw.Companyid= '' +  convert(varchar(5),@intcompanyid)  + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' +  @strcustomerid + '' and vw.DepartmentID=
'' + convert(varchar(5),@intdepartmentid)
end
else
begin
set @strsql = N''select cu.CustomerName, cu.Address1, cu.Address2, cu.Address3,
cu.CreditLimit,vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt  from vwhpCustomerLedger vw
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) cu on vw.CompanyId=cu.CompanyId and
vw.CustomerID=cu.CustomerID
where vw.Companyid= '' +  convert(varchar(5),@intcompanyid)+ '' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' +   @strcustomerid +'' and vw.DepartmentID=
'' + convert(varchar(5),@intdepartmentid)
end
end
set @strsql=@strsql+''order by tdate,type''
print @strsql
exec sp_executesql @strsql
set nocount off
Set ansi_warnings on
end
----------------------------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlights]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertFlights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
--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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHPCustomerAdvanceAsOnDate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPCustomerAdvanceAsOnDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---spHPCustomerAdvanceAsOnDate 1,0,''20080101'',0
/*
Created by :  Shinu
Created on : 05/01/2008
Modified by :
Modified on :
Purpose      : For Customer Ledger Report
*/
CREATE PROC [dbo].[spHPCustomerAdvanceAsOnDate] @intcompanyid int,
@intcustomerid int,
@strtodate varchar(10),
@intdepid int as
begin
declare @dttodate as datetime
set @dttodate = convert(datetime,@strtodate)
if @intdepid = 0
Begin
select isnull(sum(advance),0) advance
from vwHPcustomersummaryasdate
where companyid = @intcompanyid
and customerid = @intcustomerid
and invoicedate <= @dttodate
End
else
Begin
select isnull(sum(advance),0) advance
from vwHPcustomersummaryasdate
where companyid = @intcompanyid
and customerid = @intcustomerid
and invoicedate <= @dttodate
and departmentid = @intdepid
end
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[sphpadvancePayments]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sphpadvancePayments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec sphpadvancePayments ''20080101'',''20090516''
--- created By   : Jyothish S R
--- Date        : 14/05/2009
CREATE   proc [dbo].[sphpadvancePayments]
@strFromdate as varchar(8),
@strToDate as varchar(8)
as
begin
set nocount on
declare @dtFromdate as datetime
declare @dtTodate as datetime
declare @intcustid as int
declare @intPaymentAmount as numeric(18,2)
declare @CustomerName as varchar(300)
declare @Address as varchar(300)
set @dtfromdate = convert(datetime,@strfromdate,101)
set @dtTodate = convert(datetime,@strToDate,101)
create table #AdavancePayment (
CustomerID int,
CustomerName varchar(300),
CustomerAdrs varchar(500),
PaymentAmount  numeric(18,2))
declare curCustomer cursor  for  select hpCustID,hpcustname,hpcustpresentadd  from loshpcustomerdetails
open curCustomer fetch next from  curCustomer into @intcustid,@CustomerName,@Address
print @intcustid
while  @@fetch_status <> -1
begin
set @intPaymentAmount =0
select  @intPaymentAmount= ( isnull(vwcust.TotalInvoice,0)- isnull(vwad.Advance,0) ) -isnull(pr.TotalAmout,0)
from
(select hphCustomerID,sum(hpdAmount)As TotalAmout  from aHpProcessingHeader hp ,
aHpProcessingDetail hdt where hp.hphCompanyID=hdt.hpdCompanyID  and
hp.hphDepartmentID=hdt.hpdDepartmentID and hp.hphProcessingID=hdt.hpdProcessingId
and (hpdChequeDate  between @dtfromdate and @dtTodate) and hphCancel=0 and
hphCustomerID=@intcustid group by hphCustomerID)pr
inner   join (select CustomerID,  (sum(pmtamt) - sum(invamt))TotalInvoice
from vwhpCustomerLedger where type <> ''HP Invoice'' and CustomerID=@intcustid and
(tDate  between @dtfromdate and @dtTodate) group by CustomerID)vwcust
on pr.hphCustomerID=vwcust.CustomerID
left  join
(select  hprhCustomerID,sum(hprhReceiptAmount)Advance  from losHpReceiptHeader where
hprhCancel=0 and hprhReceiptType=''A'' and
(hprhReceiptDate  between @dtfromdate and @dtTodate)  and hprhCustomerID=@intcustid
group by hprhCustomerID )vwad on    vwad.hprhCustomerID=vwcust.CustomerID
if( @intPaymentAmount>0 )
begin
insert into #AdavancePayment values (@intcustid,@CustomerName,@Address,@intPaymentAmount)
end
fetch next from  curCustomer into @intcustid,@CustomerName,@Address
end
close curCustomer
deallocate curCustomer
end
Select CustomerID,CustomerName,CustomerAdrs,vw.hphProcessingNo,PaymentAmount from  #AdavancePayment pd
inner  join  (select distinct hpp.hphCustomerID,hpp.hphProcessingNo  from aHpProcessingHeader hpp ,
aHpProcessingDetail hdtt where hpp.hphCompanyID=hdtt.hpdCompanyID  and
hpp.hphDepartmentID=hdtt.hpdDepartmentID and hpp.hphProcessingID=hdtt.hpdProcessingId
and (hdtt.hpdChequeDate  between @dtfromdate and @dtTodate) and hpp.hphCancel=0
) vw   on vw.hphCustomerID=pd.CustomerID
order by CustomerName
drop table #AdavancePayment' 
END
GO
/****** Object:  View [dbo].[vwInventoryAge_old]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInventoryAge_old]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Shinu
-- Created on  : 04/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Inventory Ageing
CREATE VIEW [dbo].[vwInventoryAge_old] as
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,Due,pbhVendorID,pbdItemID,ItemCode,
ItemDescription,UnitsID,Brand,modelno,isnull(part_code,'''')part_code,
ItemCategoryID,pbdPackingtypeID,pbdItemQuantity,pbdItemUnitPrice,Stock ,OpeningStock FROM
(select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,''0 - 30'' as Due,pbhVendorID,pbdItemID,pbdPackingtypeID,
pbdItemQuantity,pbdItemUnitPrice
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1 and (getdate() -pbhBillDate between 0 and 30)
UNION ALL
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,''30 - 180'' as Due,pbhVendorID,pbdItemID,pbdPackingtypeID,pbdItemQuantity,pbdItemUnitPrice
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1 and (getdate() -pbhBillDate between 30 and 180)
UNION ALL
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,''180 - 365'' as Due,pbhVendorID,pbdItemID,pbdPackingtypeID,pbdItemQuantity,pbdItemUnitPrice
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1 and (getdate() -pbhBillDate between 180 and 365)
UNION ALL
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,''360 - 700'' as Due,pbhVendorID,pbdItemID,pbdPackingtypeID,pbdItemQuantity,pbdItemUnitPrice
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1 and (getdate() -pbhBillDate between 365 and 700)
UNION ALL
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,''> 700'' as Due,pbhVendorID,pbdItemID,pbdPackingtypeID,pbdItemQuantity,pbdItemUnitPrice
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1 and (getdate() -pbhBillDate >700) ) BILLDETAILS
LEFT OUTER JOIN aItem ai ON ItemID=pbdItemID
Left Outer Join (select ItemID,sum(Stock)Stock,sum(OpeningStock)OpeningStock from vwCompanyTotalStock group by ItemID )CompanyTotalStock
ON CompanyTotalStock.ItemID=pbdItemID'
GO
/****** Object:  View [dbo].[vwBillCurrency]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillCurrency]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwBillCurrency    Script Date: 18/01/2003 9:45:34 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 20/11/2001 9:58:59 AM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 17/11/2001 9:21:27 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 16/06/2001 15:36:30 ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 09/03/2001 02:32:25 ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 12/05/00 1:40:14 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 10/17/00 2:19:50 PM ******/
/****** Object:  View dbo.vwBillCurrency    Script Date: 10/7/00 11:07:55 AM ******/
CREATE view [dbo].[vwBillCurrency] as
select b.pbhCompanyID, b.pbhBillID, b.pbhVendorID, v.CurrencyID, ed.BuyingRate, ed.AverageRate
from LOspPurchaseBillHeader b,
avendormaster v ,exchangerate eh, exchangeratedetail ed
where b.pbhCompanyID = v.companyid  and eh.companyid = ed.companyid and
b.pbhCompanyID = eh.companyid and b.pbhVendorID = v.vendorid
and v.currencyid = ed.currencyid
and eh.ExchangeID = ed.ExchangeID and
eh.exchangedate = b.pbhBillDate
and ed.currencyid = v.currencyid'
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceDep]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceDep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 26/04/2004, 13/07/2004, 28/07/2004
-- Modified by   : Kishore, Hariharan
-- Comments  : the department accoiunt filter given (23/01/2003)
--               : removed account head filteration deptwise (25/08/2003)
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--   : Included consolidation 261203 venki
--   : Hari corrected the A, L, I ,E TYPE checking and made temporary table source
--   : Removed Cursor and looping to make the printing fast
--   : COnsolidation group corrected avoiding departmentid from grouping
--   : Opening Debit and credit net is found and kept in opening columns
----------------------------------------
--Ref.No:1
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spTrialBalanceDep] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@intCompanyId as int,
@intDepartmentId as int,
@bitCons as bit,
@intLevel as int = 0,
@intconsolidation as int =0) AS
begin
set nocount on
set ansi_warnings off
Declare
@dtFROMDate as datetime,
@dtToDate as datetime,
@intParentGroupID int,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #TrialBal(
CompanyID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
OpDebit numeric(18,2),
OpCredit Numeric(18,2),
AccountId int,
DepartmentId int)
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
SELECT @dtFROMDate = convert(datetime, @strFROMDate)
SELECT @dtToDate = convert(datetime, @strToDate)
Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
select @intCount = count(*) from aAccountfinyearOpening where
CompanyId = @intCompanyId and FinancialId = @intFinId
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0   --Ref.No:1 Commented
if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
(Select Deptid from #SubDepts1)
-----------------------------
insert into #TrialBal
SELECT acc.CompanyId, acc.AccountCode, acc.AccountDesc, acc.accounttype,
acc.GroupID, acc.GroupDesc, OpDr, OpCr, Debit, Credit, OpDebit, OpCredit,
acc.AccountId, acc.Departmentid from
(SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,
GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,
am.AccountId, d.DaDepartmentid Departmentid
FROM aaccountmaster AM, aGroupMaster GM, adeptAccounts d
WHERE GM.GroupID = AM.GroupID
AND GM.CompanyID = AM.CompanyID
AND AM.CompanyID = @intcompanyid
and am.accountid = d.daAccountid
and am.companyid = d.dacompanyid
and d.daDepartmentId in  (Select DeptId from #SubDepts1)
union all
SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,
GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,
am.AccountId, deptid DepartmentId
FROM aaccountmaster AM, aGroupMaster GM, vwGlobalAccounts vg,  #SubDepts1
WHERE GM.GroupID = AM.GroupID
AND GM.CompanyID = AM.CompanyID
AND AM.CompanyID = @intcompanyid
and am.accountid = vg.AccountId
and am.companyid = vg.CompanyId ) acc
group by acc.CompanyId,  acc.accounttype,   acc.GroupID, acc.GroupDesc, acc.AccountCode,
acc.AccountDesc, acc.AccountId, acc.Departmentid,
OpDr, OpCr, Debit, Credit, OpDebit, OpCredit order by acc.accountid asc
Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,
DepartmentId, CompanyId,
case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.DepartmentId = #TrialBal.DepartmentId
and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount >0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount <0))
Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,
DepartmentId, CompanyId,
case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount
from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.DepartmentId = #TrialBal.DepartmentId
and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount <0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount >0))
Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v , #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 Where OBCr > OBDr
Update #TrialBal set OBDr = OBDr - OBCr, OBCr = 0 Where OBDr > OBCr
Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
/*SELECT * FROM #TrialBal
where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0
ORDER BY AcType, AccCode */
SELECT CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName , sum(OBDr),
sum(OBCr), sum(DebitAmt), sum(CrEDitAmt), sum(OpDebit), sum(OpCredit),
AccountId , min(Departmentid) FROM #TrialBal
Group By CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName, AccountId
having (sum(isnull(obcr, 0))+  sum(isnull(obdr, 0)) + sum(isnull(debitamt, 0)) +
sum(isnull(creditamt, 0))) <> 0
ORDER BY AcType, AccCode
drop table #SubDepts1
drop table #vwJournalDetails
drop table #Tempjournalheader
Drop Table #TrialBal
set nocount on
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceConsol]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceConsol]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--modified by  : Hariharan
--Modified Date  : 03/02/2004, 20/03/2004, 29/03/2004
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)
--   : used temporary tables for getting data after fetching for first time
--exec spTrialBalanceConsol ''20090107'',''20100526'',1,0,1,1
-----------------------------
--Modified by : VinothMurugan V
--Date : 25/06/2010
--Refno : RefNo-01
--Purpose : Extend Verchar Value
----------------------------
--Ref.No:2
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
CREATE proc [dbo].[spTrialBalanceConsol] @strFROMDate as varchar(10), @strToDate as varchar(10),
@intcompanyid as int, @intdepartmentid as int, @bitcons as bit,
@intconsolidation as int=0  as
set nocount on
begin
declare @dtFROMDate as datetime
declare @dtToDate as datetime,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
Postgroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(200),  --RefNo-01
Remarks varchar(400), --RefNo-01
Type char(20),  --RefNo-01
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #TrialBal(
CompanyID int,
DepartmentId int,
DepartmentName varchar(100),
accountid int,
AccCode varchar(50),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
Debit numeric(18,2),
Credit numeric(18,2),
OpDebit numeric(18,2),
OpCredit Numeric(18,2),
OpBal numeric(18,2))
SELECT @dtFROMDate = convert(datetime, @strFROMDate)
SELECT @dtToDate = convert(datetime,@strToDate)
Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
select @intCount = count(*) from aAccountfinyearOpening where
CompanyId = @intCompanyId and FinancialId = @intFinId
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0   --Ref.No:2  Commented
if ISNULL(@intLastFinId,0) = 0   --Ref.No:2  Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
if @intDepartmentId = 0
begin
insert #vwJournalDetails
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
h.CompanyId = @intCompanyId
end
else
begin
insert #vwJournalDetails
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)
end
insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,
AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit )
Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,
a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,
0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where
a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid
and a.CompanyId = @intCompanyid
Update #TrialBal set OpBal = opening.Openingamount from (Select AccountId,
DepartmentId, CompanyId, Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.DepartmentId = #TrialBal.DepartmentId
and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
Update #TrialBal set OpDebit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set OpCredit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set Debit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set Credit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(Amount,0)) Amount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
/*delete from #TrialBal where departmentid in
(Select departmentid from #TrialBal group by DepartmentId
having sum(debit) = 0 and sum(credit)=0) */
Delete from #TrialBal from (Select accountid, Departmentid from #TrialBal
group by accountid, departmentid having sum(debit) = 0 and sum(credit) = 0 and
sum(OpDebit) = 0 and sum(OpCredit)=0 and
sum(OpBal)=0 ) chk where #TrialBal.accountid = chk.accountid and
#TrialBal.departmentid = chk.departmentid
--TEMPORARY CODE GIVEN TO CONSOLIDATION IMM1, 2 AND 3 AS IMM STORE
Update #TrialBal set departmentid = 3 where departmentid in (15, 16, 17)
Select CompanyID, DepartmentId, DepartmentName , accountid,
AccCode, AccDesc , AcType , GroupID , GroupName , Debit ,
Credit, OpDebit, OpCredit, OpBal , ''Debit'' DebitTitle, ''Credit'' CreditTitle,
case AcType when ''A'' then ''1'' when ''L'' THEN ''2'' WHEN ''I'' then ''3''
WHEN ''E'' THEN ''4'' end GroupNo from #TrialBal
order by AcType, GroupId, AccountId
--drop table #TrialBal
drop table #SubDepts1
drop table #vwJournalDetails
drop table #Tempjournalheader
end
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalance_Detail]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalance_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- Created By Sreejith on 20100730
-- Purpose - To show Trial Balance Report
--    spTrialBalance_Detail ''20100101'',''20100909'',1
------------------------------------
--Ref.No: 1
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spTrialBalance_Detail] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@intCompanyId as int) AS
begin
set nocount on
set ansi_warnings off
Declare @dtFROMDate as datetime,
@dtToDate as datetime,
@intParentGroupID int,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #TrialBal(
CompanyID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
AccountId int,departmentid int,departmentname varchar(30))
SELECT @dtFROMDate = convert(datetime, @strFROMDate)
SELECT @dtToDate = convert(datetime, @strToDate)
Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
select @intCount = count(*) from aAccountfinyearOpening where
CompanyId = @intCompanyId and FinancialId = @intFinId
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0           --Ref.No: 1 Commented
if ISNULL(@intLastFinId,0) = 0           --Ref.No: 1 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
insert into #TrialBal
SELECT distinct VSS.CompanyId, VSS.AccountCode, VSS.AccountDesc, VSS.accounttype,
VSS.GroupID, VSS.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit,
VSS.AccountId ,VSS.departmentid,VSS.departmentname   FROM
(SELECT   distinct ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid  ,adm.departmentname
from aaccountfinyearopening ad
left outer join   aaccountmaster AM on AM.accountid=ad.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID   AND GM.CompanyID = AM.CompanyID
left outer join adepartmentmaster adm on adm.departmentid=ad.departmentid   AND adm.CompanyID=ad.CompanyID
union all
SELECT   distinct v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid,adm.departmentname
from  #vwJournalDetails v
left outer join   aaccountmaster AM on AM.accountid=v.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID   AND GM.CompanyID = AM.CompanyID
left outer join adepartmentmaster adm on adm.departmentid=v.departmentid   AND adm.CompanyID=v.CompanyID
)vss
WHERE VSS.CompanyID = @intcompanyid order by VSS.accountid asc
--   spTrialBalance_Detail ''20100101'',''20100909'',1
Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId
Group BY AccountId,departmentid, CompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount >0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount <0)  )   and opening.departmentid= #TrialBal.departmentid
Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId
Group BY AccountId,departmentid, CompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount <0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount >0) ) and opening.departmentid= #TrialBal.departmentid
Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId,v.departmentid, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid= #TrialBal.departmentid
Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId,v.departmentid, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and trialDeb.CompanyId = #TrialBal.CompanyID
and trialDeb.CompanyId = @intCompanyId  and trialDeb.departmentid= #TrialBal.departmentid
Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 where OBCr > OBDr
Update #TrialBal set OBDr = OBDr - OBCr, OBCr =0 where OBDr > OBCr
Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId,v.departmentid, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid= #TrialBal.departmentid
Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId,v.departmentid, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid= #TrialBal.departmentid
SELECT * FROM #TrialBal
where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0
ORDER BY AcType, AccCode
drop table #vwJournalDetails
drop table #Tempjournalheader
Drop Table #TrialBal
set nocount on
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalance]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 26/04/2004, 28/07/2004
-- Modified by   : Hariharan
--   : Removed Cursor and looping to make the printing fast
--   : Opening debit and credit taken net and updated
-----------------------------------------------------
--Ref.No:1
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spTrialBalance] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@intCompanyId as int) AS
begin
set nocount on
set ansi_warnings off
Declare @dtFROMDate as datetime,
@dtToDate as datetime,
@intParentGroupID int,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #TrialBal(
CompanyID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
AccountId int)
SELECT @dtFROMDate = convert(datetime, @strFROMDate)
SELECT @dtToDate = convert(datetime, @strToDate)
Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
select @intCount = count(*) from aAccountfinyearOpening where
CompanyId = @intCompanyId and FinancialId = @intFinId
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0   --Ref.No:1 Commented
if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
-----------------------------
insert into #TrialBal
SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,
GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit,
am.AccountId FROM aaccountmaster AM, aGroupMaster GM
WHERE GM.GroupID = AM.GroupID AND GM.CompanyID = AM.CompanyID
AND AM.CompanyID = @intcompanyid order by aM.accountid asc
Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId
Group BY AccountId, CompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount >0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount <0))
Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId
Group BY AccountId, CompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
opening.Openingamount <0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
opening.Openingamount >0))
Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and trialDeb.CompanyId = #TrialBal.CompanyID
and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 where OBCr > OBDr
Update #TrialBal set OBDr = OBDr - OBCr, OBCr =0 where OBDr > OBCr
Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
SELECT * FROM #TrialBal
where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0
ORDER BY AcType, AccCode
drop table #vwJournalDetails
drop table #Tempjournalheader
Drop Table #TrialBal
set nocount on
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPLAmtForBS]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLAmtForBS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spPLAmtForBS    Script Date: 28/12/2002 4:26:50 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBS    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBS    Script Date: 31/07/2002 2:00:36 PM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBS    Script Date: 20/11/2001 9:59:15 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBS    Script Date: 17/11/2001 9:22:27 PM ******/
--Last Modified : 15/10/2001
--Modified by   : leo
CREATE proc [dbo].[spPLAmtForBS] (@strToDate as varchar(10), @intCompanyID as integer,
@numDebitAmt as numeric(18,2) output, @numCreditAmt as numeric(18,2) output)
as
set nocount on
Declare @AcCode as varchar(100),
	@AcID as integer,
	@AccDesc as varchar(100),
	@strParentGroupName varchar(100),
	@intParentGroupID int,
	@AcType as varchar(1),
	@dblDebit as numeric(18,2),
	@dblCrEDit as numeric(18,2),
	@AccountOBCr as numeric(18,2),
	@AccountOBDr as numeric(18,2),
	@OBDr as numeric(18,2),
	@OBCr as numeric(18,2),
	@GroupDesc as varchar(100),
	@GroupID as int,
	@CompanyName as varchar(100),
	@dtFROMDate as datetime,
	@dtToDate as datetime
Create table #PL(
	CompanyID int,
	AcID int,
	AccCode varchar(100),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID integer,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CrEDitAmt numeric(18,2),
	ParentGroupID int,
	ParentGroupName varchar(100))
	select @dtFromDate = sdate from vwfinyearperiod where
	convert(datetime,@strToDate,101) between sdate and edate
	SELECT @dtToDate = convert(datetime, @strToDate)
Declare curPL Cursor For
SELECT AccountID, GM.GroupID, GM.GroupDesc, AccountCode, AccountDesc, AccountType,
openingamount, openingamount, ParentGroupID FROM aAccountMaster AM,aGroupMaster GM
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'')
	AND GM.CompanyID = @intCompanyID AND AM.CompanyID = @intCompanyID
ORDER BY AccountType, AccountID
Open curPL
Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,
@AccountOBCr, @AccountOBDr, @intParentGroupID
while @@fetch_status <> -1
begin
	set @OBDr = 0.0
	set @OBCr = 0.0
	set  @dblDebit = 0.0
	set @dblCrEDit = 0.0
	SELECT @dblDebit = Sum(isnull(Amount,0)) FROM vwjournaldetails JD, moajournalheader JH,
	acompanymaster c
	WHERE c.companyid = jh.companyid and JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND
	jh.cancel =0 and JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
	@dtToDate) AND JD.JournalCrEDit = 0 AND JD.AccountID = @AcID
	SELECT @dblCrEDit = Sum(isnull(Amount,0)) FROM vwjournaldetails JD, moajournalheader JH,
	acompanymaster c
	WHERE c.companyid = jh.companyid and
	JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND jh.cancel =0 and
	JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
	@dtToDate) AND JD.JournalCrEDit = 1 AND JD.AccountID = @AcID
	insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType, @GroupID,
		'''', 0.0, 0.0, isnull(@dblDebit,0), 	-- leo
		isnull(@dblCrEDit,0), @intParentGroupID, '''')
	Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType, @AccountOBCr,
	@AccountOBDr, @intParentGroupID
end
SELECT @numDebitAmt = (sum(OBDr) + sum(DebitAmt)),
@numCreditAmt  = (sum(OBCr) + sum(CreditAmt)) FROM #PL
close curPL
deallocate curPL
set nocount on' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPL_Detail]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPL_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : Sreejith G A
--Created on : 20100807
--Purpose: To show Profit and Loss Department Wise
CREATE PROCEDURE [dbo].[spPL_Detail] (@strFROMDate as varchar(10), @strToDate as varchar(10),
@intCompanyID as int,@intlevel as int =0) as
Begin
set nocount on
Set ansi_warnings off
Declare @AcCode as varchar(100),
@AcID as int,
@AccDesc as varchar(100),
@GroupId as int,
@CompanyName as varchar(100),
@dtFROMDate as datetime,
@dtToDate as datetime,
@dtfinstartdate as datetime,
@AccountOBCr as numeric(18,2),
@AccountOBDr as numeric(18,2),
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intRecCount as int,
@intFromFinId as int,
@intLastFinId as int,
@intCount as int
Create table #PL(
CompanyID int,
AcID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
ParentGroupID int,Departmentid int)
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup Int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #PLFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AcId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ParentGroupId int,DepartmentName varchar(100))
SELECT @dtFROMDate = convert(datetime, @strFromDate)
SELECT @dtToDate = convert(datetime, @strToDate)
select @intFromFinId = FinancialId from vwfinyearperiod where companyid = @intcompanyid and
@strFROMDate between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFromFinId
if @intLastFinId = 0
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName , OBDr ,
OBCr , DebitAmt , CrEDitAmt , ParentGroupID,Departmentid )
select  vss.CompanyId,vss.AccountID, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,
vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.departmentid
from
(SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid
from aaccountfinyearopening ad
left outer join   aaccountmaster AM on AM.accountid=ad.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
union all
SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid
from  #vwJournalDetails v
left outer join   aaccountmaster AM on AM.accountid=v.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
)vss
where
(VSS.AccountType = ''I'' OR VSS.AccountType = ''E'')
AND VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc,ParentGroupID
Update #PL set OBDr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId group by CompanyId, AccountId,departmentid) opening Where
opening.Accountid = #PL.AcId and opening.CompanyId = #PL.CompanyID and
opening.CompanyId = @intCompanyId and
((#PL.ACType = ''E''  and opening.Openingamount >0) or (#PL.ACType = ''I''  and
opening.Openingamount <0))  and opening.departmentid=#PL.departmentid
Update #PL set OBCr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount ,departmentid
from aaccountfinyearopening where Financialid = @intLastFinId and
CompanyId = @intCompanyId Group by AccountId, CompanyId,departmentid) opening Where
opening.Accountid = #PL.AcId and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
and ((#PL.ACType = ''E''  and opening.Openingamount <0) or (#PL.ACType = ''I''  and
opening.Openingamount >0))   and opening.departmentid=#PL.departmentid
Update #PL set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount ,departmentid From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.CompanyId,v.departmentid) trialDeb Where trialDeb.Accountid = #PL.AcId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid=#PL.departmentid
Update #PL set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount ,departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId,
v.CompanyId,v.departmentid) trialDeb Where trialDeb.Accountid = #PL.AcId and
trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid=#PL.departmentid
Update #PL set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount ,departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId
and h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.AccountId, v.CompanyId,v.departmentid) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId and trialDeb.departmentid=#PL.departmentid
Update #PL set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.CompanyId,v.departmentid) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId and trialDeb.departmentid=#PL.departmentid
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
Insert #plFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AcId,  Departmentid, DepartmentName, orderno, levelcode, Checked,
ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AcId, ad.Departmentid, ad.DepartmentName, r.OrderNo, r.LevelCode,
0,  r.ParentGroupId from #FilteredResult r
left outer join #PL b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AcId and r.AccountId is not null))
left outer join adepartmentmaster ad on ad.departmentid=b.departmentid
where
((((((isnull(creditamt,0) - isnull(debitamt,0)) <> 0 or
(isnull(obcr,0) - isnull(obdr,0)) <> 0) and isnull(r.AccType ,'''') =''I'')
or (((isnull(debitamt,0) - isnull(creditamt,0)) <> 0 or
(isnull(obdr,0) - isnull(obcr,0)) <> 0) and isnull(r.AccType ,'''') =''E'')
) and b.accCode is not null) or b.accCode is null)  order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #PLFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #PLFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #PLFinal where GroupId = @GroupID
else
Update #PLFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
Delete from #PLFinal where LevelCode >= @intLevel and AcId is null
Select * from #PLFinal order by OrderNo
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
drop table #PLFinal
drop table #PL
drop table #FilteredResult
set nocount on
Set ansi_warnings on
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPL]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPL]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spPL ''20090101'',''20091231'',1
-- Modified by   : Hariharan,jyothish
-- Modified on   : 20/03/2004, 15/04/2004, 27/04/2004, 13/07/2004, 03/08/2004  ,04/06/2010,31/10/2011
-- Comments      : used spopeningbalance for getting the opening balances
--   : GIven FinancialId condition for getting the start date to take the records
--   : Removed Cursor and looping to get report fast.
--   : Removing
-----------------------------------------------------------------------------------------
-----  ref1:previous month has to be added in the report
CREATE PROCEDURE [dbo].[spPL] (@strFROMDate as varchar(10), @strToDate as varchar(10),
@intCompanyID as int,@intlevel as int =0) as
Begin
set nocount on
Set ansi_warnings off
Declare @AcCode as varchar(100),
@strFROMDateBeforeOneMonth as varchar(100),
@strFROMDateToOneMonth as varchar(100),
@AcID as int,
@AccDesc as varchar(100),
@GroupId as int,
@CompanyName as varchar(100),
@dtFROMDate as datetime,
@dtToDate as datetime,
@dtfinstartdate as datetime,
@AccountOBCr as numeric(18,2),
@AccountOBDr as numeric(18,2),
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intRecCount as int,
@intFromFinId as int,
@intLastFinId as int,
@intCount as int
---ref-1
set  @strFROMDateBeforeOneMonth=DateAdd(month,-1,@strFROMDate)
set  @strFROMDateToOneMonth=DateAdd (day, -1 ,@strFROMDate)
---ref-1
Create table #PL(
CompanyID int,
AcID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
ParentGroupID int,
DebitAmtMonthBefore numeric(18,2),
CreditAmtMonthBefore numeric(18,2))  --ref-1 DebitAmtMonthBefore,CreditAmtMonthBefore added
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup Int)
Create table #vwJournalDetails_Month(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup Int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #Tempjournalheader_Month
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #PLFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AcId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ParentGroupId int,
DebitAmtMonthBefore numeric(18,2),
CreditAmtMonthBefore numeric(18,2))
SELECT @dtFROMDate = convert(datetime, @strFromDate)
SELECT @dtToDate = convert(datetime, @strToDate)
select @intFromFinId = FinancialId from vwfinyearperiod where companyid = @intcompanyid and
@strFROMDate between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFromFinId
if @intLastFinId = 0
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
---ref1
insert #Tempjournalheader_Month
Select H.* from moajournalheader h (nolock) where journaldate>=@strFROMDateBeforeOneMonth
and JournalDate <=@strFROMDateToOneMonth  and h.CompanyId = @intCompanyId
-----
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
--ref1
insert #vwJournalDetails_Month
Select d.* from #Tempjournalheader_Month  h, vwJournalDetails d (nolock) where
Journaldate>=@strFROMDateBeforeOneMonth and
JournalDate <=@strFROMDateToOneMonth and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
---
Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName , OBDr ,
OBCr , DebitAmt , CrEDitAmt , ParentGroupID)
SELECT AM.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OpDebit, 0 OpCredit, 0 Debit, 0 Credit, ParentGroupID FROM
aAccountMaster AM, aGroupMaster GM
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'') AND
GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
Update #PL set OBDr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId group by CompanyId, AccountId) opening Where
opening.Accountid = #PL.AcId and opening.CompanyId = #PL.CompanyID and
opening.CompanyId = @intCompanyId and
((#PL.ACType = ''E''  and opening.Openingamount >0) or (#PL.ACType = ''I''  and
opening.Openingamount <0))
Update #PL set OBCr = abs(opening.Openingamount) from (Select AccountId,
CompanyId, sum(Openingamount) Openingamount
from aaccountfinyearopening where Financialid = @intLastFinId and
CompanyId = @intCompanyId Group by AccountId, CompanyId) opening Where
opening.Accountid = #PL.AcId and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
and ((#PL.ACType = ''E''  and opening.Openingamount <0) or (#PL.ACType = ''I''  and
opening.Openingamount >0))
Update #PL set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #PL set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId and
trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #PL set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId
and h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId
Update #PL set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId
-------------------------------------------ref1------------------------------------
Update #PL set DebitAmtMonthBefore = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails_Month v,
#Tempjournalheader_Month  h where v.JournalCredit = 0 and h.JournalId = v.JournalId
and h.CompanyId = v.CompanyId and h.JournalDate >= @strFROMDateBeforeOneMonth and
h.JournalDate <= @strFROMDateToOneMonth  group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId
Update #PL set CreditAmtMonthBefore = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails_Month v, #Tempjournalheader_Month h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @strFROMDateBeforeOneMonth and h.JournalDate <= @strFROMDateToOneMonth
group by v.AccountId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId
-----------------------------------------------------------------------------------
---    SELECT * FROM #PL
---    where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
---    order by groupid, acid
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
Insert #plFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AcId, orderno, levelcode, Checked,
ParentGroupId,DebitAmtMonthBefore,CreditAmtMonthBefore)
SELECT b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AcId, r.OrderNo, r.LevelCode,
0,  r.ParentGroupId,b.DebitAmtMonthBefore,b.CreditAmtMonthBefore from #FilteredResult r
left outer join #PL b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AcId and r.AccountId is not null))
where
((((((isnull(creditamt,0) - isnull(debitamt,0)) <> 0 or
(isnull(obcr,0) - isnull(obdr,0)) <> 0) and isnull(r.AccType ,'''') =''I'')
or (((isnull(debitamt,0) - isnull(creditamt,0)) <> 0 or
(isnull(obdr,0) - isnull(obcr,0)) <> 0) and isnull(r.AccType ,'''') =''E'')
) and b.accCode is not null) or b.accCode is null)  order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #PLFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #PLFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #PLFinal where GroupId = @GroupID
else
Update #PLFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
Delete from #PLFinal where LevelCode >= @intLevel and AcId is null
Select CompanyID,AccCode,AcDesc,AcType,GroupID,GroupName,OBDr,
OBCr,DebitAmt,CreditAmt,AcId,DepartmentId,orderno,levelcode,
Checked,ParentGroupId,isnull(DebitAmtMonthBefore,0)DebitAmtMonthBefore ,
isnull(CreditAmtMonthBefore,0)CreditAmtMonthBefore
from #PLFinal order by OrderNo
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
drop table #PLFinal
drop table #PL
drop table #FilteredResult
drop table #Tempjournalheader_Month
Drop Table #vwJournalDetails_Month
set nocount on
Set ansi_warnings on
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRatioAnalysis]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRatioAnalysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- spRatioAnalysis ''20030201'',''20030501'',1,''C'',0,0,0
------------------------------------------------------------
-- Created  by   : R Harikrishnan
-- Created  ON   : 15/09/2003
-- Comments     : For Ratio Analysis Report
-- Modified By  : Kamesh
-- Modified On  : 20/01/2004
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
-- Comments     : For Including the average
------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spRatioAnalysis]
@dtFromDate  AS VARCHAR(10)='''',
@dtToDate  AS VARCHAR(10),
@intCompanyID  AS INT,
@currency  AS CHAR(1),
@intDeptID  AS INT = 0,
@intRatioID  AS INT = 0,
@intLevel  AS INT = 0
AS
--For Testing purpose
--Commented by R Harikrishnan
--SET @dtFromDate  =''20030201''
--SET @dtToDate   =''20030501''
--SET @intCompanyID   =1
--SET @currency   =''C''
--SET @intDeptID   =0
--SET @intRatioID   = 2
--SET @intLevel   = 1
BEGIN
DECLARE @intFromFinID   AS INT,
@intMaxFromFinID AS INT,
@intMaxToFinID  AS INT,
@intToFinID   AS INT,
@intFromCount   AS INT,
@intToCount   AS INT,
@dtFromStartDate  AS DATETIME,
@dtToStartDate   AS DATETIME,
@intFromMaxFinID  AS INT,
@strSQL   AS NVARCHAR(3000),
@strOnlyToDate  AS CHAR(1)
SET NOCOUNT ON
CREATE table #TempEntityAccounts
(
CompanyID   INT,
AccountID   INT,
AccountType    CHAR(1),
FromOpeningBal   NUMERIC(18,2) NOT NULL DEFAULT(0.00),
FromJournalBalDr  NUMERIC(18,2) NOT NULL DEFAULT(0.00),
FromJournalBalCr  NUMERIC(18,2) NOT NULL DEFAULT(0.00),
ToOpeningBal   NUMERIC(18,2) NOT NULL DEFAULT(0.00),
ToJournalBalDr   NUMERIC(18,2) NOT NULL DEFAULT(0.00),
ToJournalBalCr   NUMERIC(18,2) NOT NULL DEFAULT(0.00)
)
SET @strSQL=N''SELECT
RTM.companyID, RTM.Lev1GroupID, RTM.Lev1GroupDesc, RTM.Lev2GroupID,
RTM.Lev2GroupDesc, RTM.Lev3GroupID, RTM.Lev3GroupDesc, RTM.LastGroupID,
RTM.LastLevel, RTM.LastGroupDesc, ETM.EntityId, ETM.EntityDesc, ETM.Numerator,ETM.RatioType,
ETM.Multiplier, ETM.AccountID, ETM.CalcType, ETM.AccountDesc,
CASE WHEN ETM.AccountType=''''A'''' OR ETM.AccountType=''''E'''' THEN 1
ELSE -1 END AccountType
INTO
##TempRatioEntityAccounts
FROM
(SELECT
Lev1.companyID, Lev1.GroupID Lev1GroupID, Lev1.GroupDesc Lev1GroupDesc,
Lev23.Lev2GroupID, Lev23.Lev2GroupDesc, Lev23.Lev3GroupID,
Lev23.Lev3GroupDesc,
CASE  WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN Lev23.Lev3GroupID
WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN Lev23.Lev2GroupID
ELSE Lev1.GroupID END LastGroupID,
CASE  WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN Lev23.Lev3GroupDesc
WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN Lev23.Lev2GroupDesc
ELSE Lev1.GroupDesc END LastGroupDesc,
CASE  WHEN ISNULL(Lev23.Lev3GroupID,0)<>0 THEN 3
WHEN ISNULL(Lev23.Lev2GroupID,0)<>0 THEN 2
ELSE 1 END LastLevel
FROM
aAccRatioGroupmaster Lev1 LEFT OUTER JOIN
(SELECT
Lev2.CompanyID,Lev2.GroupID Lev2GroupID,Lev2.GroupDesc
Lev2GroupDesc, Lev2.ParentGroupID Lev2ParentGroupID,
Lev3.GroupID Lev3GroupID, Lev3.GroupDesc Lev3GroupDesc
FROM
(SELECT
companyID,GroupID,GroupDesc,ParentGroupID
FROM
aAccRatioGroupmaster
WHERE
LevelCode=2) Lev2 LEFT OUTER JOIN
(SELECT
companyID,GroupID,GroupDesc,ParentGroupID
FROM
aAccRatioGroupmaster
WHERE
LevelCode=3) Lev3
ON lev2.companyID=lev3.companyID AND
Lev2.GroupID=Lev3.ParentGroupID) Lev23       ON lev1.companyID=lev23.companyID AND
Lev1.GroupID=Lev23.Lev2ParentGroupID
WHERE
LevelCode=1) RTM,
(SELECT
em.CompanyID, em.EntityId, em.GroupID, em.EntityDesc, em.Numerator,
rm.RatioType, rm.Multiplier, ea.AccountID, ea.CalcType, am.AccountDesc,
gm.AccountType
FROM
AAccRatioEntitiesMaster em, aAccRatioGroupmaster rm,
AAccRatioEntitiesAccounts ea, aAccountMaster am,
aGroupMaster gm
WHERE
em.CompanyID=rm.CompanyID and em.GroupID=rm.GroupID and
em.CompanyID=ea.CompanyID and em.EntityID=ea.EntityID and
ea.CompanyID=am.CompanyID and ea.AccountID=am.AccountID and
am.CompanyID= gm.CompanyID and am.GroupID=gm.GroupID) ETM
WHERE
RTM.CompanyID=ETM.CompanyID and RTM.LastGroupID=ETM.GroupID and
RTM.CompanyID='' + CONVERT(VARCHAR(12),@intCompanyID)
IF @intLevel=1
SET @strSQL=@strSQL + '' and RTM.Lev1GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
IF @intLevel=2
SET @strSQL=@strSQL + '' and RTM.Lev2GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
IF @intLevel=3
SET @strSQL=@strSQL + '' and RTM.Lev3GroupID='' + CONVERT(VARCHAR(12),@intRatioID)
EXECUTE sp_executeSQL @strSQL
SET @strSQL= N''INSERT INTO #TempEntityAccounts
(CompanyID,AccountID,AccountType)
SELECT
DISTINCT CompanyID, AccountID, AccountType
FROM
##TempRatioEntityAccounts''
EXECUTE sp_executeSQL @strSQL
IF ISNULL(@dtFromDate,'''')<>''''
BEGIN
SET @strOnlyToDate=''F''
--Getting the financial ID for the selected From Date
SELECT
@intFromFinID=MIN(financialid)
FROM
afinancialyear
WHERE
@dtFromDate BETWEEN CONVERT(DATETIME,CAST(startyear AS VARCHAR)+''/''+
CAST(StartMonth AS VARCHAR)+''/01'',101) AND
dateadd(mm,12,CONVERT(DATETIME,CAST(startyear AS VARCHAR)+''/''+
CAST(StartMonth AS VARCHAR)+''/01'',101) ) AND companyid= @intCompanyID
--Checking whether the selected financial ID record is there in the table
SELECT
@intFromCount=COUNT(1)
FROM
aAccountFinYearOpening
WHERE
Financialid=@intToFinID AND companyid=@intCompanyID
IF @intFromCount=0 --If not exists the financial ID
BEGIN
--Getting the last Closing date from the Table
SELECT
@intMaxFromFinID =ISNULL(MAX(financialid),0)
FROM
aAccountFinYearOpening
WHERE
companyid=@intCompanyID AND companyid=@intCompanyID
--Getting the Financial ID from the Financial Year table
IF @intMaxFromFinID =0
BEGIN
SELECT
@intMaxFromFinID=ISNULL(MIN(financialid),0)
FROM
afinancialyear
WHERE
companyid=@intCompanyID
END
END
ELSE
BEGIN
--If the financial ID exixts assigning that to
--@intMaxFromFinID
SET @intMaxFromFinID = @intFromFinID
END
--Getting the Start Fromdate depending upon the intMaxFromFinID selected
SELECT
@dtFromStartDate = CONVERT(DATETIME,CAST(startyear AS VARCHAR)
+''/''+CAST(StartMonth AS VARCHAR)+''/01'',101)
FROM
afinancialyear
WHERE
financialid=@intMaxFromFinID AND companyid=@intCompanyID
END
ELSE
BEGIN
SET @strOnlyToDate=''T''
END
--Getting the financial ID for the selected From Date
SELECT
@intToFinID=MIN(financialid)
FROM
afinancialyear
WHERE
@dtFromDate BETWEEN CONVERT(DATETIME,CAST(startyear AS VARCHAR)+''/''+
CAST(StartMonth AS VARCHAR)+''/01'',101) AND
DATEADD(mm,12,CONVERT(DATETIME,CAST(startyear AS VARCHAR)+''/''+
CAST(StartMonth AS VARCHAR)+''/01'',101) ) AND companyid= @intCompanyID
SELECT
@intToCount = COUNT(1)
FROM
aAccountFinYearOpening
WHERE
Financialid=@intToFinID AND companyid=@intCompanyID
IF @intToCount = 0
BEGIN
SELECT
@intMaxToFinID =ISNULL(MAX(financialid),0)
FROM
aAccountFinYearOpening
WHERE
companyid=@intCompanyID AND companyid=@intCompanyID
IF @intMaxToFinID =0
BEGIN
SELECT
@intMaxToFinID= ISNULL(MIN(financialid),0)
FROM
afinancialyear
WHERE
companyid=@intCompanyID
END
END
ELSE
BEGIN
SET @intMaxToFinID=@intToFinID
END
SELECT
@dtToStartDate = CONVERT(DATETIME,CAST(startyear AS VARCHAR)
+''/''+CAST(StartMonth AS VARCHAR)+''/01'',101)
FROM
afinancialyear
WHERE
financialid=@intMaxToFinID AND companyid=@intCompanyID
IF @intDeptID=0
BEGIN
IF @strOnlyToDate<>''T''
BEGIN-- IF fromdate is not passed then Execution Not needed
UPDATE
#TempEntityAccounts
SET
FromOpeningBal=OB.OpenBalance
FROM
(SELECT
ra.companyid,ra.AccountID,CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(af.Openingamount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(af.Openingdepamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(af.Openingactualamount,0.0)),0.0) END OpenBalance
FROM
#TempEntityAccounts ra
LEFT OUTER JOIN aAccountFinYearOpening af
ON ra.CompanyID=af.CompanyID AND ra.AccountID=af.AccountID
WHERE
ra.companyid=@intCompanyID AND
ISNULL(af.Financialid,0)=@intMaxFromFinID
GROUP BY
ra.companyid, ra.AccountID) OB
WHERE
#TempEntityAccounts.companyiD=OB.CompanyID AND
#TempEntityAccounts.AccountID=OB.AccountID
UPDATE
#TempEntityAccounts
SET
FromJournalBalDr=Dr.JournalBalDr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalDr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND JournalDate BETWEEN
@dtFromStartDate AND @dtFromDate AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=0 AND mh.financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
UPDATE
#TempEntityAccounts
SET
FromJournalBalCr=Dr.JournalBalCr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalCr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtFromStartDate AND @dtFromDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=1 AND financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
END -- IF fromdate is not passed then Execution Not needed
UPDATE
#TempEntityAccounts
SET
ToOpeningBal=OB.OpenBalance
FROM
(SELECT
ra.companyid,ra.AccountID,CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(af.Openingamount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(af.Openingdepamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(af.Openingactualamount,0.0)),0.0) END OpenBalance       FROM
#TempEntityAccounts ra
LEFT OUTER JOIN aAccountFinYearOpening af
ON ra.CompanyID=af.CompanyID AND ra.AccountID=af.AccountID
WHERE
ra.companyid=@intCompanyID AND
ISNULL(af.Financialid,0)= @intMaxToFinID
GROUP BY
ra.companyid, ra.AccountID) OB
WHERE
#TempEntityAccounts.companyiD=OB.CompanyID AND
#TempEntityAccounts.AccountID=OB.AccountID
UPDATE
#TempEntityAccounts
SET
ToJournalBalDr=Dr.JournalBalDr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalDr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND JournalDate BETWEEN
@dtToStartDate AND @dtToDate AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=0 AND mh.financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
UPDATE
#TempEntityAccounts
SET
ToJournalBalCr=Dr.JournalBalCr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalCr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtToStartDate AND @dtToDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=1 AND financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
END
ELSE -- Department ID =0 Condition
BEGIN
IF @strOnlyToDate<>''T''
BEGIN-- IF fromdate is not passed then Execution Not needed
UPDATE
#TempEntityAccounts
SET
FromOpeningBal=OB.OpenBalance
FROM
(SELECT
ra.companyid,ra.AccountID,CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(af.Openingamount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(af.Openingdepamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(af.Openingactualamount,0.0)),0.0) END OpenBalance
FROM
#TempEntityAccounts ra
LEFT OUTER JOIN aAccountFinYearOpening af
ON ra.CompanyID=af.CompanyID AND ra.AccountID=af.AccountID
AND af.departmentid=@intDeptID
WHERE
ra.companyid=@intCompanyID AND
ISNULL(af.Financialid,0)=@intMaxFromFinID
GROUP BY
ra.companyid, ra.AccountID) OB
WHERE
#TempEntityAccounts.companyiD=OB.CompanyID AND
#TempEntityAccounts.AccountID=OB.AccountID
UPDATE
#TempEntityAccounts
SET
FromJournalBalDr=Dr.JournalBalDr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalDr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtFromStartDate AND @dtFromDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=0 AND vw.departmentid=@intDeptID AND
financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
UPDATE
#TempEntityAccounts
SET
FromJournalBalCr=Dr.JournalBalCr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalCr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtFromStartDate AND @dtFromDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=1 AND vw.departmentid=@intDeptID AND
financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
END-- IF fromdate is not passed then Execution Not needed
UPDATE
#TempEntityAccounts
SET
ToOpeningBal=OB.OpenBalance
FROM
(SELECT
ra.companyid,ra.AccountID,CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(af.Openingamount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(af.Openingdepamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(af.Openingactualamount,0.0)),0.0) END OpenBalance
FROM
#TempEntityAccounts ra
LEFT OUTER JOIN aAccountFinYearOpening af
ON ra.CompanyID=af.CompanyID AND ra.AccountID=af.AccountID
AND af.departmentid=@intDeptID
WHERE
ra.companyid=@intCompanyID AND
ISNULL(af.Financialid,0)=@intMaxToFinID
GROUP BY
ra.companyid, ra.AccountID) OB
WHERE
#TempEntityAccounts.companyiD=OB.CompanyID AND
#TempEntityAccounts.AccountID=OB.AccountID
UPDATE
#TempEntityAccounts
SET
ToJournalBalDr=Dr.JournalBalDr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalDr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtToStartDate AND @dtToDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=0 AND vw.departmentid=@intDeptID AND
financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
UPDATE
#TempEntityAccounts
SET
ToJournalBalCr=Dr.JournalBalCr
FROM
(SELECT
ea.CompanyID, ea.AccountID, CASE
WHEN @currency =''C'' THEN ISNULL(SUM(ISNULL(amount,0.0)),0.0)
WHEN @currency =''D'' THEN ISNULL(SUM(ISNULL(depamount,0.0)),0.0)
WHEN @currency =''A'' THEN ISNULL(SUM(ISNULL(actualamount,0.0)),0.0) END JournalBalCr
FROM
vwjournaldetails vw, moajournalheader mh,
#TempEntityAccounts ea
WHERE
ea.CompanyID=vw.CompanyID AND ea.AccountID=vw.AccountID AND
mh.journalid=vw.journalid AND (JournalDate BETWEEN
@dtToStartDate AND @dtToDate) AND
mh.companyid=@intCompanyID AND mh.cancel=0 AND
vw.journalcredit=1 AND vw.departmentid=@intDeptID AND
financialid > 0
GROUP BY
ea.CompanyID, ea.AccountID) Dr
WHERE
#TempEntityAccounts.companyiD=Dr.CompanyID AND
#TempEntityAccounts.AccountID=Dr.AccountID
END --Else of DeptID = 0
--Getting the Numerator Total
SELECT
a.companyID, a.Lev1GroupID, a.Lev1GroupDesc, a.Lev2GroupID, a.Lev2GroupDesc,
a.Lev3GroupID, a.Lev3GroupDesc, a.LastGroupID, a.LastGroupDesc,
a.LastLevel, a.EntityId, a.EntityDesc, a.RatioType, a.Multiplier,
SUM(a.calctype * (b.FromOpeningBal + (a.AccountType *
(b.FromJournalBalDr- b.FromJournalBalCr)))) FromNumBal,
SUM(a.calctype * (b.ToOpeningBal + (a.AccountType *
(b.ToJournalBalDr- b.ToJournalBalCr)))) ToNumBal
INTO
#TempRatioNumerator
FROM
##TempRatioEntityAccounts a, #TempEntityAccounts b
WHERE
a.CompanyID=b.CompanyID and a.AccountID=b.AccountID AND
a.Numerator=1
GROUP BY
a.companyID, a.Lev1GroupID, a.Lev1GroupDesc, a.Lev2GroupID, a.Lev2GroupDesc,
a.LastGroupDesc, a.Lev3GroupID, a.Lev3GroupDesc, a.LastGroupID, a.LastGroupDesc,
a.LastLevel, a.RatioType, a.Multiplier, a.EntityId, a.EntityDesc,
CONVERT(TINYINT,a.Numerator)
--Getting the Denominator Total
SELECT
a.companyID, a.Lev1GroupID, a.Lev1GroupDesc, a.Lev2GroupID, a.Lev2GroupDesc,
a.Lev3GroupID, a.Lev3GroupDesc, a.LastGroupID, a.LastGroupDesc,
a.LastLevel, a.EntityId, a.EntityDesc, a.RatioType, a.Multiplier,
SUM(a.calctype * (b.FromOpeningBal + (a.AccountType *
(b.FromJournalBalDr- b.FromJournalBalCr)))) FromDenoBal,
SUM(a.calctype * (b.ToOpeningBal + (a.AccountType *
(b.ToJournalBalDr- b.ToJournalBalCr)))) ToDenoBal
INTO
#TempRatioDenominator
FROM
##TempRatioEntityAccounts a, #TempEntityAccounts b
WHERE
a.CompanyID=b.CompanyID and a.AccountID=b.AccountID AND
a.Numerator=0
GROUP BY
a.companyID, a.Lev1GroupID, a.Lev1GroupDesc, a.Lev2GroupID, a.Lev2GroupDesc,
a.Lev3GroupID, a.Lev3GroupDesc, a.LastGroupID, a.LastGroupDesc,
a.LastLevel, a.RatioType, a.Multiplier, a.EntityId, a.EntityDesc,
CONVERT(TINYINT,a.Numerator)
SELECT
a.companyID, a.Lev1GroupID, a.Lev1GroupDesc, a.Lev2GroupID, a.Lev2GroupDesc,
a.Lev3GroupID, a.Lev3GroupDesc, a.LastGroupID, a.LastGroupDesc,
a.LastLevel, a.EntityId NumerEnityID, a.EntityDesc NumerEntityDesc,
a.RatioType, a.Multiplier, a.FromNumBal,a.ToNumBal,
b.FromDenoBal, b.ToDenoBal, b.EntityId DenorEnityID,
b.EntityDesc DenorEntityDesc,@strOnlyToDate ToDateOnly,
convert(int,c.GetAverageFigure) NumerAverage,
convert(int,d.GetAverageFigure) DenorAverage
FROM
#TempRatioDenominator b, #TempRatioNumerator a,AAccRatioEntitiesMaster c,
AAccRatioEntitiesMaster d
WHERE
a.LastGroupID=b.LastGroupID and c.EntityId=a.EntityId and  d.EntityId=b.EntityId
and  c.companyid=a.companyid and  d.companyid=b.companyid
DROP TABLE #TempRatioNumerator
DROP TABLE #TempRatioDenominator
DROP TABLE ##TempRatioEntityAccounts
DROP TABLE #TempEntityAccounts
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalanceAll]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalanceAll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created On : 02/01/2004
-- Created By : Hariharan R
--Comments    : To get opening balance togehter for all accounts
------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spOpeningBalanceAll] (@dtdate as varchar(10),
@intcompid as int,
@currency as char(2),
@intdepid as int = 0,
				    @intconsolidation as int=0)
AS
begin
	declare @intfinid as int,
	@intcount as int,
	@dtstartdate as datetime,
	@intmaxfinid as int,
	@OpenBal as numeric(18,2),
	@JournalBalDr as numeric(18,2),
	@JournalBalCr as numeric(18,2),
	@stracctype as char(1),
	@strresult as char(1),
	@strtype as char(1),
	@numtemp as numeric(18,2),
	@intRecCount as int,
	@intacid as int
Create table #TempOP (
	AccId	int,
	OPBal	Numeric(18,2),
	Processed	int)
	set nocount on	
-- create the temporary table to insert sub departments.
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int Primary Key)
	if @intconsolidation=0
-- get the sub depts
insert into #SubDepts1 values(@intdepid)
	else
insert into #SubDepts1
Exec spSelectAllSubDepartments @intdepid, @intcompid
	insert #TempOp	
	SELECT AccountID, 0 AcBal, 0 Processed  from
	(SELECT AccountID, 0 AcBal, 0 Processed FROM aAccountMaster AM,aGroupMaster GM,
	adeptAccounts d, #SubDepts1 dep
	WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND
	GM.CompanyID = am.companyid AND AM.CompanyID = @intcompid
	and am.accountid = d.daaccountid and d.daDepartmentid = dep.Deptid
	/*union
	select v.Accountid, 0, 0 from vwGlobalAccounts v, aAccountMaster a, aGroupMaster g
	where v.companyid = a.companyid and v.accountid = a.accountid and a.groupid = g.groupid
	AND (G.AccountType = ''A'' OR G.AccountType = ''L'') */) Process group by Process.AccountID
	order by Accountid
	
	set @intRecCount = 0
	Select @intRecCount =  count(*) from #TempOp  where Processed =0
	
	While @intRecCount <>0
	Begin
	Select top 1 @intacid = AccId from #TempOp where Processed =0
	set @strresult =''''
	set @OpenBal = 0.0
	set @JournalBalDr = 0.0
	set @JournalBalcr = 0.0
	if len(@currency) > 1
	begin
		set @strresult = right(@currency,1)	-- ''c'' for consilidated currency,
		set @currency = upper(left(@currency,1))	-- ''d'' for department currency
	end						-- ''a'' for account currency
	select @intfinid=min(financialid) from afinancialyear where @dtdate between
	convert(datetime,cast(startyear as varchar)+''/''+cast(startmonth as varchar)+''/01'',101)
	and dateadd(mm,12,convert(datetime,cast(startyear as varchar)+''/''+cast(startmonth as varchar)+''/01'',101) )
	and companyid= @intcompid
	select @intCount=count(*) from aaccountfinyearopening where Financialid=@intfinid
	and companyid=@intcompid	
	if @intcount=0
	begin
		select @intmaxfinid=isnull(max(financialid),0) from  aaccountfinyearopening
		where companyid=@intcompid -- and accountid=@intacid
		and companyid=@intcompid
		if @intmaxfinid =0
		begin
			select @intmaxfinid=isnull(min(financialid),0) from afinancialyear
			where companyid=@intcompid
		  	select	@dtstartdate = convert(datetime,cast(startyear as varchar)
			+''/''+cast(startmonth as varchar)+''/01'',101)  from afinancialyear where
			financialid=@intmaxfinid and companyid=@intcompid			
			if @intdepid=0
			begin
				select @OpenBal = case when @currency =''C'' then
				isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
				left outer join aaccountfinyearopening af on ac.accountid=af.accountid
				where ac.groupid=ag.groupid and ac.companyid=@intcompid and
				ac.accountid=@intacid group by af.accountid, AccountType
				select 	@journalBaldr= case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
				journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=0 and financialid > 0
			
				select 	@journalBalcr = case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from  vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate<=dateadd(d,-1, convert(datetime,@dtdate))
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=1 and financialid > 0
			end
			else
			begin
				select @OpenBal = case when @currency =''C'' then
				isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
				left outer join aaccountfinyearopening af on ac.accountid=af.accountid
				and af.departmentid IN (Select DeptId from #SubDepts1)
				where ac.groupid=ag.groupid and ac.companyid=@intcompid and
				ac.accountid=@intacid group by af.accountid, AccountType
				select 	@journalBaldr = case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
			
				select 	@journalBalcr = case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
			end
		end
		else
		begin
			select	@dtstartdate = convert(datetime,cast(startyear as varchar)
			+''/''+cast(startmonth as varchar)+''/01'',101) from afinancialyear where
			financialid=@intmaxfinid and companyid=@intcompid
			if @intdepid = 0
			begin
				select @OpenBal = case when @currency =''C'' then
				isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
				left outer join aaccountfinyearopening af on ac.accountid=af.accountid
				where ac.groupid=ag.groupid and ac.companyid=@intcompid and
				ac.accountid=@intacid group by af.accountid, AccountType
				select @journalBaldr = case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end from
				vwjournaldetails vw, moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=0 and financialid > 0
			
				select 	@journalBalcr= case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate <=dateadd(d,-1,convert(datetime,@dtdate)) --hari removed between and given and 020626
				and mh.companyid=@intcompid and mh.cancel=0 and
				vw.journalcredit=1 and financialid > 0
			end
			else
			begin
				select @OpenBal = case when @currency =''C'' then
				isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
				left outer join aaccountfinyearopening af on ac.accountid=af.accountid
				and af.departmentid IN (Select DeptId from #SubDepts1)
				where ac.groupid=ag.groupid and ac.companyid=@intcompid and
				ac.accountid=@intacid group by af.accountid, AccountType
				select @journalBaldr= case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
				moajournalheader mh where mh.journalid=vw.journalid and
				accountid=@intacid and JournalDate >= @dtstartdate and
				journaldate<=dateadd(d,-1,convert(datetime,@dtdate)) --hari removed between and given and 020626
				and mh.companyid = @intcompid
and mh.cancel = 0
and vw.journalcredit = 0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
			
				select @journalBalcr = case when @currency =''C'' then
				isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
				isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
				isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
				moajournalheader mh
where mh.journalid=vw.journalid
and accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
				journaldate <= dateadd(d, -1, convert(datetime, @dtdate))
				and mh.companyid = @intcompid
and mh.cancel = 0 and
				vw.journalcredit = 1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
			end
		end
	end
	else
	begin
		select	@dtstartdate = convert(datetime,cast(startyear as varchar)
		+''/''+cast(startmonth as varchar)+''/01'',101) from afinancialyear where
		financialid=@intfinid and companyid=@intcompid	
		if @intdepid = 0	
		begin
			select @OpenBal = case when @currency =''C'' then
			isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
			left outer join aaccountfinyearopening af on ac.accountid=af.accountid
			where ac.groupid=ag.groupid and ac.companyid=@intcompid and
			ac.accountid=@intacid group by af.accountid, AccountType
			select @journalBaldr = case when @currency =''C'' then
			isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
			moajournalheader mh where mh.journalid=vw.journalid and
			accountid=@intacid and JournalDate >= @dtstartdate and
			journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
			and mh.companyid=@intcompid and mh.cancel=0 and
			vw.journalcredit=0 and financialid > 0
			
			select @journalBalcr = case when @currency =''C'' then
			isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
			moajournalheader mh where mh.journalid=vw.journalid and
			accountid=@intacid and JournalDate >= @dtstartdate and
			journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
			and mh.companyid=@intcompid and mh.cancel=0 and
			vw.journalcredit=1 and financialid > 0
		end
		else
		begin
			select @OpenBal = case when @currency =''C'' then
			isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
			left outer join aaccountfinyearopening af on ac.accountid=af.accountid
			and af.departmentid IN (Select DeptId from #SubDepts1)
			where ac.groupid=ag.groupid and ac.companyid=@intcompid and
			ac.accountid=@intacid group by af.accountid, AccountType
			select @journalBaldr = case when @currency =''C'' then
			isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
			moajournalheader mh where mh.journalid=vw.journalid and
			accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
			journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
			and mh.companyid=@intcompid and mh.cancel=0 and
			vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
		
			select @journalBalcr = case when @currency =''C'' then
			isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
			isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
			isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
			moajournalheader mh where mh.journalid=vw.journalid and
			accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
			journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
			and mh.companyid=@intcompid and mh.cancel=0
and vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
		end
	end
	-- to get the type of the account
	select @stracctype = accounttype from aaccountmaster a, agroupmaster g where
	a.groupid  = g.groupid and a.companyid = g.companyid and a.accountid = @intacid
	set @numtemp = 0.0
	if (@stracctype =''A'' or @stracctype =''E'')
	begin
		set @numtemp = convert(numeric(18,2), @openbal + (@journalbaldr-@journalbalcr))
	end
	else
	begin
		set @numtemp =  convert(numeric(18,2), @openbal + (@journalbalcr - @journalbaldr))
	end
	Update #TempOp set Processed = 1, OPBal  = @numtemp where AccId = @intAcId
	Select @intRecCount =  count(*) from #TempOp  where Processed =0
	End 	--AccountsLoop ENd
-- drop sub depts temporary table
drop table #SubDepts1
	Select AccId, OPBal from #TempOp
	
	Drop table #TempOp
	set nocount off	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance_Detail]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : Sreejith G A
--Created On : 20100806
--spOpeningBalance_Detail ''20100101'',1
------------------------------------------------
--RefNo:1
--Modified By : VinothMurugan V
--Date    : 26/08/2010
---Purpose    : Increase The Length
CREATE  proc [dbo].[spOpeningBalance_Detail] (@strToDate as varchar(10), @intCompanyID as int) as
Begin
set nocount on
Declare @AcCode as varchar(200),  --RefNo:1
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(200),   --RefNo:1
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(200), --RefNo:1
Remarks varchar(1000),  --jyothish changed 250 to 1000
Type char(20),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),    --RefNo:1
AcDesc varchar(100),   --RefNo:1
AcType varchar(20),     --RefNo:1
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int,departmentid int)
Create table #BalSheetFinal(   companyid int,
Departmentid int ,
AccId int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(20),    --RefNo:1
GroupID int,
GroupName varchar(100),    --RefNo:1
DepartmentName varchar(100),  --RefNo:1
Balance numeric(18,2) )
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(day, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
if @intLastFinId = 0
Select @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, ------NEW MODIFIED
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, departmentid)
select  vss.CompanyId, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,
vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.AccountID,vss.departmentid
from
(SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid
from aaccountfinyearopening ad
left outer join   aaccountmaster AM on AM.accountid=ad.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
union all
SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid
from  #vwJournalDetails v
left outer join   aaccountmaster AM on AM.accountid=v.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
)vss
where
-- (VSS.AccountType = ''A'' OR VSS.AccountType = ''L'') AND
VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc,ParentGroupID
Update #BalSheet set  OBDr = opening.Openingamount from (Select AccountId,
CompanyId, Sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,
AccountId,departmentid) opening Where opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
and opening.departmentid= #BalSheet.departmentid
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A'' and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set  OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''E''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''E''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''I''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''I''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.Departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId, v.Departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and trialDeb.Departmentid=#BalSheet.departmentid
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.CompanyId, v.AccountId, v.departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid = #BalSheet.departmentid
Insert #BalSheetFinal(companyid,Departmentid,AccId,AccCode,AcDesc,AcType,GroupID,GroupName,DepartmentName,Balance)
SELECT b.companyid,b.Departmentid,b.AccId,b.AccCode,b.AcDesc,b.AcType,b.GroupId,b.Groupname,ad.departmentname,
(isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
from  #balsheet b
left outer join adepartmentmaster ad on ad.departmentid=b.departmentid
where ((( isnull(AcType,'''') =''A'') or ( isnull(AcType,'''') =''L'')
or ( isnull(AcType,'''') =''E'')
or ( isnull(AcType,'''') =''I'')
and
b.accCode is not null) or b.accCode is null)
set @GroupId = 0
Select * from #BalSheetFinal --where accid=918
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance_Adjustment]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance_Adjustment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By    : Benzigar S D
-- Created On    : 28/07/2009
-- Comments      : This SP is created for adjustment Entry
------------------------------------------------------------------------------------------
Create  PROCEDURE [dbo].[spOpeningBalance_Adjustment] (@dtdate as varchar(10),
@intacid as int,
@intcompid as int,
@currency as char(2),
@opbal as numeric(18,2) = 0.0 output,
@intdepid as int = 0,
@intconsolidation as int=0)
AS
begin
declare @intfinid as int,
@intcount as int,
@dtstartdate as datetime,
@intmaxfinid as int,
@OpenBal as numeric(18,2),
@JournalBalDr as numeric(18,2),
@JournalBalCr as numeric(18,2),
@stracctype as char(1),
@strresult as char(1),
@strtype as char(1),
@numtemp as numeric(18,2)
set nocount on
-- create the temporary table to insert sub departments.
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int Primary Key)
if @intconsolidation=0
-- get the sub depts
insert into #SubDepts1 values(@intdepid)
else
insert into #SubDepts1
Exec spSelectAllSubDepartments @intdepid, @intcompid
set @strresult =''''
set @OpenBal = 0.0
set @JournalBalDr = 0.0
set @JournalBalcr = 0.0
if len(@currency) > 1
begin
set @strresult = right(@currency,1) -- ''c'' for consilidated currency,
set @currency = upper(left(@currency,1)) -- ''d'' for department currency
end      -- ''a'' for account currency
select @intfinid = min(financialid) from vwFinyearPeriod where @dtdate between
sdate and edate and companyid= @intcompid
select @intcount=count(*) from aaccountfinyearopening where Financialid=@intfinid
and companyid=@intcompid
if @intcount=0
begin
select @intmaxfinid=isnull(max(financialid),0) from  aaccountfinyearopening
where companyid=@intcompid -- and accountid=@intacid
and companyid=@intcompid
if @intmaxfinid =0
begin
select @intmaxfinid=isnull(min(financialid),0) from afinancialyear
where companyid=@intcompid
select @dtstartdate = sdate  from vwFinyearperiod where
financialid=@intmaxfinid and companyid=@intcompid
if @intdepid=0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,
aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid group by af.accountid, AccountType
select  @journalBaldr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select  @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,1, convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid group by af.accountid, AccountType
select  @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select  @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
else
begin
select @dtstartdate = sdate from vwFinyearPeriod where
companyid = @intcompid and financialid = @intmaxfinid
if @intdepid = 0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid
group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from
vwjournaldetails vw, moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select  @journalBalcr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate <=dateadd(d,0,convert(datetime,@dtdate)) --hari removed between and given and 020626
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
and af.FinancialId = @intmaxfinid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid group by af.accountid, AccountType
select @journalBaldr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate)) --hari removed between and given and 020626
and mh.companyid = @intcompid
and mh.cancel = 0
and vw.journalcredit = 0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh
where mh.journalid=vw.journalid
and accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate <= dateadd(d, 0, convert(datetime, @dtdate))
and mh.companyid = @intcompid
and mh.cancel = 0 and
vw.journalcredit = 1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
end
else
begin
/*select @dtstartdate = convert(datetime,cast(startyear as varchar)
+''/''+cast(startmonth as varchar)+''/01'',101) from afinancialyear where
financialid=@intfinid and companyid=@intcompid  */
select @dtstartdate = sdate from vwFinyearPeriod where
companyid = @intcompid and financialid = @intfinid
if @intdepid = 0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intfinid  group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intfinid group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,0,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0
and vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
-- to get the type of the account
select @stracctype = accounttype from aaccountmaster a, agroupmaster g where
a.groupid  = g.groupid and a.companyid = g.companyid and a.accountid = @intacid
if (@stracctype =''A'' or @stracctype =''E'')
begin
set @numtemp = convert(numeric(18,2), @openbal + (@journalbaldr-@journalbalcr))
end
else
begin
set @numtemp =  convert(numeric(18,2), @openbal + (@journalbalcr - @journalbaldr))
end
select @opbal = @numtemp
if (@strresult = ''s'' )
begin
select @numtemp openingbal, @stracctype type
end
-- drop sub depts temporary table
drop table #SubDepts1
set nocount off
end
------------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--sp_helptext spopeningbalance
-- last modified : 11/12/2003
-- Modified by   : Kishore
-- comments  : Added department id as an argument made it to optional (12/05/03)
--               : Removed the accountid=@intacid on aAccountFinYearOpenig table.
--                 (on comparison with v2)  (10/06/2003)
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
/*
Ref No : 101
Modified By : Shine Das
On : 28.04.2011
Comments: Earlier there was no checking was done for parameter "@dtdate". So it will show wrong information if date is
given as lessthan starting date of minimum financial year.
*/
------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spOpeningBalance] (@dtdate as varchar(10),
@intacid as int,
@intcompid as int,
@currency as char(2),
@opbal as numeric(18,2) = 0.0 output,
@intdepid as int = 0,
@intconsolidation as int=0)
AS
begin
declare @intfinid as int,
@intcount as int,
@dtstartdate as datetime,
@intmaxfinid as int,
@OpenBal as numeric(18,2),
@JournalBalDr as numeric(18,2),
@JournalBalCr as numeric(18,2),
@stracctype as char(1),
@strresult as char(1),
@strtype as char(1),
@numtemp as numeric(18,2)
set nocount on
-- create the temporary table to insert sub departments.
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int Primary Key)
if @intconsolidation=0
-- get the sub depts
insert into #SubDepts1 values(@intdepid)
else
insert into #SubDepts1
Exec spSelectAllSubDepartments @intdepid, @intcompid
set @strresult =''''
set @OpenBal = 0.0
set @JournalBalDr = 0.0
set @JournalBalcr = 0.0
if len(@currency) > 1
begin
set @strresult = right(@currency,1) -- ''c'' for consilidated currency,
set @currency = upper(left(@currency,1)) -- ''d'' for department currency
end      -- ''a'' for account currency
select @intfinid = min(financialid) from vwFinyearPeriod where @dtdate between
sdate and edate and companyid= @intcompid
----shine added Ref No : 101
if @intfinid is null
begin
select @intfinid = min(financialid) from vwFinyearPeriod where companyid= @intcompid
end
---shine Ref No : 101 end
select @intcount=count(*) from aaccountfinyearopening where Financialid=@intfinid
and companyid=@intcompid
if @intcount=0
begin
select @intmaxfinid=isnull(max(financialid),0) from  aaccountfinyearopening
where companyid=@intcompid -- and accountid=@intacid
and companyid=@intcompid
if @intmaxfinid =0
begin
select @intmaxfinid=isnull(min(financialid),0) from afinancialyear
where companyid=@intcompid
select @dtstartdate = sdate  from vwFinyearperiod where
financialid=@intmaxfinid and companyid=@intcompid
if @intdepid=0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,
aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid group by af.accountid, AccountType
select  @journalBaldr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select  @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1, convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid group by af.accountid, AccountType
select  @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end  from vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select  @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
else
begin
select @dtstartdate = sdate from vwFinyearPeriod where
companyid = @intcompid and financialid = @intmaxfinid
if @intdepid = 0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intmaxfinid
group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from
vwjournaldetails vw, moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select  @journalBalcr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate <=dateadd(d,-1,convert(datetime,@dtdate)) --hari removed between and given and 020626
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
and af.FinancialId = @intmaxfinid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid group by af.accountid, AccountType
select @journalBaldr= case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate)) --hari removed between and given and 020626
and mh.companyid = @intcompid
and mh.cancel = 0
and vw.journalcredit = 0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh
where mh.journalid=vw.journalid
and accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate <= dateadd(d, -1, convert(datetime, @dtdate))
and mh.companyid = @intcompid
and mh.cancel = 0 and
vw.journalcredit = 1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
end
else
begin
/*select @dtstartdate = convert(datetime,cast(startyear as varchar)
+''/''+cast(startmonth as varchar)+''/01'',101) from afinancialyear where
financialid=@intfinid and companyid=@intcompid  */
select @dtstartdate = sdate from vwFinyearPeriod where
companyid = @intcompid and financialid = @intfinid
if @intdepid = 0
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intfinid  group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0 and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=1 and financialid > 0
end
else
begin
select @OpenBal = case when @currency =''C'' then
isnull(sum(isnull(af.Openingamount,0.0)),0.0) when @currency =''D'' then
isnull(sum(isnull(af.Openingdepamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(isnull(af.Openingactualamount,0.0)),0.0) end from agroupmaster ag,aaccountmaster ac
left outer join aaccountfinyearopening af on ac.accountid=af.accountid
and af.departmentid IN (Select DeptId from #SubDepts1)
where ac.groupid=ag.groupid and ac.companyid=@intcompid and
ac.accountid=@intacid and af.FinancialId = @intfinid group by af.accountid, AccountType
select @journalBaldr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0 and
vw.journalcredit=0
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
select @journalBalcr = case when @currency =''C'' then
isnull(sum(ISNULL(amount,0.0)),0.0) when @currency =''D'' then
isnull(sum(ISNULL(depamount,0.0)),0.0) when @currency =''A'' then
isnull(sum(ISNULL(actualamount,0.0)),0.0) end from  vwjournaldetails vw,
moajournalheader mh where mh.journalid=vw.journalid and
accountid=@intacid and JournalDate >= @dtstartdate and --hari removed between and given and 020626
journaldate<=dateadd(d,-1,convert(datetime,@dtdate))
and mh.companyid=@intcompid and mh.cancel=0
and vw.journalcredit=1
and vw.departmentid IN (Select DeptId from #SubDepts1)
and financialid > 0
end
end
-- to get the type of the account
select @stracctype = accounttype from aaccountmaster a, agroupmaster g where
a.groupid  = g.groupid and a.companyid = g.companyid and a.accountid = @intacid
if (@stracctype =''A'' or @stracctype =''E'')
begin
set @numtemp = convert(numeric(18,2), @openbal + (@journalbaldr-@journalbalcr))
end
else
begin
set @numtemp =  convert(numeric(18,2), @openbal + (@journalbalcr - @journalbaldr))
end
print  @openbal
print @journalbaldr
print @journalbaldr
select @opbal = @numtemp
if (@strresult = ''s'' )
begin
select @numtemp openingbal, @stracctype type
end
-- drop sub depts temporary table
drop table #SubDepts1
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPLdep]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetPLdep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By        : Aneesh
-- Created On      :
-- Modified By     : Hariharan
-- Modified Date   : 19/10/2004
--spBudgetPLdep ''20040301'',''20040430'',1,1,0,0,0
-- Comments        : Corrected the account type selection
-----------------------------------------------------------------------------------------
CREATE Procedure [dbo].[spBudgetPLdep]
(@strFromDate As VarChar(10), @strToDate As VarChar(10),  @IntCompanyID As Int,
@Intdepartmentid As Int, @BitcOns As Bit,  @Intlevel As Int = 0,
@IntcOnsolidatiOn As Int =0 ) As
Begin
Set NoCount On
Set Ansi_Warnings Off
Declare @AcCode As VarChar(100),
@AcID As Int,
@AccDesc As VarChar(100),
@GroupId As Int,
@CompanyName As VarChar(100),
@dtFromDate As Datetime,
@dtToDate As Datetime,
@dtfinstartdate As Datetime,
@AcCountOBCr As numeric(18,2),
@AcCountOBDr As numeric(18,2),
@dtPrevFinUnclosedSDate As Datetime,
@dtLastFinUnclosedEDate As Datetime,
@IntRecCount As Int,
@IntFromFinId As Int,
@IntLAstFinId As Int,
@IntCount As Int
Create Table #PL
(CompanyID Int,
AcID Int,
AccCode VarChar(100),
AccDesc VarChar(100),
AcType VarChar(1),
GroupID Int,
GroupName VarChar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DeBitAmt numeric(18,2),
CreDitAmt numeric(18,2),
PrvOBDr numeric(18,2),
PrvOBCr numeric(18,2),
PrvDeBitAmt numeric(18,2),
PrvCreDitAmt numeric(18,2),
BudgetBal numeric(18,2),
ParentGroupID Int,
DepartmentId Int)
Create Table #vwJournalDetails
(companyid Int,
journalid Int,
journaldetailid Int,
journalcredit Bit,
acCountid Int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid Int,
depamount numeric(18,2),
PostGroup Int)
Create Table #Tempjournalheader
(JournalID Int,
CompanyID Int,
JournalDate SmallDatetime,
ReferenceNo VarChar(100),
Remarks VarChar(250),
Type Char(10),
Cancel Bit,
Realised Bit,
CurrencyId Int,
FinancialID Int,
chequedate Datetime,
upDatetime Datetime,
bankdate Datetime)
Create Table #FilteredResult
(groupid Int ,
AcCountCode VarChar(50),
AcCountDesc VarChar(100),
groupdesc VarChar(100),
parentGroupid Int,
Orderno Int,
levelcode Int,
departmentid Int,
DepartmentName VarChar(50),
Checked Int,
AcCountId Int,
AccType VarChar(50))
Create Table #PLFinal
(CompanyID Int,
AccCode VarChar(100),
AccDesc VarChar(100),
AcType VarChar(1),
GroupID Int,
GroupName VarChar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DeBitAmt numeric(18,2),
CreditAmt numeric(18,2),
PrvOBDr numeric(18,2),
PrvOBCr numeric(18,2),
PrvDebitAmt numeric(18,2),
PrvCreditAmt numeric(18,2),
BudgetBal numeric(18,2),
AcId Int, DepartmentId Int,
Orderno Int,
levelcode Int,
Checked Int,
ParentGroupId Int)
-- create the tempOrary table to Insert sub departments
-- table name is given As #SubDepts1 to avoid cOnflicts
-- with #SubDepts inside the sp
Create Table #SubDepts1(DeptId Int)
If @IntcOnsolidatiOn=0
Insert Into #SubDepts1 Values(@IntDepartmentId)
Else-- get the sub depts Into the tempOrary table
Insert Into #SubDepts1 Exec spSelectAllSubDepartments @IntDepartmentId, @IntCompanyId
Select @dtFromDate = Convert(Datetime, @strFromDate)
Select @dtToDate = Convert(Datetime, @strToDate)
Select @IntFromFinId = FinancialId From vwfinYearperiod Where companyid = @Intcompanyid And
@strFromDate Between sdate And edate
Select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @IntLAstFinId = Max(FinancialId) From aAcCountFinYearOpening
Where CompanyId = @IntCompanyId And FinancialId <= @IntFromFinId
If @IntLAstFinId = 0
Select @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = (Select Min(financialid) From afinancialYear Where
companyid = @IntCompanyId ) And CompanyId= @IntCompanyId
Else
Select @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = @IntLAstFinId And CompanyId= @IntCompanyId
Insert #Tempjournalheader   Select H.* From moajournalheader h (Nolock)
Where  JournalDate <=@dtToDate
And h.CompanyId = @IntCompanyId
Insert #vwJournalDetails Select d.* From #Tempjournalheader h, vwJournalDetails d
(Nolock) Where  JournalDate <=@dtToDate
And h.JournalId = d.JournalId And h.CompanyId = d.CompanyId
And h.Cancel = 0 And h.CompanyId = @IntCompanyId
Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName ,
OBDr , OBCr , DeBitAmt , CrEDitAmt , ParentGroupID , DepartmentId )
Select GrpAcId.Companyid, AcCountID, AcCountCode, AcCountDesc, AcCountType,
GrpAcId.GroupID, GrpAcId.GroupDesc, 0, 0, 0, 0, ParentGroupID, departmentid  From
(Select AM.Companyid, AcCountID, AcCountCode, AcCountDesc, AcCountType, GM.GroupID,
GM.GroupDesc, 0 OpDeBit, 0 OpCredit, 0 DeBit, 0 Credit, ParentGroupID,
daDepartmentid departmentid  From aAcCountMAster AM, aGroupMAster GM,
adeptAcCounts d, #SubDepts1 dep  Where GM.GroupID = AM.GroupID And
(GM.AcCountType = ''I'' Or GM.AcCountType = ''E'') And GM.CompanyID = am.companyid
And AM.CompanyID = @IntCompanyID  And am.AcCountid = d.daAcCountId And
am.CompanyId = d.daCompanyId And d.dadepartmentid = dep.deptid  UniOn
Select AM.Companyid, am.AcCountID, AcCountCode, AcCountDesc, AcCountType,
GM.GroupID, GM.GroupDesc, 0, 0, 0, 0, ParentGroupID, deptid departmentid From
aAcCountMAster AM, aGroupMAster GM, vwGlobalAcCounts d, #SubDepts1 dep Where
GM.GroupID = AM.GroupID And (GM.AcCountType = ''I'' Or GM.AcCountType = ''E'') And
GM.CompanyID = am.companyid And AM.CompanyID = @IntCompanyID And
am.AcCountid = d.AcCountId And am.CompanyId = d.CompanyId) GrpAcId
Group By GrpAcId.Companyid, GrpAcId.AcCountID, GrpAcId.GroupID, GrpAcId.GroupDesc,
GrpAcId.AcCountCode, GrpAcId.AcCountDesc, GrpAcId.AcCountType, GrpAcId.ParentGroupID,
GrpAcId.GroupID, GrpAcId.GroupDesc, OpDeBit, OpCredit, DeBit, Credit,
ParentGroupID, departmentid
Update #PL Set OBDr = Abs(opening.Openingamount) From (Select AcCountId,
DepartmentId, CompanyId, Case When @BitCOns = 1 Then Openingamount Else OpeningDepamount
End Openingamount From  aacCountfinYearopening Where Financialid = @IntLAstFinId And
CompanyId = @IntCompanyId) opening Where opening.AcCountid = #PL.AcId And
opening.DepartmentId = #PL.DepartmentId And opening.CompanyId = #PL.CompanyID
And opening.CompanyId = @IntCompanyId And ((#PL.ACType = ''E''  And
opening.Openingamount >0) Or (#PL.ACType = ''I''  And  opening.Openingamount <0))
Update #PL Set OBCr = Abs(opening.Openingamount) From (Select AcCountId,
DepartmentId, CompanyId, Case When @BitCOns = 1 Then Openingamount Else OpeningDepamount End Openingamount
From aacCountfinYearopening Where Financialid = @IntLAstFinId And CompanyId = @IntCompanyId) opening Where
opening.AcCountid = #PL.AcId And opening.DepartmentId = #PL.DepartmentId
And opening.CompanyId = #PL.CompanyID And opening.CompanyId = @IntCompanyId
And ((#PL.ACType = ''E''  And opening.Openingamount <0) Or (#PL.ACType = ''I''  And
opening.Openingamount >0))
Update #PL Set OBDr = OBDr + IsNull(trialDeb.amount,0) From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtPrevFinUnclosedSDate And h.JournalDate <= @dtLastFinUnclosedEDate
Group By v.AcCountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.AcCountid = #PL.AcId And trialDeb.DepartmentId = #PL.DepartmentId
And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #PL Set OBCr = OBCr + IsNull(trialDeb.amount,0) From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h Where v.JournalCredit = 1 And h.JournalId = v.JournalId And
h.CompanyId = v.CompanyId And h.JournalDate >= @dtPrevFinUnclosedSDate And
h.JournalDate <= @dtLastFinUnclosedEDate Group By v.AcCountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.AcCountid = #PL.AcId And
trialDeb.DepartmentId = #PL.DepartmentId And trialDeb.CompanyId = #PL.CompanyID
And trialDeb.CompanyId = @IntCompanyId
Update #PL Set DeBitAmt = trialDeb.amount From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate
Group By v.AcCountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.AcCountid = #PL.AcId And trialDeb.DepartmentId = #PL.DepartmentId
And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #PL Set CreditAmt = trialDeb.amount From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 1 And  h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate Group By v.AcCountId,
v.DepartmentId, v.CompanyId) trialDeb Where trialDeb.AcCountid = #PL.AcId And
trialDeb.DepartmentId = #PL.DepartmentId  And trialDeb.CompanyId = #PL.CompanyID
And trialDeb.CompanyId = @IntCompanyId
--Aneesh
--new addition
--Select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtPrevFinUnclosedSDate )
Set  @dtLastFinUnclosedEDate = dateadd(dd, -1,  dateadd(yyyy, -1, @strFromDate))
Select @IntLAstFinId = Max(FinancialId) From aAcCountFinYearOpening
Where CompanyId = @IntCompanyId And FinancialId <= @IntLAstFinId-1
If @IntLAstFinId = 0
Select @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = (Select Min(financialid) From afinancialYear Where
companyid = @IntCompanyId ) And CompanyId= @IntCompanyId
Else
Select @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = @IntLAstFinId And CompanyId= @IntCompanyId
Update #PL Set PrvOBDr = Abs(opening.Openingamount) From (Select AcCountId, DepartmentId, CompanyId,
Case When @BitCOns = 1 Then Openingamount Else OpeningDepamount End Openingamount From
aacCountfinYearopening Where
Financialid = @IntLAstFinId And CompanyId = @IntCompanyId) opening Where
opening.AcCountid = #PL.AcId And opening.DepartmentId = #PL.DepartmentId
And opening.CompanyId = #PL.CompanyID And opening.CompanyId = @IntCompanyId
And ((#PL.ACType = ''E''  And opening.Openingamount >0) Or (#PL.ACType = ''I''  And
opening.Openingamount <0))
Update #PL Set PrvOBCr = Abs(opening.Openingamount) From (Select AcCountId,
DepartmentId, CompanyId, Case When @BitCOns = 1 Then Openingamount Else OpeningDepamount End Openingamount
From aacCountfinYearopening Where Financialid = @IntLAstFinId And CompanyId = @IntCompanyId) opening Where
opening.AcCountid = #PL.AcId And opening.DepartmentId = #PL.DepartmentId
And opening.CompanyId = #PL.CompanyID And opening.CompanyId = @IntCompanyId
And ((#PL.ACType = ''E''  And opening.Openingamount <0) Or (#PL.ACType = ''I''  And
opening.Openingamount >0))
Update #PL Set PrvOBDr = IsNull(PrvOBDr,0) + IsNull(trialDeb.amount,0) From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtPrevFinUnclosedSDate And h.JournalDate <= @dtLastFinUnclosedEDate
Group By v.AcCountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.AcCountid = #PL.AcId And trialDeb.DepartmentId = #PL.DepartmentId
And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #PL Set PrvOBCr = IsNull(PrvOBCr,0) + IsNull(trialDeb.amount,0) From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h Where v.JournalCredit = 1 And h.JournalId = v.JournalId And
h.CompanyId = v.CompanyId And h.JournalDate >= @dtPrevFinUnclosedSDate And
h.JournalDate <= @dtLastFinUnclosedEDate Group By v.AcCountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.AcCountid = #PL.AcId And
trialDeb.DepartmentId = #PL.DepartmentId And trialDeb.CompanyId = #PL.CompanyID
And trialDeb.CompanyId = @IntCompanyId
--new addition
Update #PL Set prvDeBitAmt = trialDeb.amount From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >=   dateadd(yyyy, -1, @strFromDate) And
h.JournalDate <= dateadd(yyyy,-1,@StrToDate)
Group By v.AcCountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.AcCountid = #PL.AcId And trialDeb.DepartmentId = #PL.DepartmentId
And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #PL Set prvCreditAmt = trialDeb.amount From (Select v.AcCountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From  #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 1 And  h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= dateadd(yyyy, -1, @strFromDate) And
h.JournalDate <= dateadd(yyyy,-1,@StrToDate)
Group By v.AcCountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.AcCountid = #PL.AcId And trialDeb.DepartmentId = #PL.DepartmentId
And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #PL Set BudgetBal = IsNull(PlanBal.PlanAmt,0)  From (Select bpdBudgetHeadID,
IsNull(Sum(bpdAmount),0) As PlanAmt From budgetplanheader bh,
budgetplAndetail bd, aAccountMaster a, aGroupmaster g  Where
bh.bphCompanyID= @intCompanyId And bh.bphcompanyid=bd.bpdcompanyid And
bh.bphBudgetPlanID=bd.bpdBudgetPlanID And bpdrevised=0 And bphcancelled=0  And
bphdepartmentid in (Select Deptid From #SubDepts1) And
bh.bphPlanYear = Year(@dtToDate) And
bpdMonthNo >= Month(@strFromdate) And bpdMonthNo <= Month(@dttodate) and
bpdBudgetHeadID = a.aCcountid and bpdCOmpanyId = a.CompanyId and a.GroupId = g.GroupId
and a.CompanyId = g.CompanyId And (g.accounttype =''i'' Or g.accounttype =''E'')
Group By bpdBudgetHeadID) PlanBal where #PL.AcID = bpdBudgetHeadID
If @IntCOnsolidatiOn = 0
Begin
Insert #FilteredResult(groupid , AcCountCode , AcCountDesc , groupdesc ,
parentGroupid,Orderno , levelcode , departmentid , DepartmentName, Checked,
AcCountId, AccType) Exec SpGroupLevelOrdering @IntCompanyId, @IntDepartmentId
End
Else
Begin
Insert #FilteredResult(groupid , AcCountCode ,  AcCountDesc , groupdesc ,
parentGroupid , Orderno , levelcode , departmentid , DepartmentName, Checked,
AcCountId, AccType) Exec SpGroupLevelOrdering @IntCompanyId, 0
End
Insert #PLFinal(CompanyID, AccCode, AccDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DeBitAmt, CreditAmt,PrvOBDr,PrvOBCr,prvDebitAmt, prvCreditAmt,BudgetBal, AcId, DepartmentId, Orderno, levelcode, Checked , ParentGroupId)
Select b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, Sum(b.OBDr),
Sum(b.OBCr), Sum(b.DeBitAmt), Sum(b.CreditAmt), IsNull(Sum(PrvOBDr),0), IsNull(Sum(PrvOBCr),0), IsNull(Sum(prvDebitAmt),0),IsNull(Sum(prvCreditAmt),0),IsNull(Sum(BudgetBal),0), b.AcId,
Min(r.DepartmentId), r.OrderNo, r.LevelCode, 0,  r.ParentGroupId
From #FilteredResult r Left Outer Join #PL b On  ((r.GroupId = b.GroupId  And r.AcCountId is null)
Or (r.GroupId = b.GroupId  And r.AcCountId  = b.AcId And r.AcCountId Is Not Null))
Group By b.CompanyId, r.OrderNo,r.LevelCode, r.AccType, r.GroupId, r.GroupDesc,
b.AcId, b.AccCode, b.AccDesc,  r.ParentGroupId
Having
((((((Sum(IsNull(creditamt,0)) - Sum(IsNull(deBitamt,0))) <> 0 Or
(Sum(IsNull(obcr,0)) - Sum(IsNull(obdr,0))) <> 0) And IsNull(r.AccType ,'''') =''I'') Or
(((Sum(IsNull(deBitamt,0)) - Sum(IsNull(creditamt,0))) <> 0 Or
(Sum(IsNull(obdr,0)) - Sum(IsNull(obcr,0))) <> 0) And IsNull(r.AccType ,'''') =''E''))
And b.accCode Is Not Null) Or b.accCode is null)  Order By r.Orderno
Set @GroupId = 0
-- TO avoid the groups which does not have any acCounts infOrmatiOn
Select top 1 @GroupID = GroupId From #plFinal Where Checked = 0 Order By OrderNo Desc
While @GroupID <>0
Begin
Set @IntCount = 0
Select @IntCount = Count(*) From #plFinal Where
((AccDesc Is Not Null And Groupid= @GroupID)Or ParentGroupid = @GroupID)
If @IntCount = 0
Delete From #plFinal Where GroupId = @GroupID
Else
Update #plFinal Set Checked = 1 Where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #plFinal Where Checked = 0
Order By OrderNo Desc
End
Set @GroupID  = 0
If @IntLevel>0
Delete From #plFinal Where LevelCode >= @IntLevel And AcId is null
Select * From #plFinal Order By OrderNo
Drop Table #SubDepts1
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
drop table #plFinal
drop table #FilteredResult
drop table #PL
Set NoCount On
Set Ansi_Warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetOpening]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetOpening]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By  	: Hariharan
--Created Date	: 12/08/2004
CREATE Proc [dbo].[spBudgetOpening] (@strFromDate as varchar(8),
@PlanId as int, @FormatId as int, @intCompanyId as int,
@bitCons as int, @intDepid as int= 0, @intconsolidation as int= 0,
@Actuals as int =0, @OpBalance as int =0 output  ) as
Set noCount on
Begin
Declare @dtDate as datetime, @dtPackageDate as datetime, @dtFromDate as datetime,
	@dtLastFinUnclosedEDate as datetime, @intNextFinId as int, @intLastFinId as int,
	@dtToDate AS datetime, 	@intFinId as int, @dtPrevFinUnclosedSDate as datetime	
Create table #vwJournalDetailsBO(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)
Create table #TempjournalheaderBO
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepid)
else
-- get the sub depts into the temporary table
insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepid, @intCompanyId
	
set @dtDate = convert(datetime, @strFromDate)
Select @dtPackageDate = packagedate from apackagesettings where companyid = @intCompanyId
if @Actuals =0
	set @dtToDate  = dateadd(d, -day(@dtPackageDate), @dtPackageDate)
else
	set @dtToDate  = dateadd(d, -1, @dtPackageDate)
	select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where @dtToDate between sdate and edate
	Select @intNextFinId = MIN(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId > @intFinId
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	insert #TempjournalheaderBO
	Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
	and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
	insert #vwJournalDetailsBO
	Select d.* from #TempjournalheaderBO h, vwJournalDetails d (nolock) where
	Journaldate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
	(Select Deptid from #SubDepts1)
Create table #BudgetOpening(
	 CompanyID int,
	 departmentid int,	
	 accountid int,
	 PlanYear  varchar(10),
	 OpeningAMt numeric(18,2),	
	 ActualAmt numeric(18,2),
	 AcType varchar(2))
if @Actuals =0
Begin
Insert into #BudgetOpening 	
	Select a.companyid, departmentid, a.accountid, 0,
	sum(isnull(bpdAmount,0)) bpdamount, 0, AccountType
	From aAccountMaster a, aGroupMaster g, aAccRepFormat af,
	aRepFormatAccounts b Left outer join
	(Select bphDepartmentId, bphplanyear, bphCompanyId, bpdbudgetheadid,
	bpdamount from  budgetplanheader BudH, budgetplandetail BudD where
	BudH.bphBudgetPlanID = Budd.bpdBudgetPlanID and
	BudH.bphCompanyID = Budd.bpdCompanyID and budd.bpdrevised=0
	and bphcancelled=0 and bpdmonthno < month(@dtDate) and
	bphplanyear=year(@dtDate) and BudH.bphBudgetPlanID = @PlanId
	and bpdmonthno >=month(@dtPackageDate)) budd
	on b.accountid = budd.bpdbudgetheadid and
	b.CompanyId = budd.bphCompanyId where a.Groupid = g.GroupId and
	a.CompanyId = g.CompanyId and b.formatid =  @FormatId  and
	b.accountid = a.accountid and b.companyid = a.companyid and
	b.Formatid = af.FormatId and b.companyid = af.companyid
	Group by  a.companyid, a.accountcode,a.accountdesc,
	a.accountid,b.formatid,  a.groupid, b.groupid, bphplanyear,
	departmentid, AccountType
End
Else
Begin
	 Insert into #BudgetOpening 	
	 Select a.companyid, departmentid, a.accountid,
0, 0 , 0, AccountType
	 From aAccountMaster a, aGroupMaster g, aAccRepFormat af, aRepFormatAccounts b
	 where a.Groupid = g.GroupId and a.CompanyId = g.CompanyId and
	 b.formatid =  @FormatId  and b.accountid = a.accountid and
	 b.companyid = a.companyid and b.Formatid = af.FormatId and
	 b.companyid = af.companyid
End
	if @intNextFinId >0
		set @intLastFinId = @intNextFinId
	Update #BudgetOpening set OpeningAMt = isnull(OpeningAMt,0) +
	isnull(opening.Openingamount,0) from
	(Select AccountId, DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End
	Openingamount from aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId and
	departmentid = @intDepid) opening Where
	opening.Accountid = #BudgetOpening.AccountId and
	opening.DepartmentId = #BudgetOpening.DepartmentId and
	opening.CompanyId = #BudgetOpening.CompanyID and
	opening.CompanyId = @intCompanyId and Opening.Departmentid = @intDepid
	
	set @intLastFinId = isnull(@intLastFinId,0)
	set @intNextFinId = isnull(@intNextFinId,0)
	if @intLastFinId <> @intNextFinId
	Begin
Update #BudgetOpening set OpeningAMt = OpeningAMt + isnull(trialDeb.amount,0)
	from (Select v.AccountId, v.DepartmentId, v.CompanyId, case When @BitCons = 1
	then Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetailsBO v, #TempjournalheaderBO h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BudgetOpening.AccountId and
	trialDeb.DepartmentId = #BudgetOpening.DepartmentId
	and trialDeb.CompanyId = #BudgetOpening.CompanyID and
	trialDeb.CompanyId = @intCompanyId and (#BudgetOpening.AcType =''A'' or
	#BudgetOpening.AcType =''E'')
	Update #BudgetOpening set OpeningAMt = OpeningAMt - isnull(trialDeb.amount,0)
	from (Select v.AccountId, v.DepartmentId, v.CompanyId, case When @BitCons = 1
	then Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetailsBO v, #TempjournalheaderBO h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BudgetOpening.AccountId and
	trialDeb.DepartmentId = #BudgetOpening.DepartmentId
	and trialDeb.CompanyId = #BudgetOpening.CompanyID and
	trialDeb.CompanyId = @intCompanyId and (#BudgetOpening.AcType =''A'' or
	#BudgetOpening.AcType =''E'')
	Update #BudgetOpening set OpeningAMt = OpeningAMt + isnull(trialDeb.amount,0) from
	(Select v.AccountId, v.DepartmentId, v.CompanyId, case When @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetailsBO v, #TempjournalheaderBO h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BudgetOpening.AccountId and
	trialDeb.DepartmentId = #BudgetOpening.DepartmentId and
	trialDeb.CompanyId = #BudgetOpening.CompanyID and
	trialDeb.CompanyId = @intCompanyId and (#BudgetOpening.AcType =''L'' or
	#BudgetOpening.AcType =''I'')
	Update #BudgetOpening set OpeningAMt = OpeningAMt - isnull(trialDeb.amount,0)
	from (Select v.AccountId, v.DepartmentId, v.CompanyId, case When @BitCons = 1
	then Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetailsBO v, #TempjournalheaderBO h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BudgetOpening.AccountId and
	trialDeb.DepartmentId = #BudgetOpening.DepartmentId and
	trialDeb.CompanyId = #BudgetOpening.CompanyID and
	trialDeb.CompanyId = @intCompanyId and (#BudgetOpening.AcType =''L'' or
	#BudgetOpening.AcType =''I'')
	End
	
	--Select * from #BudgetOpening
	Select @OpBalance = SUM(OpeningAmt) from #BudgetOpening
END
Set noCount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetingDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created  by   : Prem
-- Created Date  : 12/10/2004
--               : for making budgeting general ledger Reports
--          : taking the previous years actual amount and
--               : current years planned amount , to compare
CREATE PROCEDURE [dbo].[spBudgetingDetails] (@intCompanyID as int,
@intDepartmentId as int,
@intYear as int, @intPlanId as int, @bitcons as int= 0) AS
Begin
set nocount on
Create table #TempBudgetDetail
( AccountID int,
AccountDesc varchar(100),
BudgetMonth int,
LastyearValue  numeric(18,2),
YearofBudget    int,
PlannedValue  numeric(18,2)
)
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #TempMonthWiseAccount  --for making the values avalibale for 12 months for each accountid
( AccountId int,
AccountDesc varchar(100),
PrevJan  numeric(18,2),
CurrJan  numeric(18,2),
PrevFeb  numeric(18,2),
CurrFeb  numeric(18,2),
PrevMar  numeric(18,2),
CurrMar  numeric(18,2),
PrevApr  numeric(18,2),
CurrApr  numeric(18,2),
PrevMay  numeric(18,2),
CurrMay  numeric(18,2),
PrevJun  numeric(18,2),
CurrJun  numeric(18,2),
PrevJul  numeric(18,2),
CurrJul  numeric(18,2),
PrevAug  numeric(18,2),
CurrAug  numeric(18,2),
PrevSep  numeric(18,2),
CurrSep  numeric(18,2),
PrevOct  numeric(18,2),
CurrOct  numeric(18,2),
PrevNov  numeric(18,2),
CurrNov  numeric(18,2),
PrevDec  numeric(18,2),
CurrDec  numeric(18,2),
YearofBudget    int
)
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where
year(journaldate) = @intYear-1 and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
h.CompanyId = @intCompanyId AND h.journalid =d.journalid and
d.departmentid = @intDepartmentId
insert #TempBudgetDetail
Select v.accountid,a.accountdesc, month(journaldate),
case g.accounttype when ''A'' then
sum(case when journalcredit = 0 then  case when @bitcons = 1 then amount else depamount end else 0 end) -
sum(case when journalcredit = 1 then  case when @bitcons = 1 then amount else depamount end else 0 end) when
''E'' then sum(case when journalcredit = 0 then  case when @bitcons = 1 then amount else depamount end else 0 end) -
sum(case when journalcredit = 1 then  case when @bitcons = 1 then amount else depamount end else 0 end)
when ''I'' then sum(case when journalcredit = 1 then  case when @bitcons = 1 then amount else depamount end else 0 end) -
sum(case when journalcredit = 0 then  case when @bitcons = 1 then amount else depamount end else 0 end)
when ''L'' then sum(case when journalcredit = 1 then  case when @bitcons = 1 then amount else depamount end else 0 end) -
sum(case when journalcredit = 0 then  case when @bitcons = 1 then amount else depamount end else 0 end) end, @intYear, 0
from #Tempjournalheader h, #vwJournalDetails v, aaccountmaster a,
agroupmaster g where h.journalid = v.journalid and h.companyid = v.companyid and
h.cancel = 0 and v.departmentid = @intDepartmentId and h.companyid=@intCompanyID and
a.accountid = v.accountid and a.groupid = g.groupid and a.companyid = g.companyid
group by v.accountid,a.accountdesc, month(journaldate), g.accounttype
insert #TempBudgetDetail
Select b.bpdBudgetHeadID, b.AccountDesc, b.bpdMonthNo, 0, b.bphPlanYear, b.bpdAmount
from
(Select bpdBudgetHeadID, bpdMonthNo, 0 lastyear, bphPlanYear, bpdAmount, AccountDesc from
budgetplanheader, budgetplandetail, aAccountMaster a  where bphCompanyID = bpdCompanyID
and bphBudgetPlanID = bpdBudgetPlanID and bphCancelled = 0 and bphPlanYear = @intYear
and bphDepartmentid = @intDepartmentId and bpdBudgetPlanID = @intPlanId and
a.AccountId = bpdBudgetHeadID and a.Companyid = bpdCompanyId) b
Left outer join #TempBudgetDetail t on bpdBudgetHeadID = t.accountid
and b.bpdMonthNo = t.BudgetMonth where BudgetMonth is null
Update #TempBudgetDetail  set PlannedValue = bpdamount from
budgetplandetail where bpdBudgetPlanId = @intPlanId
and bpdBudgetHeadID = accountid and bpdMonthNo = BudgetMonth
and bpdCompanyId = @intCOmpanyId
--Select * from #TempBudgetDetail order by accountid,budgetmonth
insert #TempMonthWiseAccount
Select accountid,AccountDesc,
sum(PrevJan), sum(CurrJan),
sum(PrevFeb), sum(CurrFeb),
sum(PrevMar), sum(CurrMar),
sum(PrevApr), sum(CurrApr),
sum(PrevMay), sum(CurrMay),
sum(PrevJun), sum(CurrJun),
sum(PrevJul), sum(CurrJul),
sum(PrevAug), sum(CurrAug),
sum(PrevSep), sum(CurrSep),
sum(PrevOct), sum(CurrOct),
sum(PrevNov), sum(CurrNov),
sum(PrevDec), sum(CurrDec),
YearofBudget
from
(
Select accountid,AccountDesc,
case  BudgetMonth when 1 then LastyearValue else 0.00 end PrevJan,
case  BudgetMonth when 1 then PlannedValue else 0.00 end CurrJan,
case  BudgetMonth when 2 then LastyearValue else 0.00 end PrevFeb,
case  BudgetMonth when 2 then PlannedValue else 0.00 end CurrFeb,
case  BudgetMonth when 3 then LastyearValue else 0.00 end PrevMar,
case  BudgetMonth when 3 then PlannedValue else 0.00 end CurrMar,
case  BudgetMonth when 4 then LastyearValue else 0.00 end PrevApr,
case  BudgetMonth when 4 then PlannedValue else 0.00 end CurrApr,
case  BudgetMonth when 5 then LastyearValue else 0.00 end PrevMay,
case  BudgetMonth when 5 then PlannedValue else 0.00 end CurrMay,
case  BudgetMonth when 6 then LastyearValue else 0.00 end PrevJun,
case  BudgetMonth when 6 then PlannedValue else 0.00 end CurrJun,
case  BudgetMonth when 7 then LastyearValue else 0.00 end PrevJul,
case  BudgetMonth when 7 then PlannedValue else 0.00 end CurrJul,
case  BudgetMonth when 8 then LastyearValue else 0.00 end PrevAug,
case  BudgetMonth when 8 then PlannedValue else 0.00 end CurrAug,
case  BudgetMonth when 9 then LastyearValue else 0.00 end PrevSep,
case  BudgetMonth when 9 then PlannedValue else 0.00 end CurrSep,
case  BudgetMonth when 10 then LastyearValue else 0.00 end PrevOct,
case  BudgetMonth when 10 then PlannedValue else 0.00 end CurrOct,
case  BudgetMonth when 11 then LastyearValue else 0.00 end PrevNov,
case  BudgetMonth when 11 then PlannedValue else 0.00 end CurrNov,
case  BudgetMonth when 12 then LastyearValue else 0.00 end PrevDec,
case  BudgetMonth when 12 then PlannedValue else 0.00 end CurrDec,
YearofBudget From #TempBudgetDetail ) t group by accountid,AccountDesc,YearofBudget
select * from #TempMonthWiseAccount
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetBalSheet]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetBalSheet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--   : Created By : Aneesh , Hariharan
--   : Created On : 12-10-2004, 19/10/2004
--spbudgetbalsheet ''20040530'',1,1,0,0,0
--Comments        : Added profit & Loss column for budgeting
CREATE PROCEDURE [dbo].[spBudgetBalSheet]
(@strToDate As VarChar(10),  @IntCompanyID As Int,
@IntDepartmentId As Int, @BitcOns As Bit,
@Intlevel As Int = 0,@IntcOnsolidatiOn As Int =0 ) As
Begin
Set Nocount On
Declare @AcCode As VarChar(100),
@AcID As Int,
@dblDeBit As Numeric(18,2),
@dblCredit As Numeric(18,2),
@GroupID As Int,
@dtToDate As Datetime,
@dtFromDate As Datetime,
@strFromdate As VarChar(10),
@IntCount As Integer,
@IntFinId As Int,
@dtPrevFinUnclosedSDate As Datetime,
@dtLAstFinUnclosedEDate As Datetime,
@IntLAstFinId As Int,
@ProfitLossBd as numeric(18,2)
Create Table #vwJournalDetails
(companyid Int,
journalid Int,
journaldetailid Int,
journalcredit Bit,
accountid Int,
Amount Numeric(18,2),
ActualAmount Numeric(18,2),
departmentid Int,
depamount Numeric(18,2),
PostGroup Int)
Create Table #Tempjournalheader
(JournalID Int,
CompanyID Int,
JournalDate smallDatetime,
ReferenceNo VarChar(100),
Remarks VarChar(250),
Type Char(10),
Cancel Bit,
Realised Bit,
CurrencyId Int,
FinancialID Int,
chequedate Datetime,
upDatetime Datetime,
bankdate Datetime)
Create Table #BalSheet
(CompanyID Int,
AccCode VarChar(100),
AcDesc VarChar(100),
AcType VarChar(1),
GroupID Int,
GroupName VarChar(100),
OBDr Numeric(18,2),
OBCr Numeric(18,2),
DeBitAmt Numeric(18,2),
CreditAmt Numeric(18,2),
prvDeBitAmt Numeric(18,2),
prvCreditAmt Numeric(18,2),
BudgetBal Numeric(18,2),
ParentGroupID Int,
AccId Int,
DepartmentId Int)
Create Table #FilteredResult
(groupid Int ,
AccountCode VarChar(50),
AccountDesc VarChar(100),
groupdesc VarChar(100),
parentGroupid Int,
Orderno Int,
levelcode Int,
departmentid Int,
DepartmentName VarChar(50),
Checked Int,
AccountId Int,
AccType VarChar(50))
Create Table #BalSheetFinal
(CompanyID Int,
AccCode VarChar(100),
AcDesc VarChar(100),
AcType VarChar(1),
GroupID Int,
GroupName VarChar(100),
OBDr Numeric(18,2),
OBCr Numeric(18,2),
DeBitAmt Numeric(18,2),
CreditAmt Numeric(18,2),
prvDeBitAmt Numeric(18,2),
prvCreditAmt Numeric(18,2),
BudgetBal Numeric(18,2),
AccId Int, DepartmentId Int, Orderno Int,
levelcode Int,
Checked Int,
ProfitLoss Numeric(18,2),
ParentGroupId Int,
ProfitLossBd Numeric(18,2))
-- create the tempOrary Table to Insert sub departments
-- Table name is given As #SubDepts1 to avoid cOnflicts
-- with #SubDepts inside the sp
Create Table #SubDepts1(DeptId Int)
If @IntcOnsolidatiOn=0
Insert Into #SubDepts1 Values(@IntDepartmentId)
Else
-- get the sub depts Into the tempOrary Table
Insert Into #SubDepts1 Exec spSelectAllSubDepartments @IntDepartmentId, @IntCompanyId
Set @dtToDate = Convert(Datetime,@strToDate)
Select @dtFromDate = sdate, @strFromdate = Convert(VarChar,sdate,120),@IntFinId = financialid
From vwfinYearperiod Where Convert(Datetime,@strToDate,101) Between sdate And edate
Select @dtLAstFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @IntLAstFinId = Max(FinancialId) From aAccountFinYearOpening
Where CompanyId = @IntCompanyId And FinancialId <= @IntFinId
If @IntLAstFinId = 0
Select  @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = (Select Min(financialid) From afinancialYear Where
companyid = @IntCompanyId ) And CompanyId= @IntCompanyId
Else
Select  @dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
Where financialid = @IntLAstFinId And CompanyId= @IntCompanyId
Insert #Tempjournalheader
Select H.* From moajournalheader h (Nolock) Where journaldate>=@dtPrevFinUnclosedSDate
And JournalDate <=@dtToDate And h.CompanyId = @IntCompanyId
Insert #vwJournalDetails
Select d.* From #Tempjournalheader h, vwJournalDetails d (Nolock) Where
Journaldate>=@dtPrevFinUnclosedSDate And
JournalDate <=@dtToDate And h.JournalId = d.JournalId And h.CompanyId = d.CompanyId
And h.Cancel = 0 And h.CompanyId = @IntCompanyId And d.departmentid in
(Select Deptid From #SubDepts1)
--to change the parent group If level id > 0
Insert Into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DeBitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)
Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID, GroupDesc,OBDR,
OBCR, DeBitAmt, CreditAmt, ParentGroupID, AccountID, daDepartmentid
From (Select am.CompanyId, AccountID, AccountCode, AccountDesc,  AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DeBitAmt, 0 CreditAmt, ParentGroupID, daDepartmentid
From aAccountMAster AM,aGroupMAster GM, adeptAccounts d, #SubDepts1 dep
Where GM.GroupID = AM.GroupID And (GM.AccountType = ''A'' Or GM.AccountType = ''L'')
And GM.CompanyID = am.companyid And AM.CompanyID = @IntCompanyID And am.Accountid = d.daAccountId
And am.CompanyId = d.daCompanyId  And d.dadepartmentid = dep.deptid Union
Select am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DeBitAmt, 0 CreditAmt, ParentGroupID, dd.deptid
From aAccountMAster AM,aGroupMAster GM,
vwGlobalAccounts d, #SubDepts1 dd Where GM.GroupID = AM.GroupID And (GM.AccountType = ''A'' Or
GM.AccountType = ''L'') And GM.CompanyID = am.companyid And AM.CompanyID = @IntCompanyID
And am.Accountid = d.AccountId And am.CompanyId = d.CompanyId) GrpAcId
Group By CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc, OBDR, OBCR, DeBitAmt, CreditAmt, ParentGroupID, AccountID,
daDepartmentid Order By GrpAcId.AccountID
Update #BalSheet Set OBDr = opening.Openingamount From     (Select AccountId, DepartmentId, CompanyId,
Case When @BitCOns = 1 Then Openingamount Else OpeningDepamount End Openingamount From
aaccountfinYearopening Where
Financialid = @IntLAstFinId And CompanyId = @IntCompanyId) opening Where
opening.Accountid = #BalSheet.AccId And opening.DepartmentId = #BalSheet.DepartmentId
And opening.CompanyId = #BalSheet.CompanyID And opening.CompanyId = @IntCompanyId
Update #BalSheet Set OBDr = OBDr + IsNull(trialDeb.amount,0) From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtPrevFinUnclosedSDate And h.JournalDate <= @dtLAstFinUnclosedEDate
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
And #BalSheet.AcType =''A''
Update #BalSheet Set OBDr = OBDr - IsNull(trialDeb.amount,0) From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 1 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtPrevFinUnclosedSDate And h.JournalDate <= @dtLAstFinUnclosedEDate
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
And #BalSheet.AcType =''A''
Update #BalSheet Set OBCr = OBDr + IsNull(trialDeb.amount,0) From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h Where v.JournalCredit = 1 And h.JournalId = v.JournalId And
h.CompanyId = v.CompanyId And h.JournalDate >= @dtPrevFinUnclosedSDate And
h.JournalDate <= @dtLAstFinUnclosedEDate Group By v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId And
trialDeb.DepartmentId = #BalSheet.DepartmentId And
trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
And #BalSheet.AcType =''L''
Update #BalSheet Set OBCr = OBDr - IsNull(trialDeb.amount,0) From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h Where v.JournalCredit = 0 And h.JournalId = v.JournalId And
h.CompanyId = v.CompanyId And h.JournalDate >= @dtPrevFinUnclosedSDate And
h.JournalDate <= @dtLAstFinUnclosedEDate Group By v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId And
trialDeb.DepartmentId = #BalSheet.DepartmentId And
trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
And #BalSheet.AcType =''L''
Update #BalSheet Set DeBitAmt = trialDeb.amount From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #BalSheet Set CreditAmt = trialDeb.amount From (Select v.AccountId,
v.DepartmentId, v.CompanyId,
Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h Where v.JournalCredit = 1 And
h.JournalId = v.JournalId And h.CompanyId = v.CompanyId And
h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And
trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #BalSheet Set prvDeBitAmt = trialDeb.amount From (Select v.AccountId,
v.DepartmentId, v.CompanyId, Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
And h.JournalDate >= @dtFromDate And h.JournalDate <= (Select dateadd(d,-day(@dtToDate),@dtToDate))
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
Update #BalSheet Set prvCreditAmt = trialDeb.amount From (Select v.AccountId,
v.DepartmentId, v.CompanyId,
Case When @BitCOns = 1 Then Sum(IsNull(v.Amount,0)) Else
Sum(IsNull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h Where v.JournalCredit = 1 And
h.JournalId = v.JournalId And h.CompanyId = v.CompanyId And
h.JournalDate >= @dtFromDate And h.JournalDate <= (Select dateadd(d,-day(@dtToDate),@dtToDate))
Group By v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId And
trialDeb.DepartmentId = #BalSheet.DepartmentId
And trialDeb.CompanyId = #BalSheet.CompanyID And trialDeb.CompanyId = @IntCompanyId
Set  @IntCount = 0
Set @dblDeBit = 0.0
Set @dblCredit = 0.0
If @IntFinId > (Select Max(financialid) From aAccountfinYearopening Where
CompanyId = @IntCOmpanyId )
Begin
Select @dtPrevFinUnclosedSDate = sdate From vwfinYearperiod Where
CompanyId = @IntCompanyId And FinancialId = (Select Max(financialid) From
aAccountfinYearopening Where CompanyId = @IntCOmpanyId )
Select @dblDeBit = Case When @BitcOns = 1 Then Sum(IsNull(Amount,0)) Else Sum(IsNull(depAmount,0)) end
From #Tempjournalheader h, #vwJournalDetails d, aaccountmAster a, agroupmAster g
Where g.groupid = a.groupid And  d.accountid = a.accountid And h.journalid = d.journalid And h.companyid = d.companyid
And h.cancel =0 And journalcredit = 0 And
(journaldate >= @dtPrevFinUnclosedSDate And journaldate <= @dtLAstFinUnclosedEDate )
And (accounttype =''e'' Or accounttype =''i'') And h.financialid > 0
And d.departmentid IN (Select DeptId From #SubDepts1)
Select @dblCredit = Case When @BitcOns = 1 Then Sum(IsNull(Amount,0)) Else Sum(IsNull(depAmount,0)) end
From #Tempjournalheader h, #vwJournalDetails d, aaccountmAster a, agroupmAster g
Where g.groupid = a.groupid And  d.accountid = a.accountid And h.journalid = d.journalid And h.companyid = d.companyid
And h.cancel =0 And journalcredit = 1 And
(journaldate >= @dtPrevFinUnclosedSDate And journaldate <= @dtLAstFinUnclosedEDate )
And (accounttype =''e'' Or accounttype =''i'' ) And h.financialid > 0
And d.departmentid IN (Select DeptId From #SubDepts1)
If IsNull(@dblDeBit,0) + IsNull(@dblCredit,0) >0
Begin
Update #BalSheet Set OBDr = IsNull(OBDr,0) +
(IsNull(@dblCredit,0)) - IsNull(@dblDeBit,0) , OBCr = 0
Where AccId = (Select RetainedEarningsAcc From Asettings Where
CompanyId = @IntCompanyId)
End
End
Set @dblDeBit = 0.0
Set @dblCredit = 0.0
Select @dblDeBit = Case When @BitcOns = 1 Then Sum(IsNull(Amount,0)) Else Sum(IsNull(depAmount,0)) end
From #Tempjournalheader h, #vwJournalDetails d, aaccountmAster a, agroupmAster g
Where g.groupid = a.groupid And  d.accountid = a.accountid And h.journalid = d.journalid And h.companyid = d.companyid
And h.cancel =0 And journalcredit = 0 And (journaldate >= @strFromdate And journaldate <= @strtodate ) And
(accounttype =''e'' Or accounttype =''i'') And h.financialid > 0
And d.departmentid IN (Select DeptId From #SubDepts1)
Select @dblCredit = Case When @BitcOns = 1 Then Sum(IsNull(Amount,0)) Else Sum(IsNull(depAmount,0)) end
From #Tempjournalheader h, #vwJournalDetails d, aaccountmAster a, agroupmAster g
Where g.groupid = a.groupid And  d.accountid = a.accountid And h.journalid = d.journalid And h.companyid = d.companyid
And h.cancel =0 And journalcredit = 1 And (journaldate >= @strFromdate And journaldate <= @strtodate ) And
(accounttype =''e'' Or accounttype =''i'' ) And h.financialid > 0
And d.departmentid IN (Select DeptId From #SubDepts1)
--BUDGET VALUE TO BE PICKED HERE
Update #BalSheet Set BudgetBal = IsNull(PlanBal.PlanAmt,0)  From (Select bpdBudgetHeadID,
IsNull(Sum(bpdAmount),0) As PlanAmt From budgetplanheader bh,
budgetplAndetail bd, aAccountMaster a, aGroupmaster g  Where
bh.bphCompanyID= @IntCompanyId And bh.bphcompanyid=bd.bpdcompanyid And
bh.bphBudgetPlanID=bd.bpdBudgetPlanID And bpdrevised=0 And bphcancelled=0  And
bphdepartmentid in (Select Deptid From #SubDepts1) And
bh.bphPlanYear = Year(@dttodate) And
bpdMonthNo >= Month(@strFromdate) And bpdMonthNo <= Month(@dttodate) And
bpdBudgetHeadID = a.aCcountid and bpdCOmpanyId = a.CompanyId and
a.GroupId = g.GroupId and a.CompanyId = g.CompanyId
And (g.accounttype =''a'' Or g.accounttype =''l'') Group By bpdBudgetHeadID) PlanBal
Where #BalSheet.AccId = bpdBudgetHeadID
Set @ProfitLossBd = 0.0
Select @ProfitLossBd =  IsNull(Sum(bpdAmount),0) From budgetplanheader bh,
budgetplAndetail bd, aAccountMaster a, aGroupmaster g Where
bh.bphCompanyID= @IntCompanyId And bh.bphcompanyid=bd.bpdcompanyid And
bh.bphBudgetPlanID=bd.bpdBudgetPlanID And bpdrevised=0 And bphcancelled=0  And
bphdepartmentid in (Select Deptid From #SubDepts1) And bh.bphPlanYear = Year(@dttodate)
And bpdMonthNo >= Month(@strFromdate) And bpdMonthNo <= Month(@dttodate) and
bpdBudgetHeadID = a.aCcountid and bpdCOmpanyId = a.CompanyId and a.GroupId = g.GroupId
and a.CompanyId = g.CompanyId And g.accounttype =''E''
Select @ProfitLossBd =  @ProfitLossBd - IsNull(Sum(bpdAmount),0) From
budgetplanheader bh, budgetplAndetail bd, aAccountMaster a, aGroupmaster g Where
bh.bphCompanyID= @IntCompanyId And bh.bphcompanyid=bd.bpdcompanyid
And bh.bphBudgetPlanID=bd.bpdBudgetPlanID And bpdrevised=0 And bphcancelled=0  And
bphdepartmentid in (Select Deptid From #SubDepts1) And
bh.bphPlanYear = Year(@dttodate) And bpdMonthNo >= Month(@strFromdate) And
bpdMonthNo <= Month(@dttodate) and bpdBudgetHeadID = a.aCcountid and
bpdCOmpanyId = a.CompanyId and a.GroupId = g.GroupId
and a.CompanyId = g.CompanyId And g.accounttype =''I''
If @IntCOnsolidatiOn = 0
Begin
Insert #FilteredResult(groupid , AccountCode , AccountDesc , groupdesc ,
parentGroupid , Orderno , levelcode , departmentid , DepartmentName, Checked,
AccountId, AccType)  Exec SpGroupLevelOrdering @IntCompanyId, @IntDepartmentId
End
Else
Begin
Insert #FilteredResult(groupid , AccountCode , AccountDesc , groupdesc ,
parentGroupid ,  Orderno , levelcode , departmentid , DepartmentName, Checked,
AccountId, AccType) Exec SpGroupLevelOrdering @IntCompanyId, 0
End
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DeBitAmt, CreditAmt,prvDeBitAmt, prvCreditAmt , BudgetBal ,AccId, departmentid,
Orderno, levelcode, Checked,ProfitLoss, ParentGroupId, ProfitLossBd)
Select b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, Sum(b.OBDr),
Sum(b.OBCr),  Sum(b.DeBitAmt), Sum(b.CreditAmt), IsNull(Sum(prvDeBitAmt),0),IsNull(Sum(prvCreditAmt),0),
IsNull(Sum(BudgetBal),0),  b.AccId, 0, r.OrderNo, r.LevelCode,  0,
IsNull(@dblDeBit,0) - IsNull(@dblCredit,0) Bal, r.ParentGroupId, @ProfitLossBd From
#FilteredResult r left outer join #balsheet b On
((r.GroupId = b.GroupId  And r.AccountId Is Null) Or (r.GroupId = b.GroupId  And
r.AccountId  = b.AccId And r.AccountId is not null)) Group By b.CompanyId, r.OrderNo, r.AccType,
r.GroupId, r.GroupDesc, r.LevelCode, r.ParentGroupId, b.AccId, b.AccCode, b.AcDesc
having ((((Sum(IsNull(obdr,0)) + Sum(IsNull(obcr,0)) + Sum(IsNull(deBitamt,0)) - Sum(IsNull(creditamt,0))) <> 0 And
IsNull(r.AccType,'''') =''A'') Or ((Sum(IsNull(obdr,0)) + Sum(IsNull(obcr,0)) + Sum(IsNull(creditamt,0))) -  Sum(IsNull(deBitamt,0))
<> 0 And IsNull(r.AccType,'''') =''L'') And b.accCode is not null) Or b.accCode Is Null)
And (r.AccType =''A'' Or r.AccType =''L'' )  Order By r.Orderno
Set @GroupId = 0
-- TO avoid the groups which does not have any accounts infOrmatiOn
Select top 1 @GroupID = GroupId From #BalSheetFinal Where Checked = 0 Order By OrderNo Desc
While @GroupID <>0
Begin
Set @IntCount = 0
Select @IntCount = count(*) From #BalSheetFinal Where
((AcDesc is not Null And Groupid= @GroupID) Or ParentGroupid = @GroupID)
If @IntCount = 0
Delete From #BalSheetFinal Where GroupId = @GroupID
Else
Update #BalSheetFinal Set Checked = 1 Where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal Where Checked = 0
Order By OrderNo Desc
End
If @IntLevel>0
Delete From #BalSheetFinal Where LevelCode >= @IntLevel And AccId Is Null
Select * From #BalSheetFinal Order By OrderNo
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
Drop Table #BalSheet
Drop Table #FilteredResult
Drop Table #BalSheetFinal
Set Nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSHeaderBackUp03052011]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSHeaderBackUp03052011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified By: Nidheesh
--Modified on:24-09-09
--Comments: increased the size of @strRemarks to 250
------------------------------------------------------------
-- Upgraded by: Regin T.
-- Upgraded on: 21-08-2010
-- Upgrade:
--  Old method of generating bill number consumed more time,since it depends on the max of all bill numbers.
--  The more the db size the more the time to find max.So in new method, the bill number is generated based on
--  the last bill number saved in losPosHeaderLastBillNo.
-- Reference: RefNo-1
------------------------------------------------------------
-- Upgraded by: Regin T.
-- Upgraded on: 18-10-2010
-- Upgrade:
--  In counter login, bill number generation is skipped since it is already generated in exe and received as input.
-- Reference: RefNo-2
------------------------------------------------------------
-- Upgraded by: MANUNADH.U
-- Upgraded on: 18-03-2011
------------------------------------------------------------
-- Upgraded by: NIDHEESH PV
-- Upgraded on: 06-04-2011
-- Upgrade: POS BILLID,POS BILLNO IS GENERATED IN THE SP FOR ALL SHOPS(BOTH COUTER WISE & NO COUTER WISE)
-- Reference: RefNo-3
create PROC [dbo].[spInsertPOSHeaderBackUp03052011]
@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,2),
@intDiscount As Numeric(18,2),
@intBillAmt As Numeric(18,2),
@intCashAccId As Int,
@intCustId As Int,
@strRemarks As Varchar(250),
@intCmpExRate As Numeric(18,2),
@strBillNo As Varchar(30),
@strConCardNo as Varchar(50),
@intDiscountAmt as Numeric(18,2),
@intBalanceAmt as Numeric(18,2) ,
@intDeliveryNeeded  as Int=0,
@BillId as Int=0 output  --RefNo-3 --BILLID IS RETURNED AS AN OUTPUT PARAMETER
As
Begin
Declare @intDepId As Int
Declare @strUser As Varchar(20)
Declare @intSalesAccId As Int
Declare @intWholeSale As Int
Declare @strCardNo as Varchar(20)
declare @BillNo as Varchar(30)
--declare @BillId as int
--Finding the User Name 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
----TO GET POSBILLNO AND POSBILLID---RefNo-3--STARS-----
EXEC spMagnolia_GeneratePosBill @intShopId, @intCounterId, @BillNo OUTPUT, @BillId OUTPUT
SET @strBillNo=@BillNo
SET @intBillId=@BillId
----TO GET POSBILLNO AND POSBILLID-----RefNo-3--ENDS---
--Insertion is done in the following sequence
--poshShopID,poshBillID,poshBillNo,poshBillDate,poshCustomerName,poshCancelled,poshCancelledRemarks,poshRecAddUser,
--poshRecModifyUser,poshPosted,poshDiscount,poshBillAmount,poshCashAccID,poshSalesAccID,poshCompanyID,poshReturned,
--poshWholesale,poshcbid,poshExchangeRate,poshfuturevc,updatetime,poshDepartmentid,poshsalespersonid,poshcustomerid,
--poshCustomerCardNo,poshfutureint,poshcurexrates,rowguid,poshdepexrate,poshexchangerates,poshUserId,poshCounterId
Insert InTo losPosHeader
(
poshShopID,poshBillID,poshBillNo,poshBillDate,poshCustomerName,poshCancelled,poshCancelledRemarks,poshRecAddUser,
poshRecModifyUser,poshPosted,poshDiscount,poshBillAmount,poshCashAccID,poshSalesAccID,poshCompanyID,poshReturned,
poshWholesale,poshcbid,poshExchangeRate,poshfuturevc,updatetime,poshDepartmentid,poshsalespersonid,
poshcustomerid,poshCustomerCardNo,poshfutureint,poshcurexrates,rowguid,poshdepexrate,poshexchangerates,
poshUserId,poshCounterId,ContactCardNo,poshDiscountAmt,poshBalance,poshBillTime,poshDeliveryNeeded
)
Values
(
@intShopId,@intBillId,@strBillNo,@dtBillDate,@strCustName,  0,   @strRemarks,@strUser,
NULL,    0,  @intDiscount,@intBillAmt, @intCashAccId,@intSalesAccId, 1,    0,
@intWholeSale,NULL,  @intCmpExRate,  NULL, GetDate(), @intDepId,  @intSalesPerId,
@intCustId,  @strCardNo,   NULL,   NULL,  NewId(),@intDepExRate,@strExRate,
@intUserId,@intCounterId,@strConCardNo,@intDiscountAmt,@intBalanceAmt,right(current_timestamp,7),@intDeliveryNeeded
)
print @BillId
End
-----------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSHeader]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified By: Nidheesh
--Modified on:24-09-09
--Comments: increased the size of @strRemarks to 250
------------------------------------------------------------
-- Upgraded by: Regin T.
-- Upgraded on: 21-08-2010
-- Upgrade:
--  Old method of generating bill number consumed more time,since it depends on the max of all bill numbers.
--  The more the db size the more the time to find max.So in new method, the bill number is generated based on
--  the last bill number saved in losPosHeaderLastBillNo.
-- Reference: RefNo-1
------------------------------------------------------------
-- Upgraded by: Regin T.
-- Upgraded on: 18-10-2010
-- Upgrade:
--  In counter login, bill number generation is skipped since it is already generated in exe and received as input.
-- Reference: RefNo-2
------------------------------------------------------------
-- Upgraded by: MANUNADH.U
-- Upgraded on: 18-03-2011
------------------------------------------------------------
-- Upgraded by: NIDHEESH PV
-- Upgraded on: 06-04-2011
-- Upgrade: POS BILLID,POS BILLNO IS GENERATED IN THE SP FOR ALL SHOPS(BOTH COUTER WISE & NO COUTER WISE)
-- Reference: RefNo-3
------------------------------------------------------------
--Upgraded By  : VinothMurugan V.
--Date         : 23/02/2011
--Purpose      : adding cheque id and pos date column  (For Sonee POS - PD Cheque)
--Last Updated by : Bijesh.B as on 03/05/2011
--Comments        : Since this upgradation was missing in server,its added
--BackUp          : spInsertPOSHeaderBackUp03052011
--Last Updated by : Jyothish as on 24/11/2011
----@intDepExRate   and @intCmpExRate decimel width is chaged
------------------------------------------------------------
--RefNo-4
--Upgraded By  : Bijesh.B
--Date         : 27/12/2011
--Purpose      : Need Tin for Cash customer
--Ticket id    :BLE-583962 (Sonee)
------------------------------------------------------------
CREATE PROC [dbo].[spInsertPOSHeader]
@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),
@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),
@strBillNo As Varchar(30),
@strConCardNo as Varchar(50),
@intDiscountAmt as Numeric(18,2),
@intBalanceAmt as Numeric(18,2) ,
@intDeliveryNeeded  as Int=0,
@BillId as Int=0 output,  --RefNo-3 --BILLID IS RETURNED AS AN OUTPUT PARAMETER
@intChequeId as int=null,
@PostdateChk as bit=0,
@CustomerTIN as varchar(50)=''''     --RefNo-4 added new column
As
Begin
Declare @intDepId As Int
Declare @strUser As Varchar(20)
Declare @intSalesAccId As Int
Declare @intWholeSale As Int
Declare @strCardNo as Varchar(20)
declare @BillNo as Varchar(30)
--declare @BillId as int
--Finding the User Name 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
----TO GET POSBILLNO AND POSBILLID---RefNo-3--STARS-----
EXEC spMagnolia_GeneratePosBill @intShopId, @intCounterId, @BillNo OUTPUT, @BillId OUTPUT
SET @strBillNo=@BillNo
SET @intBillId=@BillId
----TO GET POSBILLNO AND POSBILLID-----RefNo-3--ENDS---
--Insertion is done in the following sequence
--poshShopID,poshBillID,poshBillNo,poshBillDate,poshCustomerName,poshCancelled,poshCancelledRemarks,poshRecAddUser,
--poshRecModifyUser,poshPosted,poshDiscount,poshBillAmount,poshCashAccID,poshSalesAccID,poshCompanyID,poshReturned,
--poshWholesale,poshcbid,poshExchangeRate,poshfuturevc,updatetime,poshDepartmentid,poshsalespersonid,poshcustomerid,
--poshCustomerCardNo,poshfutureint,poshcurexrates,rowguid,poshdepexrate,poshexchangerates,poshUserId,poshCounterId
Insert InTo losPosHeader
(
poshShopID,poshBillID,poshBillNo,poshBillDate,poshCustomerName,poshCancelled,poshCancelledRemarks,poshRecAddUser,
poshRecModifyUser,poshPosted,poshDiscount,poshBillAmount,poshCashAccID,poshSalesAccID,poshCompanyID,poshReturned,
poshWholesale,poshcbid,poshExchangeRate,poshfuturevc,updatetime,poshDepartmentid,poshsalespersonid,
poshcustomerid,poshCustomerCardNo,poshfutureint,poshcurexrates,rowguid,poshdepexrate,poshexchangerates,
poshUserId,poshCounterId,ContactCardNo,poshDiscountAmt,poshBalance,poshBillTime,poshDeliveryNeeded,poshChequeAccID,
PosPostDate,poshCustomerTIN
)
Values
(
@intShopId,@intBillId,@strBillNo,@dtBillDate,@strCustName,  0,   @strRemarks,@strUser,
NULL,    0,  @intDiscount,@intBillAmt, @intCashAccId,@intSalesAccId, 1,    0,
@intWholeSale,NULL,  @intCmpExRate,  NULL, GetDate(), @intDepId,  @intSalesPerId,
@intCustId,  @strCardNo,   NULL,   NULL,  NewId(),@intDepExRate,@strExRate,
@intUserId,@intCounterId,@strConCardNo,@intDiscountAmt,@intBalanceAmt,
right(current_timestamp,7),@intDeliveryNeeded,@intChequeId,@PostdateChk,@CustomerTIN
)
--print @BillId
End
-----------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalanceMIS]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalanceMIS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spBankCashBalanceMIS    Script Date: 18/01/2003 9:45:44 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE proc [dbo].[spBankCashBalanceMIS] @intCompanyID as int, @strCurdate as varchar(10) as
set nocount on
begin
Declare
	@intSlNo as int,
	@intAccountID as int,
	@strAccountDesc as varchar(250),
	@intComCurrencyID as int,
	@intAccCurrencyID as int,
	@numFacility as numeric(18,2),
	@OpenDebit as numeric(18,2),
	@OpenCredit as numeric(18,2),
	@openamount as numeric(18,2),
	@openactualamount as numeric(18,2),
	@strCurrency as varchar(100),
	@numDebitBal as numeric(18,2),
	@numCreditBal as numeric(18,2),
	@numBalance as numeric(18,2),
	@numPostdatedPayments as numeric(18,2),
	@numPostdatedreceipts as numeric(18,2),
	@numopening as numeric(18,2),
	@dtcurdate as datetime,
	@currencyexrate as numeric(18,8)
	set @dtcurdate = convert(datetime,@strcurdate)
Create table #BankCashBalanceMIS(
	Slno int,
	AccDesc varchar(250),
	Opening numeric(18,2),
	Facility numeric(18,2),
	Balance numeric(18,2),
	postdatedpayments numeric(18,2),
	postdatedreceipts numeric(18,2),
	netbalance numeric(18,2),
	Currency varchar(100),
	exchangerate numeric(18,8)
	)
	begin tran
	declare AccountCur cursor for
	select AccountID, AccountDesc, BudgetAmount, isnull(Openingamount,0.0),
	 isnull(Openingactualamount,0.0), CurrencyID from
	aaccountmaster
	where groupid = (select bankgroupid from asettings where companyid = @intCompanyID)
	and companyid = @intcompanyid  order by groupid,CurrencyID,AccountDesc
	open AccountCur
	set @intSlno = 1
	fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,
	@Openamount,  @Openactualamount, @intAccCurrencyID
	while @@fetch_status <> -1
	begin		
		select @strCurrency = CurrencyName  from aCurrencyMaster c where
		c.CurrencyID = @intAccCurrencyID and c.companyid = @intCompanyID
		if (@openamount < 0.0)
		begin
			set @opendebit =0.0
			set @opencredit = abs(@openactualamount)
		end	
		else
		begin
			set @opendebit = @openactualamount
			set @opencredit = 0.0
		end			
		select @numDebitBal = isnull(sum(actualamount),0) from vwjournaldetails JD,
		moajournalheader JH, acompanymaster c where  c.companyid = jh.companyid
		and c.financialid = jh.financialid and JD.journalid = JH.journalid and
		JH.cancel = 0 and JH.companyid = JD.companyid and JH.companyid = @intcompanyid
		and JD.journalcredit = 0 and JD.AccountID = @intAccountID and jh.financialid <> 0
		select @numCreditBal = isnull(sum(actualamount),0) from vwjournaldetails JD,
		moajournalheader JH, acompanymaster c where  c.companyid = jh.companyid and
		c.financialid = jh.financialid and JD.journalid = JH.journalid and JH.cancel = 0
		and JH.companyid = JD.companyid and JH.companyid = @intcompanyid and
		JD.journalcredit = 1 and JD.AccountID = @intAccountID and jh.financialid <> 0
						
		select @numpostdatedpayments = isnull(sum(creditactualamt),0) from
		vwpostdatedpayments where companyid = @intcompanyid and accountid =
		@intAccountID and chequedate > @dtcurdate
		select @numpostdatedreceipts = isnull(sum(debitactualamt),0) from
		vwpostdatedreceipts where companyid = @intcompanyid and accountid =
		@intAccountID and chequedate > @dtcurdate			
		set @numBalance = (@numDebitBal + @OpenDebit ) - (@numCreditBal + @openCredit )
		set @numopening = @OpenDebit - @openCredit
		insert into #BankCashBalanceMIS values (@intSlno, @strAccountDesc,
		@numopening, @numFacility, @numBalance,@numpostdatedpayments,
		@numpostdatedreceipts,@numbalance + @numpostdatedpayments -
		@numpostdatedreceipts, @strCurrency, 1)
		
		set @intSlNo = @intSlNo + 1
		set @numDebitBal = 0
		set @numCreditBal = 0
		set @numBalance = 0	
		set @OpenCredit = 0
		set @OpenDebit = 0
		set @strCurrency = '' ''
		set @numpostdatedpayments =0
		set @numpostdatedreceipts = 0	
		fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,
		@Openamount, @Openactualamount, @intAccCurrencyID
	end	
	commit tran
end
select * from #BankCashBalanceMIS
close AccountCur
Deallocate AccountCur
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopDebitNote]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopDebitNote]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on	: 18/07/2002
-- Modified by		: leo
-----------------------------------------------------------------------------------------
-- Modified on      : 02/01/2003
-- Modified by      : Kishore
-- Comments         : Added code to insert depAmount and to convert amount
-----------------------------------------------------------------------------------------
-- Modified on      : 10/06/2003, 20/11/2003
-- Modified by      : Kishore, Hariharan R
-- Comments         : corrected the problem in debit credit (On comparison with v2)
--		    : Exchange rate declarations made with precision 8
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spULShopDebitNote] (@intCompanyId as int, @intShopID as int) AS
Begin
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intCustomerId as int
	Declare @intVendorId as int
	Declare @intOtherAccId as int
	Declare @intFinancialID as int
	Declare @intDCID as int
	Declare @strdcNo as varchar(50)
	Declare @dtdcDate as datetime
	Declare @strRemarks as varchar(250)
	Declare @intDepartmentID as int
	Declare @intCompanyCurID as int
	Declare @numBuyingRate as numeric(18,8)
	Declare @intTransCurId as int
	Declare @numAverageRate as numeric(18,8)
	Declare @numTransRate as numeric(18,8)		
	declare @bitDebit as bit
	declare @bitOppDebit as bit
	declare @numAmount as numeric(18,2)
	declare @dtutime as datetime,
	@numDepExRate as numeric(18, 8),
	@numConExRate as numeric(18, 8),
	@intCurrencyId as int,
	@strExRates VarChar(250),	
	@numAccExRate Numeric(18, 8),
	@numTransEr Numeric(18, 8),
	@numAaccAmt Numeric(18, 2),
	@numTemp Numeric (18, 2)
	
	set nocount on	
	--get the companyCurrencyId
	select @intCompanyCurID = CurrencyId from aCompanyMaster where CompanyId = @intCompanyId
	/* getting the maximum Journal id from journal table */
	select @intJournalid = isnull(max(JournalID),0) from MOaJournalHeader where CompanyId = @intCompanyId
	set @intJournalID = @intJournalID + 1
	Declare dcCur cursor for
		Select losDCNId, losDCNNo, losDCNDate, losDCNCustomerId,
		losDCNVendorId, losDCNOtherAccId, losDCNDebit,
		losDCNdetails , losDCNAmount, updatetime,
		losdcnDepartmentId, losExchangeRate, losDepExRate, losdExchangeRates
		from losDebitCreditNote
		where losDCNPosted = 0 and losDCNCompanyId = @intCompanyId
		and losDCNCancelled = 0 and losDCNShopid = @intShopid
	open dcCur
	fetch next from dcCur into @intdcID, @strdcNo, @dtdcDate,
		@intCustomerId, @intVendorId,
		@intOtherAccId, @bitdebit, @strRemarks, @numAmount,
		@dtutime, @intDepartmentid, @numTransRate,
		@numDepExRate, @strExRates
	while @@Fetch_status = 0
	begin
		--to take financialid from afinancialyear table with curfinancialyear=1
		select @intFinancialid = financialid from vwfinyearperiod where @dtdcDate between sdate and edate
		set @intJournalDetailID = 1
		-- customer
		if (@intCustomerId is not null)	
		begin		
			select @intTransCurId = CurrencyId
				from aCustomerMaster
				where CompanyId = @intCompanyId and CustomerId = @intCustomerId
			exec spReturnExRate @intTransCurId, @strExRates,
				@numTransEr output
			insert into moaJournalHeader (JournalID, CompanyId, JournalDate,
				referenceno, remarks,financialID,Type, CurrencyId,chequedate,updatetime) values
				(@intJournalID, @intCompanyId, @dtdcDate, @strdcNo,
				 @strRemarks, @intFinancialID, ''POSDCN'', @intTransCurId, @dtdcdate, @dtutime)
	
			if (@bitdebit =0)
			begin
				set @bitOppDebit = 1
			end
			else
			begin
				set @bitOppDebit = 0
			end
			set @intJournalDetailID = 1
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
				JournalCrEDit, CustomerId, Amount, actualAmount,
				DepAmount, departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyId,
				@bitOppDebit, @intCustomerId,
				(@numAmount * @numTransRate), @numAmount,
				@numAmount * @numDepExRate, @intDepartmentID)
			
			set @intJournalDetailID = @intJournalDetailID + 1
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intOtherAccId
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numAmount,
					@numAaccAmt output
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
				JournalCrEDit, AccountID, Amount, actualAmount,
				DepAmount, departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyId,
				@bitDebit, @intOtherAccId,
				(@numAmount * @numTransRate), @numaAccAmt,
				@numAmount * @numDepExRate, @intDepartmentID)
		end
		-- vendor
		if (@intVendorId is not null)
		begin
			select @intTransCurId = CurrencyId from aVendorMaster
				where CompanyId = @intCompanyId and VendorId = @intVendorId
			exec spReturnExRate @intTransCurId, @strExRates,
				@numTransEr output
			insert into moajournalheader (JournalID, CompanyId, JournalDate,
				referenceno, remarks,financialID,Type, CurrencyId, chequedate, updatetime) values
				(@intJournalID, @intCompanyId, @dtdcDate, @strdcNo, @strRemarks,@intFinancialID,
				''POSDCN'', @intTransCurId,@dtdcdate, @dtutime)	
			set @intJournalDetailID = 1
			if (@bitdebit =0)
			begin
				set @bitOppDebit = 1
			end
			else
			begin
				set @bitOppDebit = 0
			end
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
				JournalCrEDit, VendorId, Amount, actualAmount,
				DepAmount, departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyId, @bitOppDebit,
				@intVendorId,
			       (@numAmount * @numTransRate), @numAmount,
				@numAmount * @numDepExRate, @intDepartmentID)
			
			set @intJournalDetailID = @intJournalDetailID + 1
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intOtherAccId
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numAmount,
					@numAaccAmt output
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
				JournalCrEDit, AccountID, Amount, actualAmount, DepAmount,
				departmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyId,
				@bitDebit, @intOtherAccId,
				(@numAmount * @numTransRate), @numaAccAmt,
				@numAmount * @numDepExRate, @intDepartmentID )
		end
		update losDebitCreditNote set losDCNPosted = 1
			where losDCNId = @intdcID
			and losDCNShopid = @intshopid
			and losDCNCompanyId = @intCompanyId
	
		set @intJournalID = @intJournalID + 1
	
		fetch next from dcCur into @intdcID, @strdcNo, @dtdcDate, @intCustomerId,
			@intVendorId, @intOtherAccId, @bitdebit, @strRemarks,
			@numAmount, @dtutime, @intDepartmentid, @numTransRate,
			@numDepExRate, @strExRates
	end	-- for dccur
	Close dcCur
	Deallocate dcCur
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULSerBookingCancellation]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSerBookingCancellation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by : Lawrence.J
-- Created on : 20/06/2003
-- Comments   : Booking cancellation
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------
--Modified on                   : 21/08/2003, 10/10/2003
--Modified by                   : Reji Abraham, Hariharan R
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
--			       : given spconvertequiamount  	
----------------------------------------------------------------
CREATE proc [dbo].[spULSerBookingCancellation] @intCompanyID as int, @intshopid as int AS
Begin
	Declare @intadvAccountID as int
	Declare @intCashAccountID as int
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dtBookDate as datetime
	Declare @strBookingNo as varchar(50)
	Declare @intbookingid as int
	Declare @strRemarks as varchar(250)
	Declare @intCustomerid as int
	Declare @intDepartmentID as int
	Declare @numtotalinvValue as numeric(18,2)
	Declare @intComCurID as int
	declare @numer as numeric(28,8)
	declare @dtutime as datetime
	declare @numadvance as numeric(18,2)
	declare @Date1 as datetime
	declare @ShopId as int
	declare @numDep as numeric(28,8)
	declare @strExRates varchar(250)
	declare @numRespAmount as numeric(18,2)
	
	set @strExRates=''''
	/* 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
	select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid
	set @intJournalID = @intJournalID + 1
	Declare invcur cursor for
	select bkcancellId,bkcancellno,bkcancelldate,
	case when sercallbkhcustomerid is not null  then sercallbkhcustomerid end CustomerID,
	case when serCallBkhshopid is not null  then serCallBkhshopid end Shopid,
	bkcancelldetails,serbookhdepartmentid,serbookadvanceamount, serbookhcmpexrate,
	sercallbkhupdatetime serbookhupdatetime,serbookadvanceacc, serbookhcashacc,
	serbookhdepexrate, serbookhexchangerates from losbookingcancellation left outer join
	losservicebookingheader bk on bkcancellbookingId=serbookhid   inner join
	loscallbookingheader los on los.serCallBkhid=serbookhrefid and
	los.serCallBkhcompanyid=bk.serbookhcompanyid and bk.serbookhshopid=los.serCallBkhshopid
where sercallbkhcancelled = 0 and  bkcancellcomapnyid=serbookhCompanyID and
	serbookhshopid=bkcancellshopid and bkcancellcancelled=0 and serbookadvanceamount > 0 and
	bkcancellshopid =@intshopid and bkcancellcomapnyid=@intcompanyid
	open invcur
	fetch next FROM invcur into @intbookingid, @strBookingNo, @dtBookDate, @intcustomerid,
	@ShopId,@strremarks, @intdepartmentid, @numadvance, @numer, @dtutime, @intadvAccountID,
	@intCashAccountID,@numDep, @strExRates
	
	while @@Fetch_status = 0
	begin
		--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtBookDate
		between sdate and edate
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
		referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime)
		values
		(@intJournalId, @intCompanyId, @dtBookDate, @strBookingNo,
		@strRemarks, @intFinancialID, ''BC'', @intcomCurID, @dtBookDate, @dtutime)
		set @intJournalDetailID = 1		
		
		exec spConvertEquiamount @intCashAccountID, ''a'', @intadvAccountID, ''a'',
		@strExRates, @numadvance, @numRespAmount output, ''a''
		/* crediing the advance account with the full invoice Amount */
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intadvAccountID, @numadvance * @numer, @numRespAmount
		,@intDepartmentID,@numadvance*@numDep)
		set @intJournalDetailID = @intJournalDetailID +1
		
		-- DEBITING CASH Account
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intCashAccountID, @numadvance * @numer, @numadvance,
		@intDepartmentID,@numadvance*@numDep)			
		/* mark the record as posted */
		update losbookingcancellation set bkcancellposted=1 WHERE
		bkcancellcomapnyid = @intCompanyID and bkcancellshopid = @intshopid and
		bkcancellbookingId = @intbookingid
		set @intJournalID = @intJournalID + 1
		fetch next FROM invcur into @intbookingid, @strBookingNo, @dtBookDate,
		@intcustomerid,@ShopId,@strremarks, @intdepartmentid, @numadvance, @numer,
		@dtutime, @intadvAccountID, @intCashAccountID,@numDep, @strExRates  		
		
	end
	Close invcur
	Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosForSoneeAsOn04042011]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosForSoneeAsOn04042011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spULShopPOS
--------------------------------------------------------------------------
-- Created on      : 28/03/2007
-- Created by      : Shinu
-- Comments      : V4
-- added SubDepartment  also
------------------------------------------------------------------------------
--RefNo-1
-- Modified on      :  28-03-2010
-- Modified by      :  Yogesh Joe
-- Comments         :  To avoid the error "String or binary data would be truncated".
--  				   Added LEFT(), while inserting referenceno to journal header
------------------------------------------------------------------------------
/*
RefNo-2
Modified on      : 04-04-2011
Modified by	   : Bijesh.B
BackUp           : spULShopPosBackUpAsOn04042011
Comments		   : PD Cheque - POS Bill payment may be Full Cash,Full PD Cheque
					 or Partial Payment (ie,both Cash and PD Cheque)
*/
------------------------------------------------------------------------------
CREATE  PROC [dbo].[spULShopPosForSoneeAsOn04042011](@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 @dtposDate as datetime
Declare @strposNo as varchar(50)
Declare @intposid as int
Declare @strRemarks as varchar(250)
Declare @intDiscountAccountID as int
Declare @numDiscount as numeric(18,2)
Declare @intDepartmentID as int
Declare @intSubDepartmentID as int
Declare @numtotalposValue as numeric(18,2)
Declare @numtotaldiscountValue as numeric(18,2)
Declare @numtotalcostValue as numeric(18,2)
Declare @intComCurID as int
Declare @intinventoryaccid as int
Declare @intcostofgoodsaccid as int
declare @numer as numeric(28,8)
declare @numactualamt as numeric(18,2)
declare @dtutime as datetime
declare @strshop as varchar(100)
declare @dtupdatetime as datetime
declare @strfirsttransno as varchar(50)
declare @strlasttransno as varchar(50)
declare @straccountcode as varchar(25)
declare @intpltransaccid as varchar(25)
declare @intcomdeptid as varchar(25)
declare @numprofittrans as numeric(7,5)
declare @intcomprofitaccid as int
declare @depsalesval as numeric(18,2)
declare @depcostval as numeric(18,2)
declare @actcostamt as numeric(18,2)
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)
-- ALTER 2 tables one for having all the pos trans of the day of the shop
-- one to have records groupwise
CREATE table #allpos(
pbillid int,
pbilldate datetime,
pbillno varchar(100),
pcashaccid  int,
psalesaccid  int,
psalesamt numeric(18,2),
pcostamt numeric(18,2),
per numeric(28,8),
updatetime  datetime,
departmentid int,
deper numeric(28,8),
exchangerates varchar(250))
CREATE table #nposting(
pdate datetime,
cashaccid int,
salesaccid int,
salesamt numeric(18,2),
costamt numeric(18,2),
actamt numeric(18,2),
actcostamt numeric(18,2),
depsalesamt numeric(18,2),
depCostamt numeric(18,2),
updatetime datetime,
departmentid int,
exrates varchar(250))
/* 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
select @intcomcurid = currencyid from acompanymaster
where companyid = @intcompanyid
select @intdiscountaccountid = discountaccountid,
@numprofittrans = isnull(RevisedCostPricePercent,0)
from ashops where shopid = @intshopid
select @strshop = shopname, @intSubDepartmentID =SubDepartmentID from ashops where shopid = @intshopid
select @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid,
@intpltransaccid = profittransfercontrolacc, @intcomdeptid  = companydepartment,
@intcomprofitaccid = compprofitshareacc from
apackagesettings where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
set @numTotalposValue = 0.0
set @numtotaldiscountvalue =0.0
set @numTotalcostValue = 0.0
-- inserting all the day rec to the temp1 table
insert into #allpos
	 SELECT poshbillid, poshbilldate, poshbillno, poshcashaccid,
	 poshSalesAccId, isnull(sum(posdUnitPrice),0),
	 isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0),
	 poshExchangeRate, max(updatetime), poshDepartmentid, poshdepexrate, poshexchangerates
	 FROM losposheader ph, losposdetail pd
	 WHERE ph.poshshopid = pd.posdshopid
	 and ph.poshbillid = pd.posdbillid
	 and ph.poshcancellED = 0
	 and ph.poshpostED = 0
	 and ph.poshCompanyID = @intCompanyID
	 and ph.poshshopid = @intshopid
	 and isnull(PosPostDate,0)=0 --RefNo-2
	 group by poshbillid, poshbilldate, poshbillno,
	 poshDepartmentid, poshcashaccid,
	 poshsalesaccid, poshexchangerate, poshdepexrate, poshexchangerates
--RefNo-2 Start --------------------------------------------
UNION ALL
	 SELECT ph.poshbillid, poshbilldate, poshbillno, poshcashaccid,
	 poshSalesAccId,
	 --isnull(sum(posdUnitPrice),0),
	 (ph.poshBillAmount-pdChq.Amount),
	 isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0),
	 poshExchangeRate, max(ph.updatetime), poshDepartmentid, poshdepexrate, poshexchangerates
	 FROM losposheader ph, losposdetail pd,ahqPostDatedChequeDetails pdChq
	 WHERE ph.poshshopid = pd.posdshopid
	 and ph.poshbillid = pd.posdbillid
	 and ph.poshcancellED = 0
	 and ph.poshpostED = 0
	 and ph.poshCompanyID = @intCompanyID
	 and ph.poshshopid = @intshopid
	 and pdChq.PoshBillID = ph.poshbillid
	 and isnull(pdChq.Cancel,0)=0
	 and pdChq.CompanyID = @intCompanyID
	 and pdChq.ShopID = @intshopid
	 group by ph.poshbillid, poshbilldate, poshbillno,
	 poshDepartmentid, poshcashaccid,
	 poshsalesaccid, poshexchangerate, poshdepexrate, poshexchangerates
	 ,ph.poshBillAmount,pdChq.Amount
	 having (ph.poshBillAmount-pdChq.Amount)>0
--RefNo-2 End --------------------------------------------
--insert the grouped values into the temp2 table
insert into #nposting
select pbilldate, pcashaccid, psalesaccid, sum(psalesamt * per), sum(pcostamt * per),
sum(psalesamt), sum(pcostamt), sum(psalesamt * deper),
sum(pcostamt * deper), max(updatetime),
departmentid, max(Exchangerates)
from #allpos
group by pbilldate, pcashaccid, psalesaccid, departmentid,
exchangerates
Declare poscur cursor for
select  pdate, cashaccid, salesaccid, salesamt, costamt,actamt, actcostamt, updatetime,
accountcode, departmentid, depsalesamt, depcostamt, exrates
from #nposting, aaccountmaster where cashaccid = accountid
open poscur
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
while @@Fetch_status = 0
begin
--TO GET TRANSACTION EXCHANGE RATE --------------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
--TO GET TRANSACTION EXCHANGE RATE <---------------
set @strfirsttransno= ''''
set @strlasttransno=''''
--hari added to form the reference number 020204
select  @strfirsttransno= poshbillno from losposheader where poshbillid in
(select min(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
select @strlasttransno = poshbillno from losposheader where poshbillid in
(select max(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtposdate between sdate and edate
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dtposDate,
LEFT(@strfirsttransno + ''_'' + @strlasttransno + '' - '' + @straccountcode,50) ,--RefNo-1
''POS Total Sales'',@intFinancialID,''pos'', @intcomCurID,@dtposdate,  @dtupdatetime)
-- rtrim(@strshop)+ ''_'' + ''POS''+ ''_'' + convert(varchar,getdate(),120)
set @intJournalDetailID = 1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @numactualamt,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
-- change made so that the trade discount should not be treated as discount in accounts
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intSalesAccountID, @numtotaldiscountvalue, @numAaccAmt,@intDepartmentID,
@depsalesval ,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
-- DEBITING BANK
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcashaccountid, @numtotaldiscountvalue , @numactualamt,
@intDepartmentID, @depsalesval,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intINVentoryAccID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
/* crediing the INVENTORY with the full cost Amount */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intINVentoryAccID, @numTotalcostValue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcostofgoodsaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
-- DEBITING THE COST OF GOODS ACCOUNT
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcostofgoodsaccid, @numtotalcostvalue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID)
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
if @numprofittrans <> 0
begin
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcomprofitaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
-- debit company profit account with shop department
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01 ,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
select @intCurrencyid = c.currencyid from aaccountmaster c,
aaccountmaster a where c.currencyid = a.currencyid and
c.companyid = a.companyid and a.accountid = @intpltransaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
set @intJournalDetailID = @intJournalDetailID +1
-- credit transfer control account with shop department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- credit transfer control account with comp department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
end -- for profit trans
set @intJournalID = @intJournalID + 1
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
end
Close poscur
Deallocate poscur
/* mark the record as postED */
update losposheader set poshpostED =1 from #allpos p WHERE poshbillid = pbillid
and  poshCompanyID = @intCompanyID and poshshopid = @intshopid
drop table #allpos
drop table #nposting
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn05042011]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosBackUpAsOn05042011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------
---
-- Created on      : 28/03/2007
-- Created by      : Shinu
-- Comments      : V4
-- added SubDepartment  also
------------------------------------------------------------------------------
--RefNo-1
-- Modified on      :  28-03-2010
-- Modified by      :  Yogesh Joe
-- Comments         :  To avoid the error "String or binary data would be truncated".
--  				   Added LEFT(), while inserting referenceno to journal header
------------------------------------------------------------------------------
CREATE  PROC [dbo].[spULShopPosBackUpAsOn05042011] (@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 @dtposDate as datetime
Declare @strposNo as varchar(50)
Declare @intposid as int
Declare @strRemarks as varchar(250)
Declare @intDiscountAccountID as int
Declare @numDiscount as numeric(18,2)
Declare @intDepartmentID as int
Declare @intSubDepartmentID as int
Declare @numtotalposValue as numeric(18,2)
Declare @numtotaldiscountValue as numeric(18,2)
Declare @numtotalcostValue as numeric(18,2)
Declare @intComCurID as int
Declare @intinventoryaccid as int
Declare @intcostofgoodsaccid as int
declare @numer as numeric(28,8)
declare @numactualamt as numeric(18,2)
declare @dtutime as datetime
declare @strshop as varchar(100)
declare @dtupdatetime as datetime
declare @strfirsttransno as varchar(50)
declare @strlasttransno as varchar(50)
declare @straccountcode as varchar(25)
declare @intpltransaccid as varchar(25)
declare @intcomdeptid as varchar(25)
declare @numprofittrans as numeric(7,5)
declare @intcomprofitaccid as int
declare @depsalesval as numeric(18,2)
declare @depcostval as numeric(18,2)
declare @actcostamt as numeric(18,2)
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)
-- ALTER 2 tables one for having all the pos trans of the day of the shop
-- one to have records groupwise
CREATE table #allpos(
pbillid int,
pbilldate datetime,
pbillno varchar(100),
pcashaccid  int,
psalesaccid  int,
psalesamt numeric(18,2),
pcostamt numeric(18,2),
per numeric(28,8),
updatetime  datetime,
departmentid int,
deper numeric(28,8),
exchangerates varchar(250))
CREATE table #nposting(
pdate datetime,
cashaccid int,
salesaccid int,
salesamt numeric(18,2),
costamt numeric(18,2),
actamt numeric(18,2),
actcostamt numeric(18,2),
depsalesamt numeric(18,2),
depCostamt numeric(18,2),
updatetime datetime,
departmentid int,
exrates varchar(250))
/* 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
select @intcomcurid = currencyid from acompanymaster
where companyid = @intcompanyid
select @intdiscountaccountid = discountaccountid,
@numprofittrans = isnull(RevisedCostPricePercent,0)
from ashops where shopid = @intshopid
select @strshop = shopname, @intSubDepartmentID =SubDepartmentID from ashops where shopid = @intshopid
select @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid,
@intpltransaccid = profittransfercontrolacc, @intcomdeptid  = companydepartment,
@intcomprofitaccid = compprofitshareacc from
apackagesettings where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
set @numTotalposValue = 0.0
set @numtotaldiscountvalue =0.0
set @numTotalcostValue = 0.0
-- inserting all the day rec to the temp1 table
insert into #allpos
SELECT poshbillid, poshbilldate, poshbillno, poshcashaccid,
poshSalesAccId, isnull(sum(posdUnitPrice),0),
isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0),
poshExchangeRate, max(updatetime), poshDepartmentid, poshdepexrate, poshexchangerates
FROM losposheader ph, losposdetail pd
WHERE ph.poshshopid = pd.posdshopid
and ph.poshbillid = pd.posdbillid
and ph.poshcancellED = 0
and ph.poshpostED = 0
and ph.poshCompanyID = @intCompanyID
and ph.poshshopid = @intshopid
group by poshbillid, poshbilldate, poshbillno,
poshDepartmentid, poshcashaccid,
poshsalesaccid, poshexchangerate, poshdepexrate, poshexchangerates
--insert the grouped values into the temp2 table
insert into #nposting
select pbilldate, pcashaccid, psalesaccid, sum(psalesamt * per), sum(pcostamt * per),
sum(psalesamt), sum(pcostamt), sum(psalesamt * deper),
sum(pcostamt * deper), max(updatetime),
departmentid, max(Exchangerates)
from #allpos
group by pbilldate, pcashaccid, psalesaccid, departmentid,
exchangerates
Declare poscur cursor for
select  pdate, cashaccid, salesaccid, salesamt, costamt,actamt, actcostamt, updatetime,
accountcode, departmentid, depsalesamt, depcostamt, exrates
from #nposting, aaccountmaster where cashaccid = accountid
open poscur
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
while @@Fetch_status = 0
begin
--TO GET TRANSACTION EXCHANGE RATE --------------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
--TO GET TRANSACTION EXCHANGE RATE <---------------
set @strfirsttransno= ''''
set @strlasttransno=''''
--hari added to form the reference number 020204
select  @strfirsttransno= poshbillno from losposheader where poshbillid in
(select min(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
select @strlasttransno = poshbillno from losposheader where poshbillid in
(select max(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtposdate between sdate and edate
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dtposDate,
LEFT(@strfirsttransno + ''_'' + @strlasttransno + '' - '' + @straccountcode,50) ,--RefNo-1
''POS Total Sales'',@intFinancialID,''pos'', @intcomCurID,@dtposdate,  @dtupdatetime)
-- rtrim(@strshop)+ ''_'' + ''POS''+ ''_'' + convert(varchar,getdate(),120)
set @intJournalDetailID = 1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @numactualamt,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
-- change made so that the trade discount should not be treated as discount in accounts
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intSalesAccountID, @numtotaldiscountvalue, @numAaccAmt,@intDepartmentID,
@depsalesval ,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
-- DEBITING BANK
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcashaccountid, @numtotaldiscountvalue , @numactualamt,
@intDepartmentID, @depsalesval,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intINVentoryAccID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
/* crediing the INVENTORY with the full cost Amount */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intINVentoryAccID, @numTotalcostValue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcostofgoodsaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
-- DEBITING THE COST OF GOODS ACCOUNT
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcostofgoodsaccid, @numtotalcostvalue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID)
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
if @numprofittrans <> 0
begin
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcomprofitaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
-- debit company profit account with shop department
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01 ,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
select @intCurrencyid = c.currencyid from aaccountmaster c,
aaccountmaster a where c.currencyid = a.currencyid and
c.companyid = a.companyid and a.accountid = @intpltransaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
set @intJournalDetailID = @intJournalDetailID +1
-- credit transfer control account with shop department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- credit transfer control account with comp department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
end -- for profit trans
set @intJournalID = @intJournalID + 1
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
end
Close poscur
Deallocate poscur
/* mark the record as postED */
update losposheader set poshpostED =1 from #allpos p WHERE poshbillid = pbillid
and  poshCompanyID = @intCompanyID and poshshopid = @intshopid
drop table #allpos
drop table #nposting
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn04042011]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPosBackUpAsOn04042011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spULShopPOS
--------------------------------------------------------------------------
---
-- Created on      : 28/03/2007
-- Created by      : Shinu
-- Comments      : V4
-- added SubDepartment  also
------------------------------------------------------------------------------
--RefNo-1
-- Modified on      :  28-03-2010
-- Modified by      :  Yogesh Joe
-- Comments         :  To avoid the error "String or binary data would be truncated".
--  				   Added LEFT(), while inserting referenceno to journal header
------------------------------------------------------------------------------
CREATE  PROC [dbo].[spULShopPosBackUpAsOn04042011] (@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 @dtposDate as datetime
Declare @strposNo as varchar(50)
Declare @intposid as int
Declare @strRemarks as varchar(250)
Declare @intDiscountAccountID as int
Declare @numDiscount as numeric(18,2)
Declare @intDepartmentID as int
Declare @intSubDepartmentID as int
Declare @numtotalposValue as numeric(18,2)
Declare @numtotaldiscountValue as numeric(18,2)
Declare @numtotalcostValue as numeric(18,2)
Declare @intComCurID as int
Declare @intinventoryaccid as int
Declare @intcostofgoodsaccid as int
declare @numer as numeric(28,8)
declare @numactualamt as numeric(18,2)
declare @dtutime as datetime
declare @strshop as varchar(100)
declare @dtupdatetime as datetime
declare @strfirsttransno as varchar(50)
declare @strlasttransno as varchar(50)
declare @straccountcode as varchar(25)
declare @intpltransaccid as varchar(25)
declare @intcomdeptid as varchar(25)
declare @numprofittrans as numeric(7,5)
declare @intcomprofitaccid as int
declare @depsalesval as numeric(18,2)
declare @depcostval as numeric(18,2)
declare @actcostamt as numeric(18,2)
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)
-- ALTER 2 tables one for having all the pos trans of the day of the shop
-- one to have records groupwise
CREATE table #allpos(
pbillid int,
pbilldate datetime,
pbillno varchar(100),
pcashaccid  int,
psalesaccid  int,
psalesamt numeric(18,2),
pcostamt numeric(18,2),
per numeric(28,8),
updatetime  datetime,
departmentid int,
deper numeric(28,8),
exchangerates varchar(250))
CREATE table #nposting(
pdate datetime,
cashaccid int,
salesaccid int,
salesamt numeric(18,2),
costamt numeric(18,2),
actamt numeric(18,2),
actcostamt numeric(18,2),
depsalesamt numeric(18,2),
depCostamt numeric(18,2),
updatetime datetime,
departmentid int,
exrates varchar(250))
/* 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
select @intcomcurid = currencyid from acompanymaster
where companyid = @intcompanyid
select @intdiscountaccountid = discountaccountid,
@numprofittrans = isnull(RevisedCostPricePercent,0)
from ashops where shopid = @intshopid
select @strshop = shopname, @intSubDepartmentID =SubDepartmentID from ashops where shopid = @intshopid
select @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid,
@intpltransaccid = profittransfercontrolacc, @intcomdeptid  = companydepartment,
@intcomprofitaccid = compprofitshareacc from
apackagesettings where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
set @numTotalposValue = 0.0
set @numtotaldiscountvalue =0.0
set @numTotalcostValue = 0.0
-- inserting all the day rec to the temp1 table
insert into #allpos
SELECT poshbillid, poshbilldate, poshbillno, poshcashaccid,
poshSalesAccId, isnull(sum(posdUnitPrice),0),
isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0),
poshExchangeRate, max(updatetime), poshDepartmentid, poshdepexrate, poshexchangerates
FROM losposheader ph, losposdetail pd
WHERE ph.poshshopid = pd.posdshopid
and ph.poshbillid = pd.posdbillid
and ph.poshcancellED = 0
and ph.poshpostED = 0
and ph.poshCompanyID = @intCompanyID
and ph.poshshopid = @intshopid
group by poshbillid, poshbilldate, poshbillno,
poshDepartmentid, poshcashaccid,
poshsalesaccid, poshexchangerate, poshdepexrate, poshexchangerates
--insert the grouped values into the temp2 table
insert into #nposting
select pbilldate, pcashaccid, psalesaccid, sum(psalesamt * per), sum(pcostamt * per),
sum(psalesamt), sum(pcostamt), sum(psalesamt * deper),
sum(pcostamt * deper), max(updatetime),
departmentid, max(Exchangerates)
from #allpos
group by pbilldate, pcashaccid, psalesaccid, departmentid,
exchangerates
Declare poscur cursor for
select  pdate, cashaccid, salesaccid, salesamt, costamt,actamt, actcostamt, updatetime,
accountcode, departmentid, depsalesamt, depcostamt, exrates
from #nposting, aaccountmaster where cashaccid = accountid
open poscur
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
while @@Fetch_status = 0
begin
--TO GET TRANSACTION EXCHANGE RATE --------------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
--TO GET TRANSACTION EXCHANGE RATE <---------------
set @strfirsttransno= ''''
set @strlasttransno=''''
--hari added to form the reference number 020204
select  @strfirsttransno= poshbillno from losposheader where poshbillid in
(select min(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
select @strlasttransno = poshbillno from losposheader where poshbillid in
(select max(poshbillid) from losposheader where poshbilldate=@dtposdate and
poshshopid=@intshopid) and poshbilldate = @dtposdate and poshshopid =@intshopid
--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtposdate between sdate and edate
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dtposDate,
LEFT(@strfirsttransno + ''_'' + @strlasttransno + '' - '' + @straccountcode,50) ,--RefNo-1
''POS Total Sales'',@intFinancialID,''pos'', @intcomCurID,@dtposdate,  @dtupdatetime)
-- rtrim(@strshop)+ ''_'' + ''POS''+ ''_'' + convert(varchar,getdate(),120)
set @intJournalDetailID = 1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @numactualamt,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
-- change made so that the trade discount should not be treated as discount in accounts
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intSalesAccountID, @numtotaldiscountvalue, @numAaccAmt,@intDepartmentID,
@depsalesval ,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
-- DEBITING BANK
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcashaccountid, @numtotaldiscountvalue , @numactualamt,
@intDepartmentID, @depsalesval,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intINVentoryAccID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
/* crediing the INVENTORY with the full cost Amount */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intINVentoryAccID, @numTotalcostValue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcostofgoodsaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
-- DEBITING THE COST OF GOODS ACCOUNT
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcostofgoodsaccid, @numtotalcostvalue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID)
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
if @numprofittrans <> 0
begin
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intcomprofitaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
-- debit company profit account with shop department
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01 ,@intSubDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcomprofitaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intCashAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
select @intCurrencyid = c.currencyid from aaccountmaster c,
aaccountmaster a where c.currencyid = a.currencyid and
c.companyid = a.companyid and a.accountid = @intpltransaccid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where
departmentid = @intcomdeptid
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
set @intJournalDetailID = @intJournalDetailID +1
-- credit transfer control account with shop department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
@depCostVal * @numprofittrans * 0.01,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- credit transfer control account with comp department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
end -- for profit trans
set @intJournalID = @intJournalID + 1
fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid, @numtotaldiscountvalue,
@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
@depsalesval, @depcostval, @strexrates
end
Close poscur
Deallocate poscur
/* mark the record as postED */
update losposheader set poshpostED =1 from #allpos p WHERE poshbillid = pbillid
and  poshCompanyID = @intCompanyID and poshshopid = @intshopid
drop table #allpos
drop table #nposting
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopPos]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopPos]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------
-- Created on      : 28/03/2007
-- Created by      : Shinu
-- Comments      : V4
-- added SubDepartment  also
------------------------------------------------------------------------------
--RefNo-1
-- Modified on      :  28-03-2010
-- Modified by      :  Yogesh Joe
-- Comments         :  To avoid the error "String or binary data would be truncated".
--         Added LEFT(), while inserting referenceno to journal header
------------------------------------------------------------------------------
/*        [spULShopPos]1,1
RefNo-2
Modified on      : 04-04-2011
Modified by    : Bijesh.B
BackUp           : spULShopPosBackUpAsOn04042011
Comments        : PD Cheque - POS Bill payment may be Full Cash,Full PD Cheque
or Partial Payment (ie,both Cash and PD Cheque)
*/
------------------------------------------------------------------------------
/*
RefNo-3
Modified on      : 19-04-2011
Modified by    : Bijesh.B
Comments        : Bug sheet (Sonee)
If we post a POS transaction in a particular date(say 4.08.2008),but
the cheque amount given in the posdated cheque account in cash sale interface
is not shown in the ledger report while we take the report on 04.08.2011,
this should be shown only in the entry date of check.we can not perform the
posting of POS if full amount is given as cheque amount,in this situation
we can not see the cheque amount in ledger report in the particular date
*/
------------------------------------------------------------------------------
--RefNo-4
-- Modified on      : 30-11-2010
-- Modified by      : Nidheesh P V
-- Comments         : Added the part of GST
------------------------------------------------------------------------------
--<<Ref-05>>
--Modified ON :- 09/11/2011
--Modified By :- MANUNADH.U
--Comment     :- While CREDITING TO TAX ACCOUNT check whether tax amount > 0. Otherwise posting will be wrong.
--     Hence Same POS transactions are  duplicated in GST out put account.
---------------------------------------------------------------------------------------------------
--Ref-06
--Modified ON :- 10/11/2011
--Modified By :- Benzigar S D
--Comment     :- increased the variable length of @strRemarks from 250 to 500
---------------------------------------------------------------------------------------------------
--<<Ref-07>>
--Modified ON :- 25/11/2011
--Modified By :- MANUNADH.U
--Comment     :- Correct the GST OUTPUT TAX posting.
---------------------------------------------------------------------------------------------------
--Ref-08
--Modified ON :- 19/12/2011, 29/12/2011
--Modified By :- BIJESH.B
--Comment     :- Corrected Ledger post in case of PD cheque (Ledger amount +GST not tallying
--               with Sales Report
--Client      :  Sonee
--Desc        :  Added '' PDCheque bit '' column
---------------------------------------------------------------------------------------------------
--Ref-09
--Modified ON :- 02/01/2012
--Modified By :- Bijesh.B
--Ticket ID   :  CLS-110435 (Sonee)
--Comment     :- Cost of Goods sold figure is greater that cash a/c
---------------------------------------------------------------------------------------------------
--Ref-10
--Modified ON :- 06/01/2012
--Modified By :- Bijesh.B
--Desc : Cost of Goods sold value is wrong
---------------------------------------------------------------------------------------------------
--Ref-11
--Modified ON :- 08/01/2012
--Modified By :- Bijesh.B
--Desc : Cost of Goods sold value is wrong
---------------------------------------------------------------------------------------------------
--Ref-12
--Modified ON :- 09/01/2012
--Modified By :- Bijesh.B
--Desc : Cost of Goods sold value is wrong
-- spULShopPos 1,11
---------------------------------------------------------------------------------------------------
CREATE  PROC [dbo].[spULShopPos](@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 @dtposDate as datetime
Declare @strposNo as varchar(50)
Declare @intposid as int
Declare @strRemarks as varchar(500)  --Ref-06
Declare @intDiscountAccountID as int
Declare @numDiscount as numeric(18,9)
Declare @intDepartmentID as int
Declare @intSubDepartmentID as int
Declare @numtotalposValue as numeric(18,9)
Declare @numtotaldiscountValue as numeric(18,9)
Declare @numtotalcostValue as numeric(18,9)
Declare @intComCurID as int
Declare @intinventoryaccid as int
Declare @intcostofgoodsaccid as int
declare @numer as numeric(28,9)
declare @numactualamt as numeric(18,9)
declare @dtutime as datetime
declare @strshop as varchar(100)
declare @dtupdatetime as datetime
declare @strfirsttransno as varchar(50)
declare @strlasttransno as varchar(50)
declare @straccountcode as varchar(25)
declare @intpltransaccid as varchar(25)
declare @intcomdeptid as varchar(25)
declare @numprofittrans as numeric(18,9)
declare @intcomprofitaccid as int
declare @depsalesval as numeric(18,9)
declare @depcostval as numeric(18,9)
declare @actcostamt as numeric(18,9)
declare @numTransEr as numeric(18,9),@numAccEr as numeric(18,9),@numAaccAmt as numeric(18,9),
	@intCurrencyid as int,@strexrates as varchar(250),@numdepamt as numeric(18,9)
--RefNo-4-added for gst--
declare @IntCount as int
declare @TaxCurrId as int
declare @numTaxEr as numeric(18,9)
declare @TaxAcntId as int
declare @TaxCatId as int
declare @TaxAmount as numeric(18,9)
declare @CTaxAmount as numeric(18,9)
declare @DTaxAmount as numeric(18,9)
declare @TaxAccAmount as numeric(18,9)
--
declare @CTotalTaxAmount as numeric(18,9)
declare @DTotalTaxAmount as numeric(18,9)
declare @TotalTaxAmnt as numeric(18,9)
declare @TotalAccTax as numeric(18,9)
declare @PostDtCheque as bit --Ref-08
--RefNo-4---
-- ALTER 2 tables one for having all the pos trans of the day of the shop
-- one to have records groupwise
CREATE table #allpos(
	pbillid int,
	pbilldate datetime,
	pbillno varchar(100),
	pcashaccid  int,
	psalesaccid  int,
	psalesamt numeric(18,9),
	pcostamt numeric(18,9),
	per numeric(28,9),
	updatetime  datetime,
	departmentid int,
	deper numeric(28,9),
	exchangerates varchar(250),
	PDCheque bit,--Ref-08
	FullCash bit --Ref-09
	)
CREATE table #nposting(
	pdate datetime,
	cashaccid int,
	salesaccid int,
	salesamt numeric(18,9),
	costamt numeric(18,9),
	actamt numeric(18,9),
	actcostamt numeric(18,9),
	depsalesamt numeric(18,9),
	depCostamt numeric(18,9),
	updatetime datetime,
	departmentid int,
	exrates varchar(250),
	PDCheque bit --Ref-08
	)
--Ref-11 start
CREATE table #CostPriceTotal(
	BillDate datetime,
	DeptId int,
	AccountId int,
	ActualCostAmount numeric(18,9),
	CompCostAmount numeric(18,9),
	DepCostAmount numeric(18,9)
	)	
--Ref-11 ends
	
--RefNo-4-added for gst--
declare  @Taxtable table(
	billdate datetime,		--<<Ref-07>>
	poshCashAccID INT,		--<<Ref-07>>
	taxCateId int,
	taxAccntId int,
	taxAmount numeric(18,9),
	CtaxAmount numeric(18,9),
	DtaxAmount numeric(18,9))
--RefNo-4-added for gst--
set nocount on
/* 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
select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid
select @intdiscountaccountid = discountaccountid,@numprofittrans = isnull(RevisedCostPricePercent,0)
from ashops where shopid = @intshopid
select @strshop = shopname, @intSubDepartmentID =SubDepartmentID from ashops where shopid = @intshopid
select @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid,
	@intpltransaccid = profittransfercontrolacc, @intcomdeptid  = companydepartment,
	@intcomprofitaccid = compprofitshareacc
from apackagesettings
where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
set @numTotalposValue = 0.0
set @numtotaldiscountvalue =0.0
set @numTotalcostValue = 0.0
-- inserting all the day rec to the temp1 table
-- Full CASH ie, full bill amount
insert into #allpos
	SELECT poshbillid,poshbilldate,poshbillno,poshcashaccid,poshSalesAccId,isnull(sum(posdUnitPrice),0),
	  --isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0), --Ref-09 commented
	  0, --Ref-09 added
	  poshExchangeRate,
	  max(updatetime), poshDepartmentid, poshdepexrate, poshexchangerates,0,1
FROM losposheader ph, losposdetail pd
WHERE ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid and ph.poshcancellED = 0
	  and ph.poshpostED = 0 and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
and isnull(PosPostDate,0)=0 --RefNo-2
group by poshbillid, poshbilldate, poshbillno,poshDepartmentid, poshcashaccid,poshsalesaccid,
poshexchangerate, poshdepexrate, poshexchangerates
--RefNo-2 Start --------------------------------------------
--CASH + PD CHEQUE -> Taking only cash amount ie, Total Bill Amount - PD Cheque Amount
UNION ALL
SELECT ph.poshbillid, poshbilldate, poshbillno, poshcashaccid,poshSalesAccId,
--isnull(sum(posdUnitPrice),0),--(ph.poshBillAmount-pdChq.Amount),
	  (ph.poshBillAmount-pdCheque.PosBankAmount),
	  --isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0),--Ref-09 commented
	  0, --Ref-09  added
	  poshExchangeRate,
	  max(ph.updatetime), poshDepartmentid, poshdepexrate, poshexchangerates,0,0
	FROM losposheader ph, losposdetail pd,losPosChequeDetails pdCheque
	  --ahqPostDatedChequeDetails pdChq --,ahqPDChequeprocessing pdChqPro
	WHERE ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid and ph.poshcancellED = 0
and ph.poshpostED = 0 and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
	  and isnull(PH.PosPostDate,0)=1 and pdCheque.PoshBillID =ph.poshbillid
and pdCheque.PoshShopID = ph.poshShopID
AND (ph.poshBillAmount-pdCheque.PosBankAmount)>0  --Ref-10 added
	  --and pdChq.PoshBillID = ph.poshbillid --and isnull(pdChq.Cancel,0)=0
	  --and pdChq.CompanyID = @intCompanyID  --and pdChq.ShopID = @intshopid
	  --and pdchq.TransID = pdChqPro.PDTransId --and isnull(pdChqPro.PDChequePosted,0) =0
group by ph.poshbillid,poshbilldate,poshbillno,poshDepartmentid,poshcashaccid,poshsalesaccid,
poshexchangerate, poshdepexrate, poshexchangerates,ph.poshBillAmount,pdCheque.PosBankAmount
	  --pdChq.Amount --having (ph.poshBillAmount-pdChq.Amount)>0
--RefNo-2 End --------------------------------------------
	--RefNo-3 Start --------------------------------------------
	--CASH + PD CHEQUE -> Taking only Cheque amount
	UNION ALL
	
	SELECT ph.poshbillid, poshbilldate, poshbillno, ph.poshChequeAccID,poshSalesAccId,
	  --ph.poshBillAmount-(ph.poshBillAmount-pdChq.Amount),
	  pdCheque.PosBankAmount,
	  --isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0), --Ref-09 commented
	  0, --Ref-09 added
	  poshExchangeRate, max(ph.updatetime), poshDepartmentid, poshdepexrate, poshexchangerates,1,0
	FROM losposheader ph,losposdetail pd,losPosChequeDetails pdCheque
	  --ahqPostDatedChequeDetails pdChq --,ahqPDChequeprocessing pdChqPro
	WHERE ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid and ph.poshcancellED = 0
	  and ph.poshpostED = 0 and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
	  and isnull(PH.PosPostDate,0)=1 and pdCheque.PoshBillID =ph.poshbillid
	  and pdCheque.PoshShopID = ph.poshShopID
	  --and pdChq.PoshBillID = ph.poshbillid  --No need to check whether PdChq is Registered/Not
	  --and isnull(pdChq.Cancel,0)=0 --and pdChq.CompanyID = @intCompanyID
	  --and pdChq.ShopID = @intshopid --and pdchq.TransID = pdChqPro.PDTransId
	  --and isnull(pdChqPro.PDChequePosted,0) =0
	group by ph.poshbillid, poshbilldate, poshbillno,poshDepartmentid, ph.poshChequeAccID,
	  poshsalesaccid, poshexchangerate, poshdepexrate, poshexchangerates,ph.poshBillAmount,
	  pdCheque.PosBankAmount
	  --,pdChq.Amount --having  ph.poshBillAmount-(ph.poshBillAmount-pdChq.Amount)>0
	--RefNo-3 End --------------------------------------------
--Ref-11 start commented and added
	----Ref-09 start (Updating the cost amount)
	----Ref-10 ''poshcashaccid'' grouping added in below query
	--	Update #allpos set pcostamt = posdCostPrice
	--	from(SELECT poshbilldate,
	--		isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0)posdCostPrice,
	--		poshDepartmentid,poshcashaccid
	--		FROM losposheader ph, losposdetail pd
	--		WHERE ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid and ph.poshcancellED = 0
	--		and ph.poshpostED = 0 and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
	--		GROUP BY
	--		poshbilldate, poshDepartmentid,poshcashaccid
	--	) vwCostPrice
	--	WHERE
	--	  #allpos.pbilldate = vwCostPrice.poshbilldate and  #allpos.departmentid = vwCostPrice.poshDepartmentid
	--	  and #allpos.FullCash=1 and #allpos.pcashaccid=vwCostPrice.poshCashAccID
	----Ref-09 ends
	
	insert into #CostPriceTotal
	select poshBillDate,poshDepartmentid,poshcashaccid,
		isnull(sum((posdQuantity + posdFreeQuantity) * posdCostPrice), 0)ActCostPrice,
		isnull((sum((posdQuantity + posdFreeQuantity) * posdCostPrice)* poshExchangeRate), 0)CompCostPrice,
		isnull((sum((posdQuantity + posdFreeQuantity) * posdCostPrice)* poshdepexrate), 0)DepCostPrice
	from losposheader ph, losposdetail pd
		where ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid and ph.poshcancellED = 0
		and ph.poshpostED = 0 and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
		group by
		poshbilldate, poshDepartmentid,poshcashaccid,poshExchangeRate,poshdepexrate
--Ref-11 ends
--RefNo-4---to insert tax cateid,tax A/C & tax amount in the table variable---
	insert into @Taxtable
	  select poshbilldate,poshCashAccID,posdItemTaxCategory,TaxAccountId,
		isnull(sum(posdItemTaxAmount),0)as TaxAmount,
		sum(isnull(posdItemTaxAmount,0)* poshExchangeRate) as ComTaxAmount,
		sum(isnull(posdItemTaxAmount,0)* poshdepexrate) as DepTaxAmount
	  FROM losposheader ph
		inner join losposdetail pd on ph.poshshopid = pd.posdshopid and ph.poshbillid = pd.posdbillid
		inner join ataxcategorymaster tc on TaxCompanyId=ph.poshCompanyID AND posdItemTaxCategory=TaxId
		  and TaxCancelled=0 --and TaxAccountable=1
	  WHERE ph.poshcancellED = 0 and ph.poshpostED = 0 and isnull(posdItemTaxCategory,0)<>0
		and ph.poshCompanyID = @intCompanyID and ph.poshshopid = @intshopid
	  GROUP BY poshbilldate,poshCashAccID,posdItemTaxCategory,TaxAccountId     --<<Ref-07>>
	---RefNo-4----
--insert the grouped values into the temp2 table
	insert into #nposting
	  select pbilldate,pcashaccid,psalesaccid,sum(psalesamt * per),sum(pcostamt * per),sum(psalesamt),
		sum(pcostamt),sum(psalesamt * deper),sum(pcostamt * deper), max(updatetime),
		departmentid, max(Exchangerates),0
	  from #allpos
	  where PDCheque=0  --Ref-08
	  group by pbilldate, pcashaccid, psalesaccid, departmentid,exchangerates
	
----Ref-08 start
	insert into #nposting
	  select pbilldate,pcashaccid,psalesaccid,sum(psalesamt * per),sum(pcostamt * per),sum(psalesamt),
		sum(pcostamt),sum(psalesamt * deper),sum(pcostamt * deper), max(updatetime),
		departmentid, max(Exchangerates),1
	  from #allpos
	  where PDCheque=1
	  group by pbilldate, pcashaccid, psalesaccid, departmentid,exchangerates
--Ref-08 ends
--Ref-12 start
	Update #nposting set  costamt = CompCostAmount,actcostamt=ActualCostAmount,
			depCostamt=DepCostAmount
	from(SELECT BillDate,DeptId,AccountId,CompCostAmount,ActualCostAmount,DepCostAmount
		 from #CostPriceTotal GROUP BY BillDate,DeptId,AccountId,
		 CompCostAmount,ActualCostAmount,DepCostAmount)vwCostPrice
	where  #nposting.cashaccid = vwCostPrice.AccountId AND
	#nposting.departmentid= vwCostPrice.DeptId AND #nposting.pdate=vwCostPrice.BillDate
--Ref-12 ends
	Declare poscur cursor for
	select  pdate, cashaccid, salesaccid, salesamt, costamt,actamt, actcostamt, updatetime,
	  accountcode, departmentid, depsalesamt, depcostamt, exrates
	   ,pdcheque --Ref-08
	from #nposting, aaccountmaster where cashaccid = accountid
	open poscur
	  fetch next FROM poscur into @dtposdate,@intCashAccountID,@intsalesaccountid,@numtotaldiscountvalue,
	  @numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime, @straccountcode, @intdepartmentid,
	  @depsalesval, @depcostval, @strexrates, @PostDtCheque
	  while @@Fetch_status = 0
	  begin
		--TO GET TRANSACTION EXCHANGE RATE --------------->
		select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intCashAccountID
		exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
		--TO GET TRANSACTION EXCHANGE RATE <---------------
set @strfirsttransno= ''''
		set @strlasttransno=''''
		--hari added to form the reference number 020204
select @strfirsttransno = poshbillno from losposheader where poshbillid in
		(
		  select min(poshbillid) from losposheader
		  where poshbilldate=@dtposdate and poshshopid=@intshopid and poshCancelled=0 and poshPosted=0
		) and poshbilldate = @dtposdate and poshshopid =@intshopid  and poshCancelled=0 and poshPosted=0
		select @strlasttransno = poshbillno from losposheader where poshbillid in
		(
		  select max(poshbillid) from losposheader
		  where poshbilldate=@dtposdate and poshshopid=@intshopid and poshCancelled=0 and poshPosted=0
		) and poshbilldate = @dtposdate and poshshopid =@intshopid  and poshCancelled=0 and poshPosted=0
		--to take financialid from afinancialyear table with curfinancialyear=1 --Z hari011211
		select @intFinancialID = financialid from vwfinyearperiod
		where @dtposdate between sdate and edate
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno,remarks,financialID,
		  Type,CurrencyID,chequedate,updatetime)
		values (@intJournalID, @intCompanyID, @dtposDate,
		  LEFT(@strfirsttransno + ''_'' + @strlasttransno + '' - '' + @straccountcode,50) ,--RefNo-1
		  ''POS Total Sales'',@intFinancialID,''pos'', @intcomCurID,@dtposdate,@dtupdatetime)
		-- rtrim(@strshop)+ ''_'' + ''POS''+ ''_'' + convert(varchar,getdate(),120)
		set @intJournalDetailID = 1
		--RefNo-4--------------------------------------
		select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),
		  @DTotalTaxAmount=sum(isnull(DtaxAmount,0))
		from @Taxtable where billdate=@dtposDate AND poshCashAccID=@intCashAccountID
		GROUP BY billdate,poshCashAccID--,taxCateId--<<Ref-07>>
	    if @TotalTaxAmnt is null
	    begin
		  set @TotalTaxAmnt=0.00
		  set @CTotalTaxAmount=0.00
		  set @DTotalTaxAmount=0.00
		end
		---@TotalTaxAmnt-->in CASH A/C currency
		---TO CONVERT INTO SALE A/C CURRENCY---
		select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		exec spconvertcurrency @numTransEr , @numAccEr , @TotalTaxAmnt,@TotalAccTax output
		--TO CONVERT INTO SALE A/C CURRENCY---
--RefNo-4----------------------------------------
select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		exec spconvertcurrency @numTransEr , @numAccEr , @numactualamt,@numAaccAmt output
		/* crediing the sales account with the full invoice Amount */
		-- change made so that the trade discount should not be treated as discount in accounts
	if @PostDtCheque=1 --Ref-08 if part and else part added
	begin
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
		  Amount,actualAmount,departmentID, depamount,SubDepartmentID)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intSalesAccountID,
		  (@numtotaldiscountvalue-0), (@numAaccAmt-0),@intDepartmentID,
		  (@depsalesval-0) ,@intSubDepartmentID)
		
		
end
	else
	begin
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
		  Amount,actualAmount,departmentID, depamount,SubDepartmentID)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intSalesAccountID,
		  (@numtotaldiscountvalue-@CTotalTaxAmount), (@numAaccAmt-@TotalAccTax),@intDepartmentID,
		  (@depsalesval-@DTotalTaxAmount) ,@intSubDepartmentID)
		
		end
		set @intJournalDetailID = @intJournalDetailID +1
-- DEBITING BANK
		insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,JournalCrEDit, AccountID,
		  Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intcashaccountid,
		  @numtotaldiscountvalue , @numactualamt,@intDepartmentID, @depsalesval,@intSubDepartmentID)
		set @intJournalDetailID = @intJournalDetailID +1
		select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intINVentoryAccID
		exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numAaccAmt output
/* crediing the INVENTORY with the full cost Amount */
	if @numtotalcostvalue >0  --Ref-09 only if condition added
	begin
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
		  Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intINVentoryAccID,
		  @numTotalcostValue, @numAaccAmt,@intDepartmentID, @depCostVal,@intSubDepartmentID )
end
		set @intJournalDetailID = @intJournalDetailID +1
		select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intcostofgoodsaccid
		exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numAaccAmt output
		-- DEBITING THE COST OF GOODS ACCOUNT
	if @numtotalcostvalue >0  --Ref-09 only if condition added
	begin
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit,AccountID,
		  Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intcostofgoodsaccid,
		  @numtotalcostvalue, @numAaccAmt,@intDepartmentID, @depCostVal,@intSubDepartmentID)
end
		--RefNo-4-----------------------------------
		select @IntCount=count(*) from @Taxtable
		while (@IntCount>0)
		begin
		  --select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
		  --from @Taxtable order by taxCateId
		  set @TaxAmount=0--<<Ref-07>>
		  select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,
		    @TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
		  from @Taxtable
		  where billdate=@dtposDate AND poshCashAccID=@intCashAccountID----<<Ref-07>>
		  order by taxCateId--<<Ref-07>>
		  --TO GET TAX EXCHANGE RATE --------------->
		  select @TaxCurrId = currencyid from aaccountmaster a where accountid = @TaxAcntId
		  exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
		  --TO GET TAX EXCHANGE RATE <---------------
		  ---------------------------------------
		  exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,@TaxAccAmount output
		  ------------------------------------------
		  if @TaxAmount > 0--<<Ref-05>>
		  begin
			set @intjournalDetailID=@intjournalDetailID+1
			-- CREDITING TO TAX ACCOUNT
			insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,JournalCrEDit,AccountID,
			  Amount, actualAmount,departmentID, depamount,SubDepartmentID)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@TaxAcntId, @CTaxAmount ,
			  @TaxAccAmount,@intDepartmentID, @DTaxAmount,@intSubDepartmentID)
		  end
		  --delete from @Taxtable where @TaxCatId=taxCateId  --<<Ref-07>>
		  delete from @Taxtable where billdate=@dtposDate AND poshCashAccID=@intCashAccountID AND
			taxCateId=@TaxCatId--<<Ref-07>>
		  set @IntCount=@IntCount-1
		end
		--RefNo-4-------------------------------------------
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
		if @numprofittrans <> 0
		begin
		  -- FOR CONVERTING TO ACCOUNT AMOUNT---------->
		  select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intcomprofitaccid
		  exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		  exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster where departmentid = @intcomdeptid
		  exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numDepAmt output
		  -- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
-- debit company profit account with shop department
		  set @intJournalDetailID = @intJournalDetailID +1
		  insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit,AccountID,
			Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intcomprofitaccid ,
		    @numtotalcostvalue * @numprofittrans * 0.01,@numAaccAmt * @numprofittrans * 0.01,
		    @intDepartmentID,@depCostVal * @numprofittrans * 0.01 ,@intSubDepartmentID )
		  set @intJournalDetailID = @intJournalDetailID +1
		  insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit,AccountID,
		    Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intcomprofitaccid,
		    @numtotalcostvalue * @numprofittrans * 0.01,@numAaccAmt * @numprofittrans * 0.01,
		    @intcomdeptid,@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
		  -- FOR CONVERTING TO ACCOUNT AMOUNT---------->
		  select @intCurrencyid = currencyid from aaccountmaster a where accountid = @intCashAccountID
		  exec spReturnExrate @intcurrencyid, @strexrates, @numTransEr output
select @intCurrencyid = c.currencyid from aaccountmaster c,aaccountmaster a
where c.currencyid = a.currencyid and c.companyid = a.companyid and
			a.accountid = @intpltransaccid
		  exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		  exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numAaccAmt output
select @intCurrencyid = depcurrencyid from adepartmentmaster
where departmentid = @intcomdeptid
		  exec spReturnExrate @intcurrencyid, @strexrates, @numAccEr output
		  exec spconvertcurrency @numTransEr , @numAccEr , @actcostamt,@numDepAmt output
		  -- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
set @intJournalDetailID = @intJournalDetailID +1
		  -- credit transfer control account with shop department
		  insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit,AccountID,
			Amount, actualAmount,departmentID,depamount,SubDepartmentID)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
			@numAaccAmt * @numprofittrans * 0.01, @intDepartmentID,
			@depCostVal * @numprofittrans * 0.01,@intSubDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- credit transfer control account with comp department
		  insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intpltransaccid , @numtotalcostvalue * @numprofittrans * 0.01,
			@numAaccAmt * @numprofittrans * 0.01, @intcomdeptid,
			@numDepAmt * @numprofittrans * 0.01 ,@intSubDepartmentID)
end -- for profit trans
		set @intJournalID = @intJournalID + 1
	  fetch next FROM poscur into @dtposdate, @intCashAccountID, @intsalesaccountid,
	    @numtotaldiscountvalue,@numTotalcostValue, @numactualamt, @actcostamt, @dtupdatetime,
	    @straccountcode, @intdepartmentid,@depsalesval, @depcostval, @strexrates
	    ,@PostDtCheque --Ref-08
	end
Close poscur
Deallocate poscur
/* mark the record as postED */
update losposheader set poshpostED =1 from #allpos p
WHERE poshbillid = pbillid and  poshCompanyID = @intCompanyID and poshshopid = @intshopid
drop table #allpos
drop table #nposting
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULBookInvoice_BEFOREGST]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULBookInvoice_BEFOREGST]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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.
CREATE PROCEDURE [dbo].[spULBookInvoice_BEFOREGST] @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
/* 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 @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
--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
set @numadvance = isnull(@numservcost,0) + isnull(@numpartscost,0) - isnull(@numinvamount,0)
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               end
if @numservcost >0
begin
if @intCashAccountID is not null
exec spConvertEquiamount @intCashAccountID, ''a'', @intserviceaccid, ''a'',
@strExRates, @numservcost, @numRespAmount output, ''a''
else
Begin
if @intcustomerid is not null and @intcustomerid >0
exec spConvertEquiamount @intcustomerid, ''c'', @intserviceaccid, ''a'',
@strExRates, @numservcost, @numRespAmount output, ''a''
else
exec spConvertEquiamount @intOtherDepId, ''d'', @intserviceaccid, ''a'',
@strExRates, @numservcost, @numRespAmount output, ''a''
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
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, @numtotalcostvalue,
@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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULBookInvoice]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULBookInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULHQSWO]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHQSWO]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- Last Modified : 12/12/2001, 29/12/2003
-- Modified by   : hariharan, Hariharan
--COmments  : Incorporated in V3 to include the provision for
--   : Recovering items or to write off the excess or shortage in imports
----------------------------------------
-- RefN0-1
-- Modified by   : Nidheesh P V
--COmments  : Actually the HQ Write-Off should be posted to
--1)Write off A/C  &   2)Inventory A/C()instead of stock Transfer Controll A/C
--so posted to Inventory A/C instead of Stock transfer
--Ticket No:MZA-925451
------------------------------------
CREATE proc [dbo].[spULHQSWO] @intCompanyID as int, @intTransId as int as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intswoiD as int,
@intFinancialID as int,
@strswoNo as varchar(100),
@dtswoDate as datetime,
@strRemarks as varchar(500),
@intDepartmentID as int,
@numswoAmt as numeric(18,2),
@intCompanyCurID as int,
@intExcessShortageDiffaccId as int,
@intswoaccid as int,
@intgodownid as int,
@intshopid as int,
@dtutime as datetime,
@intFailcount as int,
@strzerorate as varchar(1),
@numStockAddclear as numeric(18,3),
@numStockDedclear as numeric(18,3) ,
@stockTransferAcc int,
@IntTransferType as char(1),
@numDepExRate as numeric(18,8),
@numConExRate as numeric(18,8),
@strExRates as varchar(250),
@intCurrencyId as int,
@intInventoryAccId as int,
@numAccExRate as numeric(18,8),
@numSrAmt as numeric(18,8),
@numAaccAmt as numeric(18,8),
@numTransEr as numeric(18,8)
--get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster WHERE CompanyID = @intCompanyID
select @intExcessShortageDiffaccId = HQPurchaseAccId,
@strzerorate = substring(isnull(futurevc,''''),1,1),
@stockTransferAcc = stocktransfercontrolacc,
@intInventoryAccId = InventoryID from apackagesettings
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare swocur cursor for
SELECT swID, swTransCode + '' ''+ rtrim(convert(varchar(50),swID)),
swdate, ''system'', isnull(swShopID,0) s, isnull(swGodownID,0) g, updatetime,
swWriteOffType, swdepExRate, swdConExRate, swExchangeRates
FROM moStockWriteOffHQ WHERE swposted =0 and swID = @intTransId
open swocur
fetch next FROM  swocur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
@intshopid, @intgodownid, @dtutime, @IntTransferType, @numDepExRate, @numConExRate,
@strExRates
while @@Fetch_status = 0
begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster a
where a.AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
--to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
--and the item master table. If so we cannot do any thing in the posting with out item rate.
--so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
if @intshopid<>0 and @intshopid is not null
begin
select @intFailcount = count(*) from moStockWriteOffHQ, aitem where
swID = @intswoiD and swShopID = @intshopid and swItemID = itemid
and (swCostPrice=null or swCostPrice=0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
set @intfailcount=0
end
if @intgodownid <> 0 and @intgodownid is not null
begin
select @intFailcount = count(*) from moStockWriteOffHQ, aitem where
swID = @intswoiD and swgodownid = @intgodownid and swItemID = itemid
and (swCostPrice=null or swCostPrice=0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
set @intfailcount=0
end
set @intfailcount = 0 -- to allow posting even the itemrate is 0
if @intfailcount = 0 -- for item rate=0 check
begin
if @intgodownid <> 0
begin
-- to update the item rate to the gadcostprice
update moStockWriteOffHQ set swCostPrice = itemrate from
aitem where ( swCostPrice =null or swCostPrice =0) and swID = @intswoiD
and swgodownid = @intgodownid and switemid = itemid
end
else
begin
-- to update the item rate to the gadcostprice
update moStockWriteOffHQ set swCostPrice = itemrate from
aitem where ( swCostPrice =null or swCostPrice =0) and swID = @intswoiD
and swshopid = @intshopid and switemid = itemid
end
if (@intgodownid > 0)
select @intDepartmentID = departmentid, @intswoaccid = stockwriteoffaccid
from agodown where godownid = @intgodownid
else
select @intDepartmentID = departmentid, @intswoaccid = stockwriteoffaccid
from ashops where shopid = @intshopid
set @numStockAddclear = 0.0
set @numStockDedclear = 0.0
-- getting the total amount with qty and item cost price
select @numswoAmt = isnull(sum((isnull(swAddStock,0) + isnull(swDedStock,0))
* swCostPrice),0), @numStockAddclear = SUM(isnull(swAddStock,0)),
@numStockDedclear = sum(isnull(swDedStock,0)) from moStockWriteOffHQ where swid = @intswoiD
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,
@strRemarks, @intFinancialID, ''hqswo'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
if @numStockAddclear >0
Begin
if @intTransferType = 0
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intswoaccid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt,
@numAaccAmt output
--debiting hte inventory accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intswoaccid,
@numswoamt * @numConExRate, @numAaccAmt, @intdepartmentid,
@numswoamt * @numDepExRate)
End
ELSE
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExcessShortageDiffaccId
and companyId = @IntCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intExcessShortageDiffaccId,
@numswoamt * @numConExRate, @numAaccAmt , @intdepartmentid, @numswoamt * @numDepExRate )
eND
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @stockTransferAcc
and companyId = @IntCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
set @intJournalDetailID = @intJournalDetailID + 1
------------------ RefN0-1-------start-------commented below code and added new--------
-----------credited to Inventory A/C instead of Stock Transfer control A/C in the case of Add.---------
-- Credit transfer account
------    insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
------    JournalCrEDit, accountid, Amount, actualamount,departmentid, depamount) values
------    (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
------    @stockTransferAcc, @numswoamt * @numConExRate, @numAaccAmt,
------    @intdepartmentid, @numswoamt * @numDepExRate)
-- Credit Inventory account
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intInventoryAccId, @numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate)
------------------ RefN0-1-------ends------------------------
End
if @numStockDEDclear >0
Begin
if @intTransferType = 0
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intswoaccid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, Depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intswoaccid,
@numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
eND
eLSE
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExcessShortageDiffaccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intExcessShortageDiffaccId,
@numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
eND
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @stockTransferAcc
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
------------------ RefN0-1-------start-------commented below code and added new--------
-----------Debited to Inventory A/C instead of Stock Transfer control A/C in the case of Dedu.-------------
-- Debit transfer account
----   insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
----   JournalCrEDit, accountid, Amount, actualamount,departmentid, DepAmount) values
----   (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
----   @stockTransferAcc, @numswoamt * @numConExRate, @numAaccAmt,
----   @intdepartmentid, @numswoamt * @numDepExRate )
-- Credit transfer account
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount, actualamount,departmentid, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intInventoryAccId, @numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
------------------ RefN0-1-------ends------------------------
End
update moStockWriteOffHQ set swposted = 1 WHERE
swid = @intswoiD
set @intJournalID = @intJournalID + 1
end -- for item rate=0 check
fetch next FROM  swocur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
@intshopid, @intgodownid, @dtutime, @IntTransferType, @numDepExRate,
@numConExRate, @strExRates
end -- CUR END
Close swocur
Deallocate swocur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULInvRecover]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvRecover]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on      : 07/01/2003
-- Modified by      : Hariharan R
-- Comments         : Added code to insert depAmount and to convert amount
-- Verified By Hariharan on 07/01/2003
----------------------------------------------------------------------------------
-- Modified on      : 10/06/2003
-- Modified by      : Kishore
-- Comments         : recovery transaction sp modified to take the stock transfer account
--                    (on comparison with v2)
----------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spULInvRecover] @intCompanyID as int, @intGodownId as int AS
begin
	Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intsrid as int,
	@intFinancialID as int,
	@strsrNo as varchar(50),
	@dtsrDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentId as int,
	@numSrAmt as numeric(18,2),
	@intCompanyCurID as int,
	@intinventoryaccid as int,
	@intSwoAccId as int,
	@intRecoveryAccId 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),
	@intStockTransaferAccId as int
	--get the companyCurrencyID
	SELECT @intCompanyCurID = CurrencyID
		FROM acompanymaster
		WHERE CompanyID = @intCompanyID
	
	select @intDepartmentId= DepartmentId, @intSwoAccId = stockwriteoffaccid
		from aGodown
		where GodownId = @intGodownId
	select @intinventoryaccid = InventoryID, @intRecoveryAccId = futureint,
		@strzerorate = substring(isnull(futurevc,''''),1,1),
		@intStockTransaferAccId = stocktransfercontrolacc
		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 srcur cursor for
		SELECT srID, rtrim(godownname) + ''_'' + rtrim(convert(varchar(20),srID)),
		srdate, ''system'', updatetime, srConExRate, srDepExRate, srExchangeRates
		FROM loiStockRecovery i, aGodown g
		WHERE GodownId = srGodownId and srGodownId = @intGodownId and srposted = 0
	open srcur
	
	fetch next FROM  srcur into @intsriD, @strsrno, @dtsrDate, @strRemarks,@dtutime,
		@numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0	
	begin	-- cur begin
		select @intCurrencyId = CurrencyId
			from aAccountMaster a
			where a.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 @dtsrDate 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 loistockrecovery, aItem where
			srID =  @intsriD and srGodownId = @intGodownId and sritemid = itemid
			and ( srCostPrice =null or srCostPrice =0) and (itemrate=0 or itemrate is null)
		-- to allow to proceed if allow zero rate condition given - hari 020905
		if @strzerorate = ''z''
		begin
		 	set @intfailcount=0
		end
		if @intfailcount = 0 	-- for item rate =0 check
		begin
			-- to update the item rate to the gadCostPrice 		
			update loistockrecovery set srCostPrice = itemrate from
				aItem where ( srCostPrice =null or srCostPrice =0) and srID =  @intsriD
				and srGodownId = @intGodownId and sritemid = itemid
			--getting the total amount with qty and item cost price
			select @numSrAmt = isnull(sum((sraddStock - srdedstock)* srCostPrice),0)
				from loiStockRecovery
				where srGodownId = @intGodownId and srid = @intsrid
			if (@numSrAmt <> 0)
			begin
	
				insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
					referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
					values (@intJournalID, @intCompanyID, @dtsrDate, @strsrno,
					@strRemarks, @intFinancialID, ''isrec'', @intcompanycurID, @dtsrDate, @dtutime )
				set @intJournalDetailID = 1
				if (@numSrAmt > 0)
				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,
						abs(@numSrAmt) * @numConExRate, abs(@numSrAmt),
						abs(@numSrAmt) * @numDepExRate,
						@intDepartmentId )	
					set @intJournalDetailID = @intJournalDetailID +1
					-- for converting the amount --->
					select @intCurrencyId = CurrencyId
						from aAccountMaster
						where AccountId = @intRecoveryAccId
					exec spReturnExRate @intCurrencyId, @strExRates,
						@numAccExRate output
					exec spConvertCurrency @numTransEr, @numAccExRate,
						@numSrAmt,
						@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,
						@intStockTransaferAccId, abs(@numSrAmt) * @numConExRate,
						@numAaccAmt, abs(@numSrAmt) * @numDepExRate,
						@intDepartmentId)
				end	-- end for more addtion
	
				if (@numSrAmt < 0)
				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,
						abs(@numSrAmt) * @numConExRate, abs(@numSrAmt),
						abs(@numSrAmt) * @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 = abs(@numSrAmt)
					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,
						@intStockTransaferAccId, abs(@numSrAmt) * @numConExRate,
						@numAaccAmt,
						abs(@numSrAmt) * @numDepExRate, @intDepartmentId)
				end	-- end for more addtion
			end	
					
			update loiStockRecovery set srposted = 1 WHERE
				srid = @intsrID and srGodownId = @intGodownId
				set @intJournalID = @intJournalID + 1	
		end -- for item rate =0 check
		
		fetch next FROM  srcur into @intsriD, @strsrno, @dtsrDate, @strRemarks,@dtutime,
			@numConExRate, @numDepExRate, @strExRates
	end	-- CUR END
	Close srcur
	Deallocate srcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULMASAgreement]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASAgreement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------
-- Created on : 21/08/2003
-- Created by   : R Harikrishnan
-- Comment     : For Posting the manaam Agreement depositAmt
-- Created by   : venki 101103
-- Comment     : For Posting the manaam Agreement chking the deposit date is there then only it will post
--------------------------------------
CREATE proc [dbo].[spULMASAgreement]
@intCompanyID as int,
@intshopid as int
as
begin
-- For testing by R Harikrishnan
-- Begin Tran
-- Set @intCompanyID=1
-- Set @intShopID =24
Declare @intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@intCashAccId as int,
@intAdvanceAccId as int,
@intAgmntID as int,
@intDeptID as int,
@intComCurID as int,
@dtAgmntDate as datetime,
@dtUpdTime as datetime,
@strAgmntNo as varchar(50),
@strRemarks as varchar(250),
@strExRates as varChar(250),
@numDepExRate as numeric(18,8),
@numConExRate as numeric(18,8),
@numDepositAmt as numeric(18,2),
@numResAmt as numeric(18,2)
set @numDepExRate = 0.00
set @numConExRate = 0.00
set @numDepositAmt = 0.00
set @intCashAccId = 0
set @intAdvanceAccId = 0
set @intAgmntID = 0
set @intDeptID = 0
set @numResAmt = 0.00
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
select
@intComCurid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
Declare AgmntCur cursor for
SELECT
mghAgreementID, mghAgreementDate, mghAgreementNo, mghRemarks,
mghDepartmentid, mghUpdatetime, mghExchangeRate, mghDepExRate,
mghExchangeRates, mghAdavanceAccID, mghAccountId, mghsecurittyamount
FROM
losApartmentAgreementHeader ah
WHERE
mghCancelled = 0 and mghPosted = 0 and
mghShopid = @intshopid and mghCompanyID=@intCompanyID and
mghadvdate is not null
open AgmntCur
fetch next FROM
AgmntCur
into
@intAgmntID, @dtAgmntDate, @strAgmntNo, @strRemarks, @intDeptID,
@dtUpdTime, @numConExRate, @numDepExRate, @strExRates, @intAdvanceAccId,
@intCashAccId, @numDepositAmt
while @@Fetch_status = 0
begin
if @numDepositAmt<>0
begin
-- to take financialid from afinancialyear table with curfinancialyear=1
-- hari011211
select
@intFinancialID = financialid
from
vwfinyearperiod
where
@dtAgmntDate between sdate and edate
-- to update the item rate to the gadcostprice
insert into moaJournalHeader
(JournalID, CompanyID, JournalDate, referenceno, remarks,
financialID, Type, CurrencyID, chequedate, updatetime)
values
(@intJournalID, @intCompanyID, @dtAgmntDate, @strAgmntNo,
@strRemarks, @intFinancialID, ''sdep'', @intComCurid,
@dtAgmntDate, @dtUpdTime)
set @intJournalDetailID = 1
/* debiting the inventory account with the full */
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, DepAmount, departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intCashAccId, @numDepositAmt * @numConExRate,
@numDepositAmt, @numDepositAmt * @numDepExRate,
@intDeptID)
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
exec spConvertequiamount @intCashAccId, ''a'', @intAdvanceAccId,
''a'', @strExRates, @numDepositAmt, @numResAmt output,''''
/* debiting the A account with the full */
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, DepAmount, departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intAdvanceAccId, @numDepositAmt * @numConExRate,
@numResAmt, @numDepositAmt * @numDepExRate, @intDeptID  )
/* mark the record as postED */
select 1,@intAgmntID
update
losApartmentAgreementHeader
set
mghPosted  = 1
WHERE
mghShopid = @intShopID and mghAgreementID = @intAgmntID and
mghCompanyID= @intCompanyID
set @intJournalID = @intJournalID + 1
end  -- finish of block if the transaction is posted based on the if condition *** hari 011211
fetch next FROM
AgmntCur
into
@intAgmntID, @dtAgmntDate, @strAgmntNo, @strRemarks, @intDeptID,
@dtUpdTime, @numConExRate, @numDepExRate, @strExRates, @intAdvanceAccId,
@intCashAccId,@numDepositAmt
end
Close AgmntCur
Deallocate AgmntCur
-- rollback tran
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionBills]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersInterDivisionBills]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : VinothMurugan V.
--Created Date  : 04/09/2010
--Purpose  : InterDivision Bills for company wise
--Client : Kooddoo
CREATE proc [dbo].[spUpdateLEDgersInterDivisionBills] @intCompanyID as int, @intbillsid as int as
begin
Declare @intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@strBillsNo as varchar(50),
@dtBillsDate as datetime,
@intDiscountAccID as int,
@intVendorID as int,
@strRemarks as varchar(250),
@intDepartmentID as int,
@numDiscount as numeric(18,2),
@numBillAmt as numeric(18,2),
@intDebitAccID as int,
@numDebitAmt as numeric(18,2),
@intCashBankID as int,
@numvendoramt as numeric(18,2),
@dtutime as datetime,
@numdepRate as numeric(18,9),
@numconsRate as numeric(18,9),
@strexrates as varchar(250),
@numaccamt as numeric(18,2),
@IntDetailDeptid as int,
@intcurrencyid as int
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
CompanyID = @intCompanyID
SELECT @intBillsID= BillsID, @strBillsno = Billsno, @dtBillsDate = BillDate,
@intVendorID = vendorID, @intDiscountAccID = discountAccountID, @numDiscount = discount,
@numBillAmt = billAmount, @strRemarks = case when (chequeno is null or chequeno ='''')
then remarks else chequeno + '';    '' + remarks end , @intFinancialID = FinancialID,
@intCashBankID = bankcashaccID, @dtutime = updatetime, @intdepartmentid = departmentid,
@strexrates = exchangerates, @numdepRate = depexrate, @numconsrate = exchangerate
FROM interdivisionbillsheader WHERE postED =0 and CompanyID = @intCompanyID
and cancellED =0 and billsid = @intbillsid
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
SELECT @intcurrencyid = CurrencyID FROM avendormaster
WHERE CompanyID = @intCompanyID and vendorID = @intvendorID
insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsNo,
@strRemarks, @intFinancialID, ''IDB'', @intcurrencyid, @dtBillsDate, @dtutime)
set @numvendoramt =0
Declare DebitBillCur cursor for
SELECT AccountID,departmentid, Amount FROM interdivisionbillsdetails
WHERE CompanyID = @intCompanyID and BillsID = @intBillsID
open debitbillcur
fetch next FROM debitbillcur into @intDebitAccID,@IntDetailDeptid, @numDebitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intvendorid, ''v'', @intdebitaccid, ''a'', @strexrates,
@numdebitamt, @numaccamt output
insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,DepartmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, @numDebitAmt * @numconsrate, @numaccamt,
@IntDetailDeptid, @numDebitAmt * @numdeprate)
set @numvendoramt = @numvendoramt + @numDebitAmt
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM debitbillcur into @intDebitAccID,@IntDetailDeptid, @numDebitAmt
end
close DebitBillCur
deallocate debitbillcur
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intVendorID,
@numvendoramt * @numconsrate, @numvendoramt, @intDepartmentID,
@numvendoramt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
update interdivisionbillsheader set postED =1 WHERE BillsID = @intBillsID and CompanyID = @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownRecovery]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownRecovery]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateGodownRecovery    Script Date: 18/01/2003 9:45:45 PM ******/
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created By 	: Kishore
--Created Date  : 28/12/2002
--Comments	: (V3)
--                Updates the godown stock
--                for the transaction recovery in godown
--Verified by 	: Hariharan R
-------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateGodownRecovery] @RecoveryId int,
				   @GodownId int  as
begin
	declare
	@cur_RecoveryId int,
	@cur_GodownId int,
	@cur_ItemId int,
	--@cur_ItemGoodQty numeric(18, 3),
	@cur_AddQty numeric(18, 3),
	@cur_DedQty numeric(18, 3),
	--@cur_FromTable char(1),
	@cur_cost numeric(18, 2),
	@cur_ShipmentID int,
	@recCount as int,
	@ItemQty as numeric(18, 3)
	set nocount on
	declare cursor_Detail  cursor for
		select srId srId, srGodownId GodownId, srItemId ItemId,
		srAddStock AddQty, srDedStock DedQty,
		ItemRate, b.ShipmentId
		from (loiStockRecovery Rec left outer join aItem
		on Rec.srItemId = aItem.ItemId),
		(select min(gsShipmentId) ShipmentId from moiGodownStock) b
		where srId = @RecoveryId
		and srGodownId = @GodownId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_RecoveryId, @cur_GodownId, @cur_ItemId,
		@cur_AddQty, @cur_DedQty,
		@cur_cost, @cur_ShipmentId
	while @@fetch_status = 0
	begin
		-- if add qty is not zero, add stock
		-- other wise (if ded qty is not zero)
		-- then reduce stock
		if @cur_AddQty > 0
	   	begin
			set @ItemQty = @cur_AddQty
		end
		else
		begin		
			set @ItemQty = -1 * @cur_DedQty
		end
		-- check if the record exists in the stock table
		select @recCount = count(*) from moiGodownStock
				where gsItemId = @cur_ItemId
				and gsGodownId = @cur_GodownId
		
		-- if it does not exist
		if @recCount = 0
		begin
			-- insert to stock table
			insert moiGodownStock(gsGodownId, gsItemId,
				gsStock, gsShipmentId, gsItemCost, gsStockdate)
				select @cur_GodownId,  @cur_ItemId,
				@ItemQty, @cur_shipmentId, @cur_cost, getdate()
		end
		else	-- if the record exists in the stock table
		begin
			-- update stock table
			update moiGodownStock set gsStock =  gsStock + @ItemQty
					where gsItemId = @cur_ItemId
					and gsGodownId = @cur_GodownId
		End
		-- get next record from the cursor
		fetch next from cursor_Detail into
			@cur_RecoveryId, @cur_GodownId, @cur_ItemId,
			@cur_AddQty, @cur_DedQty,
			@cur_cost, @cur_ShipmentId
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlights]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateFlights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlightOperator]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateFlightOperator]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 04/Oct/2010
--Created by	: Praveen S
--Comments	: For Updating the Details In Flight Operator
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateFlightOperator]
@flghtopcompanyid INT,
@flghtopid INT,
@flghtopname VARCHAR(50),
@flghtsegid INT,
@flghtremarks VARCHAR(50),
@flghtactive BIT
AS BEGIN
	 SET NOCOUNT ON
	 UPDATE FlightOperatorMaster
	 SET FlghtOpName = @flghtopname,Remarks = @flghtremarks,Active = @flghtactive,FlghtSegID=@flghtsegid
	 WHERE FlghtOpid = @flghtopid AND companyid = @flghtopcompanyid
	 SET NOCOUNT OFF
	UPDATE Flights
	SET Active = @flghtactive
	WHERE FlightOpid = @flghtopid AND companyid = @flghtopcompanyid
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateDailyShopStock]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateDailyShopStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 18/01/2003 9:45:45 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 03/10/2002 5:06:54 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 14/09/2002 12:48:16 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 31/07/2002 2:00:35 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 20/11/2001 9:59:12 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 17/11/2001 9:22:19 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 16/06/2001 15:36:36 ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 09/03/2001 02:32:28 ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 12/05/00 1:40:16 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 10/17/00 2:19:53 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyShopStock    Script Date: 10/7/00 11:08:01 AM ******/
CREATE proc [dbo].[spUpdateDailyShopStock] (@intShopID as int, @strTransDate as varchar(10)) as
Declare
	@dtTransDate as datetime,
	@dtStockDate as datetime,
	@intShipmentID as int,
	@intItemID as int,
	@intOpeningStock as numeric(18,3),
	@intStock as numeric(18,3),
	@intOpeningBadStock as numeric(18,3),
	@intBadStock as numeric(18,3),
	@numItemCostPrice as numeric(18,2)
set nocount on
begin tran
set @dtTransDate = @strTransDate
SELECT @dtStockDate =  max(StockDate) FROM mosShopStock WHERE ShopID = @intShopID
if @dtTransDate > @dtStockDate
begin
	Declare ShopStockCur cursor for
	SELECT ShipmentID, ItemID, OpeningStock, Stock, OpeningBadStock, BadStock, ItemCostPrice
	FROM mosShopStock WHERE ShopID = @intShopID AND StockDate = @dtStockDate
	open ShopStockCur
	fetch next from ShopStockCur into
	@intShipmentID, @intItemID, @intOpeningStock, @intStock, @intOpeningBadStock,
	@intBadStock, @numItemCostPrice
	while @@fetch_status = 0
	begin
		if @intStock <> 0 or @intBadStock <> 0
			INSERT INTO mosShopStock (ShopID, StockDate, ShipmentID, ItemID,
			OpeningStock, Stock, OpeningBadStock, BadStock, ItemCostPrice)
			VALUES (@intShopID, @dtTransDate, @intShipmentID, @intItemID,
			@intStock, @intStock, @intBadStock, @intBadStock, @numItemCostPrice)
		fetch next from ShopStockCur into
		@intShipmentID, @intItemID, @intOpeningStock, @intStock, @intOpeningBadStock,
		@intBadStock, @numItemCostPrice
	end
	close ShopStockCur
	deallocate ShopStockCur
end		
commit tran
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateDailyGodownStock]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateDailyGodownStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 18/01/2003 9:45:45 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 03/10/2002 5:06:54 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 14/09/2002 12:48:16 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 31/07/2002 2:00:36 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 20/11/2001 9:59:14 AM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 17/11/2001 9:22:24 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 16/06/2001 15:36:37 ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 09/03/2001 02:32:28 ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 12/05/00 1:40:16 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 10/17/00 2:19:52 PM ******/
/****** Object:  Stored Procedure dbo.spUpdateDailyGodownStock    Script Date: 10/7/00 11:07:59 AM ******/
CREATE proc [dbo].[spUpdateDailyGodownStock] (@intGodownID as int, @strTransDate as varchar(10)) as
Declare
	@dtTransDate as datetime,
	@dtStockDate as datetime,
	@intLocationID as int,
	@intShipmentID as int,
	@intItemID as int,
	@intOpeningStock as numeric(18,3),
	@intStock as numeric(18,3),
	@intOpeningBadStock as numeric(18,3),
	@intBadStock as numeric(18,3),
	@numItemCost as numeric(18,2)
set nocount on
begin tran
set @dtTransDate = @strTransDate
SELECT @dtStockDate =  max(gsStockDate) FROM moiGodownStock WHERE gsGodownID = @intGodownID
if @dtTransDate > @dtStockDate
begin
	Declare GodownStockCur cursor for
	SELECT gsLocationID, gsShipmentID, gsItemID, gsOpeningStock, gsStock, gsOpeningBadStock,
	gsBadStock, gsItemCost
	FROM moiGodownStock WHERE gsGodownID = @intGodownID AND gsStockDate = @dtStockDate
	open GodownStockCur
	fetch next from GodownStockCur into
	@intLocationID, @intShipmentID, @intItemID, @intOpeningStock, @intStock,
	@intOpeningBadStock, @intBadStock, @numItemCost
	while @@fetch_status = 0
	begin
		if @intStock <> 0 or @intBadStock <> 0
			INSERT INTO moiGodownStock (gsGodownID, gsLocationID, gsStockDate,
			gsShipmentID, gsItemID,	gsOpeningStock, gsStock, gsOpeningBadStock,
			gsBadStock, gsItemCost)
			VALUES (@intGodownID, @intLocationID, @dtTransDate, @intShipmentID,
			@intItemID, @intStock, @intStock, @intBadStock, @intBadStock,
			@numItemCost)
		fetch next from GodownStockCur into
		@intLocationID, @intShipmentID, @intItemID, @intOpeningStock, @intStock,
		@intOpeningBadStock, @intBadStock, @numItemCost
	end
	close GodownStockCur
	deallocate GodownStockCur
end		
commit tran
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateRecepieDetails]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateRecepieDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---Create Stored Procedure - spUpdateRecepieDetails
--Created By   : Hariharan
--Created Date : 15/10/2004
--Comments     : Sp Created for Getting Receipe Details For BOT
CREATE Proc [dbo].[spUpdateRecepieDetails] @intCompanyId int, @intOutletId int,
@intBotId int, @intBillId as int as
set nocount on
Begin
Create table #tempBotDetails
(DishId int,
ItemID int,
UnitID int,
qty numeric(18,3),
itemrate numeric(18,2),
DishCheck int,
packingtypeid int)
Declare @intCount as int
Insert #tempBotDetails
Select fb_rd_dishID, Fb_rd_itemid, au.UnitID, fb_rd_quantity * Fb_bd_botquantity,
ai.itemrate, Fb_rd_Futurebit, null from fb_recipedetails rd, AUnit  au,
aitem ai, fb_botdetails bt where ai.itemid=rd.fb_rd_itemid and ai.unitsid=au.unitid
and rd.fb_rd_dishID = fb_bd_dishid and Fb_rd_Companyid = Fb_bd_Companyid and
bt.Fb_bd_botid = @intBotId and fb_bd_Outletid = @intOutletId and
Fb_bd_Companyid = @intCompanyId order by rd.Fb_rd_itemid
Select @intCount = count(*) from #tempBotDetails where DishCheck=1
while @intCount <> 0
Begin
Insert #tempBotDetails
Select rd.fb_rd_dishID, Fb_rd_itemid, au.UnitID, fb_rd_quantity*qty,
ai.itemrate, rd.Fb_rd_Futurebit, null from #tempBotDetails tmp,
fb_recipedetails rd, AUnit  au, aitem ai where ai.itemid=rd.fb_rd_itemid and
ai.unitsid=au.unitid and rd.fb_Rd_CompanyId=1 and rd.fb_rd_dishID = tmp.itemid
and tmp.DishCheck=1
--AVOIDING THE DISH ITEM DETAILS WHICH ARE ITSELF A DISH AGAIN
Update #tempBotDetails set DishCheck = 2 where dishid in
(Select itemid from #tempBotDetails)
--CHECKING FOR ITEMS WHICH ARE DISH AGAIN
Select @intCount = Count(*) From #tempBotDetails Where DishCheck=1
End
Update #tempBotDetails Set PackingTypeId = p.packingtypeid From
aItemPackingDetail p Where #tempBotDetails.itemid = p.itemid
and p.packingslno = 1
Delete from LosPosDetail where posdShopId = @intOutLetId and
posdBillid = @intBillId
Insert LosPosDetail(posdShopID, posdBillID, posdItemID, posdPackingTypeID,
posdPUnitID, posdQuantity,  posdcostprice)
Select @intOutletId, @intBillId, ItemId, PackingtypeId, UnitID, sum(qty), itemrate
From #tempBotDetails Where DishCheck <> 2 Group by ItemId, PackingtypeId,
UnitID, itemrate
End
Set NoCount Off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSHeaderAsOn07062011]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSHeaderAsOn07062011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdatePOSHeaderAsOn07062011]
@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,2),
@intDiscount As  Numeric(18,2),
@intBillAmt As  Numeric(18,2),
@intCashAccId As Int,
@intCustId As Int,
@strRemarks As Varchar(250),
@intCmpExRate As  Numeric(18,2),
@intDiscountAmt As  Numeric(18,2) ,
@intDeliveryNeeded  as Int=0
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
Where poshBillId=@intBillId And poshShopId=@intShopId
End
----------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSHeader]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdatePOSHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spYearEndCheck]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearEndCheck]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 01/06/2004, 13/07/2004
-- Modified by   : Hariharan
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : included consolidation venki 261203
--		 : Removed cursor and given temporary table names
--		 : carry forwarding of unclosed financial year done
--		 : Financialid considerations corrected
--		 : consolidation option department wise is corrected
--		 : Script Verified
CREATE PROCEDURE [dbo].[spYearEndCheck] (@strToDate as varchar(10),
@intCompanyID as int,
@intDepartmentId as int, @bitCons as int =0 ) AS
Begin
set nocount on
Declare @AcCode as varchar(100),
	@AcID as int,
	@dblDebit as numeric(18,2),
	@dblCredit as numeric(18,2),
	@GroupID as int,
	@dtToDate as datetime,
	@dtFromDate as datetime,
	@strFromdate as varchar(10),
	@intCount as integer,
	@intFinId as int,
	@dtPrevFinUnclosedSDate as datetime,
	@dtLastFinUnclosedEDate as datetime,
	@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
Create table #BalSheet(
	CompanyID int,
	AccCode varchar(100),
	AcDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	Closing numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	ParentGroupID int,
	AccId int,
	DepartmentId int)
	set @dtToDate = CONVERT(DATETIME,@strToDate)
	select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
	 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	insert #Tempjournalheader
	Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
	and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
	Journaldate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid = @intDepartmentId
	--to change the parent group if level id > 0	
	Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
	OBDr, Closing, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)	
	Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
	GroupDesc, OBDR, Closing, DebitAmt, CreditAmt, ParentGroupID, AccountID,
	daDepartmentid from (SELECT am.CompanyId, AccountID, AccountCode, AccountDesc,
	AccountType, GM.GroupID, GM.GroupDesc, 0 OBDR, 0 Closing, 0 DebitAmt, 0 CreditAmt,
	ParentGroupID, daDepartmentid FROM aAccountMaster AM,aGroupMaster GM,
	adeptAccounts d WHERE GM.GroupID = AM.GroupID AND
	(GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND
	AM.CompanyID = @intCompanyID and am.Accountid = d.daAccountId and
	am.CompanyId = d.daCompanyId and d.dadepartmentid = @intDepartmentId
	Union
	SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
	GM.GroupDesc, 0 OBDR, 0 Closing, 0 DebitAmt, 0 CreditAmt, ParentGroupID, @intDepartmentId
	FROM aAccountMaster AM,aGroupMaster GM,
	vwGlobalAccounts d  WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
	GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
	and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId	
	group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
	GroupDesc, OBDR, Closing, DebitAmt, CreditAmt, ParentGroupID, AccountID,
	daDepartmentid ORDER BY GrpAcId.AccountID
	Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
	aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId
	and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
	Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set OBdr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	
	Update #BalSheet set Closing = obDr + DebitAmt - CreditAmt where AcType=''A''
	Update #BalSheet set Closing = obDr + CreditAmt - DebitAmt  where AcType=''L''
set @dblDebit = 0.0
set @dblCredit = 0.0
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid = @intDepartmentId
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
and d.departmentid = @intDepartmentId
Update #BalSheet set Closing = Closing + @dblCredit - @dblDebit  from aSettings s
where #BalSheet.AccId = s.Retainedearningsacc
set @intFinId = @intFinId + 1
Select ''OP'', AccId, AccCode, AcDesc, AcType, GroupName, Closing, OpeningDepAmount
from #BalSheet left outer join aAccountFinyearopening
on #BalSheet.DepartmentId = aAccountFinyearopening.departmentid
and #BalSheet.Companyid = aAccountFinyearopening.CompanyId
and #BalSheet.AccId = aAccountFinyearopening.AccountID and
@intFinId =  aAccountFinyearopening.FinancialId
where #balSheet.Closing <> isnull(aAccountFinyearOpening.OpeningDepAmount,0)
and #balSheet.Closing <> 0	
UNION ALL
	
Select ''YE'', AccId, AccCode, AcDesc, AcType, GroupName, Closing, OpeningDepAmount
from #BalSheet left outer join ayearendtemp
on #BalSheet.DepartmentId = ayearendtemp.departmentid
and #BalSheet.Companyid = ayearendtemp.CompanyId
and #BalSheet.AccId = ayearendtemp.AccountID and
@intFinId =  ayearendtemp.FinancialId
where #balSheet.Closing <> isnull(ayearendtemp.OpeningDepAmount,0)
and #balSheet.Closing <> 0	
	
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
Drop Table #BalSheet
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spYearEnd]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spYearEnd]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--modified by  : Hariharan,Aneesh
--Modified Date  : 28/02/2004
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)
--   : used temporary tables for getting data after fetching for first time
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--Modified By :Benzigar S D
--Modified On :20/11/2010
--Comment     :Increased the length of ReferenceNo and Remarks
CREATE  proc [dbo].[spYearEnd] @intCompanyid as varchar(10) as
set nocount on
begin
declare @dtFROMDate as datetime
declare @dtToDate as datetime,
@intNextFinyearid as int,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int,
@intretainedearningsacc as int
CREATE table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup       int)
CREATE table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(1000),
Remarks varchar(1000),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
CREATE table #TrialBal(
CompanyID int,
DepartmentId int,
DepartmentName varchar(100),
accountid int,
AccCode varchar(50),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
Debit numeric(18,2),
Credit numeric(18,2),
OpBal numeric(18,2),
dDebit numeric(18,2),
dCredit numeric(18,2),
dOpBal numeric(18,2),
cDebit numeric(18,2),
cCredit numeric(18,2),
cOpBal numeric(18,2))
delete from ayearendtemp
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId
set @intNextFinyearid = @intLastFinId + 1
SELECT @dtFROMDate = SDATE, @dtToDate  = EDATE from vwfinyearperiod where CompanyId = @intCompanyId
and financialId = @intLastFinId
select @intretainedearningsacc = retainedearningsacc from asettings where companyId = @intCompanyId
-- ALTER the temporary table to insert sub departments
insert #Tempjournalheader
Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtFromDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
JournalDate>= @dtFromDate and JournalDate <=@dtToDate and
h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
h.CompanyId = @intCompanyId
insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,
AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, dDebit, dCredit, dOpBal, cDebit, cCredit, cOpBal )
Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,
a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,
0, 0, 0, 0, 0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where
a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid
and a.CompanyId = @intCompanyid
Update #TrialBal set OpBal = opening.OpeningActualamount, dOpBal = opening.OpeningDepamount,
cOpBal = opening.Openingamount from (Select AccountId,
DepartmentId, CompanyId, Openingamount, OpeningActualamount, OpeningDepamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.DepartmentId = #TrialBal.DepartmentId
and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
Update #TrialBal set Debit = trialDeb.Actualamount, dDebit = trialDeb.Depamount,
cDebit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(Amount,0)) Amount, Sum(isnull(depAmount,0)) depamount,
Sum(isnull(ActualAmount,0)) Actualamount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #TrialBal set Credit = trialDeb.Actualamount, dCredit = trialDeb.depamount,
cCredit = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, Sum(isnull(Amount,0)) Amount, Sum(isnull(depAmount,0)) depamount,
Sum(isnull(ActualAmount,0)) Actualamount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
--delete from #TrialBal where departmentid in
--(Select departmentid from #TrialBal where accountid <> @intretainedearningsacc group by DepartmentId
--having sum(debit) = 0 and sum(credit)=0 and sum(OpBal)=0 )
--Delete from #TrialBal where accountid in
--(Select accountid from #TrialBal where accountid <> @intretainedearningsacc group by accountid
--having sum(debit) = 0 and sum(credit) = 0 and sum(OpBal)=0)
insert into aYearEndTemp
Select CompanyID, AccountId, AcType, @intNextFinyearid, (cOPBal + cDebit - cCredit), (dOPBal + dDebit - dCredit) ,
(OPBal + Debit - Credit), AccCode, AccDesc, Departmentid, DepartmentName from #TrialBal where AcType =''A''
insert into aYearEndTemp
Select CompanyID, AccountId, AcType, @intNextFinyearid, (cOPBal +  cCredit - cDebit ), (dOPBal + dCredit- dDebit ) ,
(OPBal + Credit- Debit), AccCode, AccDesc, Departmentid, DepartmentName from #TrialBal where AcType =''L''
--UPDATING PROFIT
Update aYearEndTemp set openingActualamount = openingActualamount+Bal, openingdepamount = openingdepamount  + dBal,
openingamount =  openingamount + cBal
from (Select @intretainedearningsacc AccId, DepartmentId, sum(OpBal+ Credit + Debit) Bal,
sum(dOpBal+dCredit-dDebit) dBal, sum(cOpBal+cCredit - cDebit) cBal from #TrialBal where
AcType in (''I'', ''E'') group by Departmentid) profit where AccountId = AccId and
aYearEndTemp.Departmentid = profit.DepartmentID
delete from aYearEndTemp where openingamount =0 and openingdepamount = 0 and openingactualamount = 0
select * from aYearEndTemp
drop table #TrialBal
drop table #vwJournalDetails
drop table #Tempjournalheader
end
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersPAndCBill]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersPAndCBill]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 30/11/2002, 16/07/2003, 27/08/2003, 06/02/2004
-- Modified by      	: leo, Hariharan R, Kishore, Hariharan R
-- comments		: modified for new exchange rate concept
--			: modified to handle the lctoaccount ( 0 or 1) feature
-- 			:  Corrected the journal id, detail id misplacing probs (27/08/2003)
--			: other chareges amount additing to the header amount avoided
--			: as in header amount it will include the other charges
-- 			: Modified on 22/04/03 - blocking error for journal inserting
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE PROC [dbo].[spUpdateLedgersPAndCBill] @intCompanyID as int, @intBillID as int AS
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@strBillNo as varchar(50),
	@dtBillDate as datetime,
	@intVendorID as int,
	@strRemarks as varchar(300),
	@intDepartmentID as int,
	@numBillAmt as numeric(18,2),
	@intGITAccid as int,
	@bitposted as bit,
	@intpoid as int,
	@numdepRate as numeric(18,9),
	@numconsRate as numeric(18,9),
	@strexrates as varchar(250),
	@dtutime as datetime,
	@intcurrencyid as int,
	@LCtobeAccounted as int,
	@intRefJournalid as int,
	@numLCAmount	as numeric(18,2)
	
	select @LCtobeAccounted = isnull(Lctoaccount,0) from miscsettings
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
		WHERE CompanyID = @intCompanyID
	SELECT @intBillID= pbhBillID, @strBillno= pbhBillNo, @dtBillDate = pbhBillDate,
	@intVendorID=pbhVendorID, @numBillAmt = pbhbillamount, @strRemarks = pbhRemarks,
	@intFinancialID = pbhFinancialID, @intDepartmentid = pbhDepartmentID, @intGITAccid =
	pbhPurchaseAccID, @numconsRate = pbhexchangerate, @intpoid= pbhpoid, @dtutime =
	updatetime, @numdepRate = pbhdepexrate, @strexrates = pbhexchangerates ,
	@numLCAmount = isnull(pbhLcAmount,0) from losppurchasebillheader
	where pbhPosted = 0 and pbhCompanyID = @intCompanyID
	and pbhCancelled = 0 and pbhbillid = @intBillID
	-- hari added to post whole amount credit to supplier if the lc is not to be accounted	
	if @LCtobeAccounted = 0
		set @numBillAmt = @numBillAmt + @numLCAmount  	
		
	set @intJournalDetailID = 1
	set @intJournalID = @intJournalID + 1
	select @intcurrencyid = currencyid from avendormaster where companyid =
	@intcompanyid and vendorid = @intvendorid
	if @numbillamt <> 0
	begin		
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno,
		remarks, financialID,Type,CurrencyID,cancel,realised, chequedate,updatetime)
		values (@intJournalID, @intCompanyID, @dtBillDate, @strBillNo,
		@strRemarks, @intFinancialID, ''PACB'', @intCurrencyID, 0, 0, @dtbilldate, @dtutime)			
		-- if the po  used in this bill is posted already then it has to be reversed
		select @bitposted = pohposted from lopurchaseorderheader
			where pohcompanyid = @intcompanyid
			and pohpoid = @intpoid
		
		if (@bitposted = 1)
		begin
			select @intRefJournalid = journalid from  moajournalheader where cancel =0
			and referenceno = (select pohpono from lopurchaseorderheader
						where pohpoid = @intpoid)
						
			insert into moajournaldetails(JournalDetailID, JournalID, JournalCredit,
			AccountID ,CustomerID,VendorID   ,Amount, ActualAmount ,CompanyID ,
			DepartmentID ,depamount  )
			
			 select  @intJournalDetailID, @intjournalid, abs(JournalCredit-1), AccountID,
			CustomerID, VendorID, Amount, ActualAmount,
			CompanyID, DepartmentID, depamount
			from moajournaldetails
			where vendorid is not null
			and journalid = @intRefJournalid
	
			set @intJournalDetailID = @intJournalDetailID + 1
			
			insert into moajournaldetails (JournalDetailID, JournalID, JournalCredit,
			AccountID ,CustomerID,VendorID   ,Amount, ActualAmount ,CompanyID ,
			DepartmentID ,depamount  )
			select @intJournalDetailID, @intjournalid, abs(JournalCredit-1), AccountID,
			CustomerID, VendorID, Amount, ActualAmount,
			CompanyID, DepartmentID, depamount
			from moajournaldetails
			where accountid is not null and
			journalid = @intRefJournalid
			set @intJournalDetailID = @intJournalDetailID + 1
		end
		-- end of po posting reversal
		/* crediting  the Vendor account with bill amt - lc amount*/
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, vendorID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intVendorID, @numbillAmt * @numconsrate ,@numbillamt,@intDepartmentid,
		@numbillamt * @numdeprate)
			
		set @intJournalDetailID = @intJournalDetailID + 1
		declare @numvendorer as numeric(18,2),
			@numaccer as numeric(18,2),
			@numaccpoamt as numeric(18,2)			
		exec spReturnExrate @intcurrencyid, @strexrates, @numvendorer output
		--to arrive on account currency equivalent, vendorid
		select @intcurrencyid = currencyid from aaccountmaster where
		companyid = @intcompanyid and accountid = @intGITAccid
		exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
		exec spconvertcurrency @numvendorer, @numaccer, @numbillamt, @numaccpoamt output
		 --debit the goods in transit account  with bill amt + lc mar amount split posting
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, accountID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intgitaccID, @numbillAmt* @numconsRate, @numaccpoamt ,@intDepartmentid,
		@numbillamt * @numdeprate)
		Set @intjournalDetailID = @intjournalDetailID + 1
	end	-- if billamount
	update losppurchasebillheader
		set pbhpostED = 1
		WHERE pbhBillID = @intBillID
		and pbhCompanyID = @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgerspandcRet]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgerspandcRet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLEDgerspandcRet    Script Date: 18/01/2003 9:45:47 PM ******/
-- Last Modified on 	: 30/11/2002
-- Modified by      	: leo
-- comments		: modified for new exchange rate concept
CREATE proc [dbo].[spUpdateLEDgerspandcRet] @intCompanyID as int, @intBillID as int as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@strBillNo as varchar(50),
	@dtBillDate as datetime,
	@intVendorID as int,
	@strRemarks as varchar(300),
	@intDepartmentID as int,
	@numBillAmt as numeric(18,2),
	@intPurchaseAccid as int,
	@bitposted as bit,
	@intpoid as int,
	@numdepRate as numeric(18,9),
	@numconsRate as numeric(18,9),
	@strexrates as varchar(250),
	@dtutime as datetime,
	@intcurrencyid as int
	
	select @intPurchaseAccid = PurchaseRtnAccID from apackagesettings where
	companyid = @intCOmpanyid
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID
	SELECT @intBillID = prhreturnid, @strBillno= prhreturnno, @dtBillDate = prhreturndate,
	@intVendorID = prhvendorid, @numBillAmt = sum(prdsuppamount) ,
	@strRemarks = prhremarks, @intFinancialID = prhFinancialID,
	@intDepartmentid = prhDepartmentID, @numconsRate = prhexrate, @dtutime = prhReturnupdatetime,
	@numdepRate = prhdepexrate, @strexrates = prhexchangerates from loPurchaseReturnheader,
	loPurchaseReturnDetail where  prhReturnID=prdReturnID And prhposted =0 and prhcompanyid =
	@intCompanyID and prhcancelled =0 and prhreturnid=@intBillID
	group by prdcompanyid, prhreturnid, prhreturnno, prhreturndate, prhvendorid,
	prhremarks, prhFinancialID, prhDepartmentID, prhexrate, prhReturnupdatetime, prhdepexrate,
	prhexchangerates
	set @intJournalDetailID = 1
	set @intJournalID = @intJournalID + 1
	select @intcurrencyid = currencyid from avendormaster where companyid =
	@intcompanyid and vendorid = @intvendorid
	begin		
		insert into moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno,
		remarks, financialID,Type,CurrencyID,cancel,realised, chequedate,updatetime)
		values (@intJournalID, @intCompanyID, @dtBillDate, @strBillNo,
		@strRemarks, @intFinancialID,''pcret'',@intCurrencyID,0,0, @dtbilldate, @dtutime)			
		/* Debiting  the Vendor account with return amount*/
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, vendorID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
		@intVendorID, @numbillAmt * @numconsrate ,@numbillamt,@intDepartmentid,
		@numbillamt * @numdeprate)
			
		set @intJournalDetailID = @intJournalDetailID + 1
		declare @numvendorer as numeric(18,2),
			@numaccer as numeric(18,2),
			@numaccamt as numeric(18,2)			
		--to get Vendor CurrencyId
		select @numvendorer = currencyid from aVendorMaster where
		companyid = @intcompanyid and Vendorid = @intvendorid
		--to arrive on account currency equivalent, vendorid
		select @intcurrencyid = currencyid from aaccountmaster where
		companyid = @intcompanyid and accountid = @intPurchaseAccid
		exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
		exec spconvertcurrency @numvendorer, @numaccer, @numbillamt, @numaccamt output
		 --Crediting purchase return accid
		insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
		JournalCrEDit, accountID, Amount, actualAmount, Departmentid, depamount)
		values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
		@intPurchaseAccid, @numbillAmt* @numconsRate, @numaccamt ,@intDepartmentid,
		@numbillamt * @numdeprate)
		
	end	-- if billamount
	update loPurchaseReturnheader  set prhposted =1 WHERE prhreturnid = @intBillID
	and prhcompanyid = @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldExchangeRates2]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateOldExchangeRates2]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------
--Created on 	: 21/07/2003
--Created by 	: R Harikrishnan
--Comments	: To correct all the exchange rates in a table
-----------------------------------------------------------------------------------------
--Modified on 	: 25/08/2003
--Modified by 	: R Harikrishnan
--Comments	: Modified for updating the Vendor Customer Exchange Rates in Payments
--		: and receipts
-----------------------------------------------------------------------------------------
CREATE Procedure [dbo].[spUpdateOldExchangeRates2]
	@intCompanyID 		as int,			--The companyID (mandatory)
	@strTableName 		as varchar(250), 	--The name of the table(Mandatory)
	@strWherecondition	as varchar(250),	--The name of the table(Optional)
	@strConExRateColName 	as varchar(250),	--The consolidation exchange rate
							--column name of the strTablename
	@strDepExRateColName 	as varchar(250),	--The department exchange rate
							--column name of the strTablename
							--(Mandatory)
	@strExRatesColName 	as varchar(250),	--The exchange rates string
							--column name of the strTablename
							--(Mandatory)
	@strPKColName1	 	as varchar(250),	--The first primary column name of the
							--strTablename (shopID,companyID,GodownID)
							--(Mandatory)
	@strPKColName2	 	as varchar(250),	--The second primary column name of the
							--strTablename (Mandatory)
	@strPKColName3	 	as varchar(250),	--The third primary column name of the
							--strTablename (Optional)
	@strCustIDColName 	as varchar(250),	--The customerID column name of
							--strTablename (Optional)
	@strVendIDColName 	as varchar(250),	--The vendor id column name of
							--strTablename (Optional)
	@strAccIDColName 	as varchar(250),	--The AcountID column name of
							--strTablename (Optional)
	@strPurShopIDColName 	as varchar(250),	--The purchase shopid column name of
							--strTablename (Optional)
	@strAccIDValue	 	as varchar(250),	--The account value of the transaction
							--strTablename (InventoryID)(Optional)
	@strPKType 		as char(1)		--''S'' for ShopID
							--''G'' for GodownID
					  		--''C'' for CompanyID
as
begin
	Create Table #TempExRates
	(
		PkCol1		int not null,
		PkCol2		int not null,
		PkCol3		int null,
		CustomerID	int null,
		VendorID	int null,
		AccountID	int null,
		PurShopID	int null
	)
	--Commented for testing purpose
--	set @strTableName=''losInvoiceHeader''
--	set @strPKColName1=''ihShopID''
--	set @strPKColName2=''ihInvoiceID''
--	set @strAccIDValue=''''
--	set @strPKType=''S''
--	set @strWherecondition='' where ihInvoiceID=2''
--	set @strConExRateColName=''ihexchangerate''
--	set @strDepExRateColName=''ihdepexrate''
--	set @strExRatesColName=''ihexchangerates''
--	set @intCompanyID =1
	declare @strSql 		as nVarchar(2000),
		@intCount		as int,
		@intPK1			as int,
		@intPK2			as int,
		@intPK3			as int,
		@intLoopCount		as int,
		@intCustomerID 		as int,
		@intVendorID 		as int,
		@intAccountID 		as int,
		@intPurShopID		as int
	set @strSql= ''select '' + @strPKColName1 + '','' + @strPKColName2 + '','' +
		isnull(@strPKColName3,''Null'') + '','' +
		isnull(@strCustIDColName,''Null'') + '','' +
		isnull(@strVendIDColName,''Null'') + '',''  +
		case 	when isnull(@strAccIDColName,'''')<>'''' then @strAccIDColName
			when isnull(@strAccIDValue,'''')<>'''' then @strAccIDValue
			else ''Null'' end + '',''  + isnull(@strPurShopIDColName,''Null'') +
		'' from '' + @strTableName + '' '' + isnull(@strWherecondition,'''')
	--inserting the details into the temporary table
	insert into #TempExRates
		exec sp_executesql @strSql
	--Getting the total count
	select
		@intCount=count(PkCol1)
	from
		#TempExRates
	--Setting the count to the total count	
	set @intLoopCount=@intCount
	while @intLoopCount<>0
	begin
		select top 1
			@intPK1=PkCol1,@intPK2=PkCol2,@intPK3=PkCol3,@intCustomerID=CustomerID,
			@intVendorID=VendorID,@intAccountID=AccountID,@intPurShopID=PurShopID
		from
			#TempExRates order by PkCol1,PkCol2,PkCol3
		--exec spUpdateOldExchangeRates1 @intGodownID,@intShopID@intDepartmentID,
		--@intCompanyID,@intCustomerID,@intVendorID,@intAccountID,
		--@intTransID,@strTableName,@strConExRateColName,@strDepExRateColName,
		--@strExRatesColName,@strPKColName1,@strPKColName2,@strPKColName3,
		--@strPKColName3Value,@strPKType
		--For Shops
		if @strPKType=''S''
		begin
			exec spUpdateOldExchangeRates1 null,@intPK1,null,@intCompanyID,@intCustomerID,
				@intVendorID,@intAccountID,@intPurShopID,@intPK2,@strTableName,@strConExRateColName,
				@strDepExRateColName,@strExRatesColName,@strPKColName1,@strPKColName2,
				@strPKColName3,@intPK3,@strPKType
		end
		
		--For godown
		if @strPKType=''G''
		begin
			exec spUpdateOldExchangeRates1 @intPK1,null,null,@intCompanyID,@intCustomerID,
				@intVendorID,@intAccountID,@intPurShopID,@intPK2,@strTableName,@strConExRateColName,
				@strDepExRateColName,@strExRatesColName,@strPKColName1,@strPKColName2,
				@strPKColName3,@intPK3,@strPKType
		end
		
		--For the Customer Vendor Updation
		if @strPKType=''R''
		begin
			exec spUpdateOldExchangeRates1 null,null,@intPK1,@intCompanyID,@intCustomerID,
				@intVendorID,@intAccountID,@intPurShopID,@intPK2,@strTableName,@strConExRateColName,
				@strDepExRateColName,@strExRatesColName,@strPKColName1,@strPKColName2,
				@strPKColName3,@intPK3,@strPKType
		end
		--For Company
		if @strPKType=''C''
		begin
			exec spUpdateOldExchangeRates1 null,null,@intPK1,@intCompanyID,@intCustomerID,
				@intVendorID,@intAccountID,@intPurShopID,@intPK2,@strTableName,@strConExRateColName,
				@strDepExRateColName,@strExRatesColName,@strPKColName1,@strPKColName2,
				@strPKColName3,@intPK3,@strPKType
		end
		--For Journal
		if @strPKType=''J''
		begin
			exec spUpdateOldExchangeRates1 null,null,@intPK1,@intCompanyID,@intCustomerID,
				@intVendorID,@intAccountID,@intPurShopID,@intPK2,@strTableName,@strConExRateColName,
				@strDepExRateColName,@strExRatesColName,@strPKColName1,@strPKColName2,
				@strPKColName3,@intPK3,@strPKType
		end
		--Delete the row after updation
		delete from #TempExRates where
			PkCol1=@intPK1 and PkCol2=@intPK2 and isnull(PkCol3,0)=isnull(@intPK3,0)
	
		set @intLoopCount=@intLoopCount-1
	end
	drop table #TempExRates
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersServiceInv]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersServiceInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateLedgersServiceInv    Script Date: 18/01/2003 9:45:45 PM
-- Last Modified on : 01/12/2002
-- Modifed by       : leo
Ref No1
Modified By: Shine Das
Modified On: 22.09.2011
Comments   : Need to include Posting of GST
------------------
Ref No2
Modified By: Nidheesh P V
Modified On: 29.10.2011
Comments   : Checked isnull condition
------------------
Ref No 3
Modified By: SHINE DAS
Modified On: 25.04.2012
Comments   : Department amount for customer was wrong.
------------------
*/
CREATE proc [dbo].[spUpdateLedgersServiceInv] @intCompanyID as int, @intinvoiceid as int as
begin
Declare @intCashAccountID as int,
@intJournalID as int,
@intJournalDetailID as int,
@intSAccountID as int,
@numSAmount as numeric(18,2),
@intFinancialID as int,
@dtInvoiceDate as datetime,
@intCustomerID as int,
@strInvoiceNo as varchar(50),
@strRemarks as varchar(200),
@intDiscountAccountID as int,
@numDiscount as numeric(18,2),
@intDepartmentID as int,
@bitCash as bit,
@bitProduct as bit,
@numTotalInvValue as numeric(18,2),
@dtutime as datetime,
@numconsrate as numeric(18,9),
@numdeprate as numeric(18,9),
@intcurrencyid as int,
@strexrates as varchar(250),
@numseraccamt as numeric(18,2),
@intServiceTaxID INT, ---Ref No1
@intGSTOutPutAccountID INT, ---Ref No1
@numGSTTaxAmount as numeric(18,9), ---Ref No1
@numAccGSTTaxAmount as numeric(18,9) ---Ref No1
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
CompanyID = @intCompanyID
---Ref No1  start
select @intServiceTaxID=isnull(TaxCategoryforServices,0) from apackagesettings
IF (@intServiceTaxID<>0)
Begin
select @intGSTOutPutAccountID=TaxAccountId from aTaxCategoryMaster where TaxId  =@intServiceTaxID
END
--- ---Ref No1  end
set @intJournalID = @intJournalID + 1
---Ref No1  Commented below snippet
/*
SELECT @intInvoiceID= InvoiceID, @dtInvoiceDate = InvoiceDate, @intCustomerID =
CustomerID, @strInvoiceno = InvoiceNo, @strRemarks = case when (chequeno is null or
chequeno ='''') then remarks else chequeno + '';'' + remarks end, @intDiscountAccountID =
DiscountAccountID, @numDiscount = Discount, @intDepartmentID = DepartmentID,
@bitProduct = Product, @intFinancialID = FinancialID, @intCashAccountID = BankCashID,
@numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,
@strexrates = exchangerates FROM AccountsInvoiceHeader
WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and
Product = 0 and invoiceid = @intInvoiceID
*/
SELECT @intInvoiceID= InvoiceID, @dtInvoiceDate = InvoiceDate, @intCustomerID =
CustomerID, @strInvoiceno = InvoiceNo, @strRemarks = case when (chequeno is null or
chequeno ='''') then remarks else chequeno + '';'' + remarks end, @intDiscountAccountID =
DiscountAccountID, @numDiscount = isnull(Discount,0) , @intDepartmentID = DepartmentID,   -- Ref No2
@bitProduct = Product, @intFinancialID = FinancialID, @intCashAccountID = BankCashID,
@numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,
@strexrates = exchangerates, @numGSTTaxAmount=isnull(TaxAmount,0) FROM AccountsInvoiceHeader  --Ref No2
WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and
Product = 0 and invoiceid = @intInvoiceID
set @numTotalInvValue =0
exec spConvertequiamount @intcustomerid, ''c'', @intGSTOutPutAccountID, ''a'',
@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output
-- get cash or crEDit
if (@intCashAccountID is null) --crEDit trans
begin
SELECT @intcurrencyid = CurrencyID FROM aCustomerMaster
WHERE CompanyID = @intCompanyID and CustomerID = @intCustomerID
INSERT INTO moajournalheader(JournalID, CompanyID, JournalDate, ReferenceNo,
Remarks, FinancialID, Type, CurrencyID, chequedate, updatetime)
VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate, @strInvoiceNo,
@strRemarks, @intFinancialID, ''AI'', @intcurrencyid, @dtinvoicedate, @dtutime)
set @intJournalDetailID = 1
Declare ServiceInv cursor for
SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails
WHERE CompanyID = @intCompanyID and InvoiceID = @intInvoiceID
ORDER BY InvoiceDetailID
open ServiceInv
FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
while @@fetch_status = 0
begin
exec spConvertequiamount @intcustomerid, ''c'', @intSAccountID, ''a'',
@strexrates, @numSAmount, @numseraccamt output
/* inserting the sales account with the full invoice Amount */
INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,
@intSAccountID, (@numSAmount * @numconsRate),
@numseraccamt, @intDepartmentID, (@numSAmount * @numdepRate) )
set @numTotalInvValue  = @numTotalInvValue  + @numSAmount
set @intJournalDetailID = @intJournalDetailID +1
FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
end
close ServiceInv
deallocate ServiceInv
/* check if discount allowED if allowED then post discount details */
if @numDiscount > 0
begin
exec spConvertequiamount @intcustomerid, ''c'', @intDiscountAccountID, ''a'',
@strexrates, @numDiscount, @numseraccamt output
INSERT INTO moajournaldetails(JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDiscountAccountID, (@numDiscount * @numconsRate),
@numseraccamt,@intDepartmentID, (@numDiscount * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
end
INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
JournalCredit, CustomerID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intCustomerID, (((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount)*@numconsRate),
(@numTotalInvValue - @numDiscount)+@numGSTTaxAmount,@intDepartmentID,
--((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount*@numdepRate))        -----Ref No 3 IMPROPER BRACKETING FOUND
((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount)*@numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
end  -- end for crEDit trans
else
begin -- cash trans
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID and AccountID = @intCashAccountID
INSERT INTO moajournalheader(JournalID, CompanyID, JournalDate, ReferenceNo,
Remarks, FinancialID, Type, CurrencyID, chequedate,updatetime)
VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate, @strInvoiceNo,
@strRemarks, @intFinancialID, ''AI'', @intcurrencyid, @dtinvoicedate, @dtutime)
set @intJournalDetailID = 1
Declare ServiceInv cursor for
SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails
WHERE CompanyID = @intCompanyID and InvoiceID = @intInvoiceID
ORDER BY InvoiceDetailID
open ServiceInv
FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
while @@fetch_status = 0
begin
exec spConvertequiamount @intCashAccountID, ''a'', @intSAccountID, ''a'',
@strexrates, @numSAmount, @numseraccamt output
/* inserting the sales account with the full invoice Amount */
INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,
@intSAccountID, (@numSAmount * @numconsRate),
@numseraccamt, @intDepartmentID, (@numSAmount * @numdepRate))
set @numTotalInvValue  = @numTotalInvValue  + @numSAmount
set @intJournalDetailID = @intJournalDetailID +1
FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
end
close ServiceInv
deallocate ServiceInv
/* check if discount allowED if allowED then post discount details */
if @numDiscount > 0
begin
exec spConvertequiamount @intCashAccountID, ''a'', @intDiscountAccountID, ''a'',
@strexrates, @numDiscount, @numseraccamt output
INSERT INTO moajournaldetails(JournalID, JournalDetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,
@intDiscountAccountID, (@numDiscount * @numconsRate),
@numseraccamt, @intDepartmentID, (@numDiscount * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
end
INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,
@intCashAccountID, ((@numTotalInvValue - @numDiscount) *
@numconsRate),(@numTotalInvValue - @numDiscount),@intDepartmentID,
((@numTotalInvValue - @numDiscount) * @numdepRate)  )
set @intJournalDetailID = @intJournalDetailID +1
end -- end for cash
/* mark the record as postED */
---Ref No1 start posting of GST amount
IF (@intServiceTaxID<>0)
Begin
--   exec spConvertequiamount @intcustomerid, ''c'', @intGSTOutPutAccountID, ''a'',
--@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output
INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,
@intGSTOutPutAccountID, (@numGSTTaxAmount * @numconsRate),
@numAccGSTTaxAmount, @intDepartmentID, (@numGSTTaxAmount * @numdepRate) )
set @intJournalDetailID = @intJournalDetailID +1
END
---Ref No1 end posting of GST amount
UPDATE AccountsInvoiceHeader SET Posted = 1 WHERE CompanyID = @intCompanyID and
InvoiceID = @intInvoiceID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAllotedStock]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAllotedStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created on 	: 05/05/03
--created by	: leo
CREATE proc [dbo].[spAllotedStock] @intshopid as int as
begin
	set nocount on
	create table #temp1(
		orderno		varchar(50)	null,
		orderdate 	datetime	null,
		referenceno	varchar(100)	null,
		customername	varchar(100)	null,
		salespername	varchar(100)	null,
		itemname	varchar(250)	null,
		itemid 		int		null,
		Quantity	numeric(18,3)	null,
		amount  	numeric(18,2)	null,
		curStock		numeric(18,3)	null
		)
insert into #temp1
select h.ihinvoiceno Orderno, h.ihinvoicedate orderdate, h.ihreferenceno, c.customername,
sp.spername, vw.itemdescription, d.iditemid, sum(d.idquantity) Quantity, sum(d.idunitprice) amount, 0.0  from
losinvoicedetail d , acustomermaster c, vwitemdescription vw, losinvoiceheader h
left outer join (select ihproformaid invid, ihshopid shopid from losinvoiceheader
where ihcancelled=0 and ihtype =''i'' ) inv on
h.ihinvoiceid = inv.invid and h.ihshopid = inv.shopid
left outer join asalespersonmaster sp on h.ihsalespersonid = sp.sperid
where h.ihcustomerid = c.customerid and h.ihshopid = d.idshopid and h.ihinvoiceid = d.idinvoiceid and
h.ihcancelled =0 and h.ihshopid = @intshopid and h.ihtype = ''p'' and h.ihtransfinished =1 and
isnull(inv.invid,0) =0 and d.iditemid = vw.itemid
group by h.ihinvoiceno, h.ihinvoicedate, h.ihreferenceno, c.customername, sp.spername,
vw.itemdescription, d.iditemid
update #temp1 set curstock = stock from vwinquiryshopstock, #temp1 where
vwinquiryshopstock.itemid  = #temp1.itemid
select orderno, orderdate, referenceno, customername, salespername, itemname, Quantity,
amount, curStock from #temp1
drop table #temp1
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwunpostedposbills]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwunpostedposbills]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwunpostedposbills] as
select shopname,poshbillno,poshbilldate,poshbillamount,poshcancelled, poshcancelledremarks,poshposted,username  from
LOsPosHeader inner join ashops on shopid=poshshopid inner join lousers on userid = poshuserid  where poshposted =0'
GO
/****** Object:  View [dbo].[vwHQAccinterdevBills]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccinterdevBills]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By : VinothMurugan V.
--Date    : 13/10/2010
--Purpose   : showing inter divisional bills
create view [dbo].[vwHQAccinterdevBills] as
select bh.companyid companyid, bh.billsid, bh.departmentid, bh.billsno, bh.referenceno,
bh.billdate, dateadd(day,dueperiod,billdate) duedate, bh.vendorid,
sum(bd.amount) billamount, 0 as paidamount,''IDB'' Type from InterDivisionBillsHeader bh, InterDivisionBillsDetails bd
where bh.companyid = bd.companyid and bh.billsid = bd.billsid and bh.cancelled=0 and
bh.cashpurchase=0 group by bh.companyid,  bh.billsid, bh.departmentid,bh.billsno, bh.referenceno,
bh.billdate, bh.dueperiod, bh.vendorid'
GO
/****** Object:  View [dbo].[vwpartsfromcustomer]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpartsfromcustomer]'))
EXEC dbo.sp_executesql @statement = N'
--created by dheena
--created date 10-06-2003
--purpose :using partsfromcustomer sub report
--,that report used in rptbooking
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE  view [dbo].[vwpartsfromcustomer] as
select  custprodcompanyid,custprodbookingid, custprodshopid,custprodcomments,''Parts From Customer'' type,sercallbkhno serbookhno,
sercallbkhrecvdfrom serbookhrecvdfrom, sercallbkhdate serbookhdate,
itemid,itemdescription,customerid,customername,serbookadvanceamount,AccountDesc, sercallbkhtime serbookhtime,
cast(datepart(hh,sercallbkhtime)as varchar)+'':''+
cast(datepart(mi,sercallbkhtime)as varchar) +'':''+
cast(datepart(ss,sercallbkhtime) as varchar) time,itemcode,custprodname,custprodqty,
isnull(custprodusedqty,0) usedqty, custprodusecomments from
losservicebookingheader bk inner join loscallbookingheader los on los.serCallBkhid=serbookhrefid
and los.serCallBkhcompanyid=bk.serbookhcompanyid and bk.serbookhshopid=los.serCallBkhshopid
left outer join acustomermaster on sercallbkhcustomerid=customerid
left outer join aaccountmaster on serbookadvanceacc=accountid,losserpartsfromcustomer
left outer join aitem on custprodproductid=itemid where
custprodbookingid=serbookhid and custprodshopid=serbookhshopid
and custprodcompanyid=serbookhcompanyid'
GO
/****** Object:  View [dbo].[vwpaymentlisting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentlisting]'))
EXEC dbo.sp_executesql @statement = N'
--sp_helptext vwpaymentlisting
--select * from vwpaymentlisting
--Last Modified on  : 08/03/2003 ,17/06/2007,
--Modified by   : leo  ,Shinu,Aadyakumar
--Comments   : added the currency symbol to the view  ,Added phPaymentVoucherNo,Added AccountDesc
CREATE view  [dbo].[vwpaymentlisting] as
select  ph.phcompanyid companyid, ph.phpaymentid paymentid, ph.phpaymentno, ph.phpaymentdate paymentdate,
ph.phPayee Payee, ph.phvendorid vendorid, v.vendorname, ph.phremarks remarks, ph.phbankcashid bankcashid,
ph.phcustomeramount customeramount, ph.phCancelled, ph.phDepartmentID, ph.phCancelledRemarks, ph.phPosted,
d.DepartmentName, ph.phAmount, c.symbol, ph.phChequeDetails,ph.phPaymentVoucherNo,acc.AccountDesc
from
ahqpaymentvoucherheader ph, aaccountmaster acc, avendormaster v,aDepartmentMaster d, acurrencymaster c
where
ph.phcompanyid*=v.companyid and ph.phvendorid *= v.vendorid and
ph.phcompanyid = acc.companyid and ph.phbankcashid = acc.accountid and
ph.phDepartmentID = d.DepartmentID and ph.phCompanyID=d.CompanyID and
acc.companyid = c.companyid and acc.currencyid = c.currencyid and phlcpayment = ''OP'''
GO
/****** Object:  View [dbo].[vwpaymentCLbankwise]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentCLbankwise]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 08/03/02
--Modified by 		: leo
--Comments 		: v3
CREATE view [dbo].[vwpaymentCLbankwise] as
select phcompanyid companyid, phpaymentid paymentid, phpaymentdate paymentdate, phpaymentno paymentno,
phcbreferenceno cbreferenceno, phpayee payee, phbankcashid bankcashid, phamount amount, case when phcancelled =1
then ''Yes'' else ''No'' end as cancelled, phremarks cancelledremarks, a.accountdesc, phDepartmentID, phchequedetails,
symbol, phremarks from ahqpaymentvoucherheader ph, aaccountmaster a, acurrencymaster c where ph.phcompanyid = a.companyid and
phbankcashid = a.accountid and a.companyid = c.companyid and a.currencyid = c.currencyid and ph.phlcpayment =''OP'''
GO
/****** Object:  View [dbo].[vwPaymentCheckList]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPaymentCheckList]'))
EXEC dbo.sp_executesql @statement = N'
/*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Last Modified on 	: 28/12/02
Modified by 		: dheena
Comments 		: add dep id
-------------------------------------------------------------------
Modified on          : 31/08/2003
Modified by          : Kishore
Comments             : Added UpdateTime field
Verified by 	    : Hariharan
Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-------------------------------------------------------------------*/
CREATE VIEW [dbo].[vwPaymentCheckList]
AS
SELECT     ph.phCompanyID, ph.phPaymentID, ph.phPaymentNo, ph.phPaymentDate, ph.phPayee,
CASE WHEN (ph.phcustomerid IS NOT NULL) THEN ''Customer'' WHEN (ph.phvendorid IS NOT NULL) THEN ''Vendor'' ELSE ''Others'' END AS caption,
CASE WHEN (ph.phcustomerid IS NOT NULL) THEN cm.customername WHEN (ph.phvendorid IS NOT NULL)
THEN vm.vendorname ELSE ''N/A'' END AS custorven, bacc.AccountDesc, ph.phRemarks, ph.phChequeDetails AS chequeno, ph.phPosted,
ph.phCancelled, ph.phAmount, ph.phcbreferenceno AS bankrefno, ph.phExchangeRate, ph.phCustomeramount AS vendoramount, dm.DepartmentName,
ph.phDepartmentID, ph.updatetime
FROM         dbo.aHQPaymentVoucherHeader AS ph LEFT OUTER JOIN
dbo.aCustomerMaster AS cm ON ph.phCompanyID = cm.CompanyID AND ph.phCustomerID = cm.CustomerID LEFT OUTER JOIN
dbo.aVendorMaster AS vm ON ph.phCompanyID = vm.CompanyID AND ph.phVendorID = vm.VendorID INNER JOIN
dbo.aAccountMaster AS bacc ON ph.phCompanyID = bacc.CompanyID AND ph.phBankCashID = bacc.AccountID INNER JOIN
dbo.aDepartmentMaster AS dm ON ph.phCompanyID = dm.CompanyID AND ph.phDepartmentID = dm.DepartmentID'
GO
/****** Object:  View [dbo].[vwhpSPfinding]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhpSPfinding]'))
EXEC dbo.sp_executesql @statement = N'
----Created by Prasanth KNR
----To get the Hire Purchase item Selling price
----Last modified :
CREATE view [dbo].[vwhpSPfinding] as
select sp.sellingprice,sp.itemid from
losshopitemshipmentdetail sp inner join aitem a on sp.itemid=a.itemid
inner join aitempackingdetail ap on sp.itemid=ap.itemid and sp.packingTypeid=ap.packingTypeid'
GO
/****** Object:  View [dbo].[vwOpeningStock]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOpeningStock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwOpeningStock    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwOpeningStock    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwOpeningStock    Script Date: 31/07/2002 2:00:27 PM ******/
CREATE view [dbo].[vwOpeningStock] as
select shipmentid, itemid, sum(opstock) opstock, sum(stock) stock from
(select gsshipmentid shipmentid, gsitemid itemid, isnull(gsopeningstock,0) opstock, isnull(gsstock,0) stock from moigodownstock where gsshipmentid=1
union all
select shipmentid, itemid, isnull(openingstock,0) opstock, isnull(stock,0) from mosshopstock where shipmentid=1) s
group by shipmentid,itemid'
GO
/****** Object:  View [dbo].[vwHQAccBills]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccBills]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwHQAccBills    Script Date: 18/01/2003 9:45:35 PM ******/
--modified by : hariharan
--modified date : 04/11/2002
--departmentid given in header instead of detail table
-------------------------------------------------------
--Modified by : VinothMurugan V.
--Date		  : 13/10/2010
--Purpose	  : adding type
CREATE view [dbo].[vwHQAccBills] as
select bh.companyid companyid, bh.billsid, bh.departmentid, bh.billsno, bh.referenceno,
bh.billdate, dateadd(day,dueperiod,billdate) duedate, bh.vendorid,
sum(bd.amount) billamount, 0 as paidamount,''AB'' Type from Bills bh, billsdebitdetails bd
where bh.companyid = bd.companyid and bh.billsid = bd.billsid and bh.cancelled=0 and
bh.cashpurchase=0 group by bh.companyid,  bh.billsid, bh.departmentid,bh.billsno, bh.referenceno,
bh.billdate, bh.dueperiod, bh.vendorid'
GO
/****** Object:  View [dbo].[vwGoodsRequestToHq]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodsRequestToHq]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 08/12/2003, 16/06/2004
-- Modified by  : Kishore, Hariharan R
-- Comments  : Added the case when for itemdescription
--     for catalog sales (06/08/2003 - R Harikrishnan)
--                      : Added Unit code (08/12/2003)
--   : Correncyid =1 condition is given to filter only mrf price and to avoid
--   : duplication of rows
--   : removed the sellingprice fetching to make fast
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create view [dbo].[vwGoodsRequestToHq] as
select
GRHrequestID, GRHshopID, GRHrequestNO, GRHrequestDate, GRHremarks, GRDgoodQty,
ai.ItemCode, convert(varchar(500),(case when isnull(grdreqcomments,'''')='''' then ai.ItemDescription  else
ai.ItemDescription + '' - '' +grdreqcomments  end)) ItemDescription, ai.ItemRate,ai.modelno, 0 Sellingprice, z.SizeName,
c.ColorName, grhrequesttype, u.Unitcode
from
mosgoodsrequestheader, mosgoodsrequestdetail,
/*left outer join vwshopitemshipmentdetailpu sd
on grditemid = sd.itemid and grdshopid = sd.shopid and 1 = sd.Currencyid */
aitem ai left outer join acolor c on ai.colorid = c.colorid
left outer join asize z on ai.sizeid = z.sizeid, aUnit u
where
grhrequestid = grdrequestid
and grhshopid = grdshopid
and grditemid = ai.itemid
and ai.UnitsId = u.UnitId'
GO
/****** Object:  View [dbo].[vwreexportinvoices]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportinvoices]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------
--Modified on 	: 04/08/2003
--Modifies By	: R Harikrishnan
--Comments	: Added ExchangeRates String field
--Modifies By	: venki 100903
--Comments	: added invoice TYpe only for accounts settlements
----------------------------------------------------------------
CREATE view [dbo].[vwreexportinvoices]  as
select
	h.rehcompanyid companyid, h.rehdepartmentid, h.rehshopid shopid,
	h.rehReferenceNo refno, h.rehexportid invoiceid, h.rehexportno invoiceno,
	h.rehexportdate invoicedate, h.rehDueDate, rehcustomerid customerid, rehexportamount,
	0 as settled, "RE" as type, isnull(rehReferenceNo,'''') referenceno,
	isnull(rehremarks,'''') remarks, rehupdatetime, h.rehFinancialID, h.rehexchangerate,
	h.rehdepexrate,h.rehexchangerates
from
	losexportheader h
where
	h.rehcancelled=0 and rehcustomerid is not null and h.rehtype like ''%i%'''
GO
/****** Object:  View [dbo].[vwPurchaseAmount]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseAmount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwPurchaseAmount    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwPurchaseAmount    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwPurchaseAmount    Script Date: 31/07/2002 2:00:29 PM ******/
/****** Object:  View dbo.vwPurchaseAmount    Script Date: 20/11/2001 9:59:01 AM ******/
/****** Object:  View dbo.vwPurchaseAmount    Script Date: 17/11/2001 9:21:34 PM ******/
CREATE view [dbo].[vwPurchaseAmount] as
select ph.pohpoid , sum(pd.podQty*pd.podUnitPrice) purchaseAmount from loPurchaseOrderHeader ph,
lopurchaseorderdetail pd where ph.pohpoid=pd.podPoid  group by ph.pohpoid'
GO
/****** Object:  View [dbo].[vwprePurchaseOrderTracking1]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwprePurchaseOrderTracking1]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created By   : Benzigar S D
--Created Date : 09082008
------------------------------------------------------------------------
create view [dbo].[vwprePurchaseOrderTracking1] as
select a.pohpoid,
case when a.pohrequestid is not null then mos.Grhrequestno end as ShopRequetNO,
case when a.pohquotationid is not null then ab.pohpono end as QuotationNo,ab.pohquotationid,ab.pohrequestid as PoRequestid,
case when a.pohshopid is not null then a.pohshopid else ab.pohshopid end as pohshopid
from loprePurchaseOrderHeader a left outer join mosgoodsrequestheader mos on a.pohrequestid=mos.grhrequestid and a.pohshopid =mos.grhshopid
left outer join loprePurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
where  a.pohtype=''PP'''
GO
/****** Object:  View [dbo].[vwprePurchaseAmount]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwprePurchaseAmount]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created By     : Benzigar S D
--Date             08092008
------------------------------------------------------------------------
create view [dbo].[vwprePurchaseAmount] as
select ph.pohpoid , sum(pd.podQty*pd.podUnitPrice) purchaseAmount from loprePurchaseOrderHeader ph,
loprepurchaseorderdetail pd where ph.pohpoid=pd.podPoid  group by ph.pohpoid'
GO
/****** Object:  View [dbo].[vwpostingsdifference]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpostingsdifference]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpostingsdifference    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwpostingsdifference    Script Date: 14/09/2002 12:48:05 AM ******/
CREATE view [dbo].[vwpostingsdifference] as
select cr.journalid, cramount, dramount from
(select h.journalid, sum(d.amount) cramount
from moajournalheader h, vwjournaldetails d where h.journalid = d.journalid and h.cancel =0 and h.financialid <> 0
and d.journalcredit =1
group by h.journalid) cr,
(select h.journalid, sum(d.amount) dramount
from moajournalheader h, vwjournaldetails d where h.journalid = d.journalid and h.cancel =0 and h.financialid <> 0
and d.journalcredit =0
group by h.journalid) dr where
cr.journalid = dr.journalid and cramount <> dramount'
GO
/****** Object:  View [dbo].[vwPosSalesForReport]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosSalesForReport]'))
EXEC dbo.sp_executesql @statement = N'
-- View
----sp_helptext vwPosSalesForReport
--------------------------------------------------------------
-- Created by  : Kishore
-- Created on  : 29/07/2003
-- Comments    : Taken from v2
--               This view is used in rptPosSales
--------------------------------------------------------------
-- Modified by : Kishore
-- Modified on : 14/07/2003
-- Comments    : Added posdFreeQuantity column
--------------------------------------------------------------
--Modified by : Yogesh Joe
--Modified on : 31-07-2009
--Comments    : To handle kit item.
---------------------------------------------------------------
--Modified by : Regin
--Modified on : 30-01-2010
--Comments    : To add a new column to get comma separated Serial Numbers
---------------------------------------------------------------
--Modified by : Sreejith G A
--Modified on : 17-06-2010
--Comments    : Added the column ac.AccountDesc to the view. Left outer join
--    of aAccountMaster with poshCashAccId already existed. So just added
--     the column ac.AccountDesc to the query
---jyothish SR
---Modifeid :02-12-2010  serila number filed is added
--fnIssueSerialNos  function returns serila number
---------------------------------------------------------------
---  losHpItemRegistrationDetails   added to  the vwPosSalesForReport
--Modified By : VinothMurugan V.
--Date    : 09/02/2010
--Purpose   : Adding HirePurchase,address1,address2 Column
--Client : Sheesha
--------------------------------
-- RefNo :01
--Modified by : Shine Das
--Modified on : 16-09-2011
--Comments    : To bring warranty feature some fields added
-----------------------------------------------------------
-- RefNo :02
--Modified by : Aadyakumar.D.V
--Modified on : 01-10-2011
--Comments    : Added CUSTOMERTIN  column
-----------------------------------------------------------
-- RefNo :03
--Modified by : Shine Das
--Modified on : 22-11-2011
--Comments    : Added posdbilldetailid  column
-----------------------------------------------------------
--RefNo :04
--Modified by : Aadyakumar.D.V
--Modified on : 22-11-2011
--Comments    : Added poshCashAccID  to identify the account id
--Comments    : Added Type to identify the mode of transaction
-----------------------------------------------------------
-- RefNo :05
--Modified by : Shine Das
--Modified on : 29-11-2011
--Comments    : Added posdItemTaxPercentage  column
-----------------------------------------------------------
-- RefNo :06
--Modified by : Bijesh.B
--Modified on : 27-12-2011
--Comments    : included column poshCustomerTIN in case of cash customer
-----------------------------------------------------------
-- RefNo :07
--Modified by : Bijesh.B
--Modified on : 30-01-2012
--Comments    : Mode of payment is wrong in case of full pd cheque (Bugsheet)
-----------------------------------------------------------
-- RefNo :08
--Modified by : Bijesh.B
--Modified on : 09-02-2012
--Ticket Id   : TON-249295
--Comments    : Need to enter TIN,if Cutomer TIN is empty in customer master
-----------------------------------------------------------
CREATE VIEW [dbo].[vwPosSalesForReport] AS
SELECT posdItemType,posdKitID,poshBillAmount,isnull(spername, '''') spername,
case when (posdDescription is null or posdDescription ='''') then
vw.ItemDescription
else posdDescription
end ItemDescription, losposheader.poshBillId, poshBillNo, losposheader.poshShopId, poshBillDate,
posdItemId, posdQuantity, posdPQuantity, posdUnitPrice,
posdActualUnitPrice, posdCostPrice,
poshRecAddUser, poshRecModifyUser, UnitCode, PackingTypeCode, poshCustomerName,
Symbol, posdPackingTypeId, u.UnitId, a.ItemCode,
UnitName, PackingTypeName, poshCancelledRemarks Remarks, posdFreeQuantity, poshCancelled,
IRRegistrationID, IRRegistrationNo,IRRegistrationDate,IRShipment,IRMode,IRCancel,IRForSales,IRModelNo,
IREngineNo,IRFrameno, IRProduction,IRCase,IRLocation,IRCustomerID, IRRegNo,IRRoadWorthiness, IRSold,IRSoldColor,
IRRemarks,IRUserName, IRUpdateUser, IRUpdateTime,IREngineCapacity,IRSeatingCapacity,IRManufactureYear,
IRImportYear , IRTypeofVehicle,hirepurchase,address1,address2,
dbo.fnIssueSerialNos(1502, losposheader.poshShopId, losposheader.poshBillId, posdItemId) posdSerialNo,posdServWarrantyUpto,posdPartsWarrantyUpto,  ----- RefNo :01 added for warranty
-- RefNo :08 start commneted and added
	--CASE isnull(losPosHeader.poshcustomerid,0) WHEN 0 THEN losPosHeader.poshCustomerTIN    -- RefNo :06
	--ELSE CM.CUSTOMERTIN END  -- RefNo :06
	CASE ISNULL(CM.CUSTOMERTIN,'''') WHEN '''' THEN  losPosHeader.poshCustomerTIN
	ELSE CM.CUSTOMERTIN END
-- RefNo :08 ends
AS CUSTOMERTIN,posdItemTaxAmount,poshDiscount,   -- RefNo :02
posdbilldetailid,-- RefNo :03
--RefNo :04 ---------------start---------------------
poshCashAccID,
-- RefNo :07   START COMMENTED BELOW AND ADDED
	--case ac.misc when ''CC'' then ''Credit Card''
	--             when ''DC'' then ''Debit Card''
	--             when ''CA'' then ''Cash''
	--             when null then ''''
	--			 else ''''		
	--end
	--+
	--case poshChequeAccID when 0 then ''''
	--                     when null then ''''
	--			         else ''\Post Dated Cheque''		
	--end
	CASE losposheader.poshBillAmount - ISNULL(chq.PosBankAmount,0) when 0 then
		''Post Dated Cheque''
	ELSE
		case ac.misc when ''CC'' then ''Credit Card''
					 when ''DC'' then ''Debit Card''
					 when ''CA'' then ''Cash''
					 when null then ''''
					 else ''''		
		end
		+
		case poshChequeAccID when 0 then ''''
							 when null then ''''
							 else ''\Post Dated Cheque''		
		end
	END
-- RefNo :07   ENDS
Type,posdItemTaxPercentage   -- RefNo :05
--RefNo :04 ---------------end---------------------
FROM losPosHeader left outer join aSalesPersonMaster sp
ON sp.sperId = poshSalesPersonId
LEFT OUTER JOIN aAccountMaster ac
ON ac.AccountId = poshCashAccId
left OUTER JOIN losHpItemRegistrationDetails  lhp ON --lhp.IRShopID=losPosHeader.poshShopID  and
lhp.IRTransactionID= losPosHeader.poshBillID and IrInterfaceID = 1502
LEFT OUTER JOIN aCurrencyMaster c
ON ac.CurrencyId = c.CurrencyId
left outer join acustomermaster cm on losPosHeader.poshcustomerid = cm.CustomerID
-- RefNo :07   start
left outer join losPosChequeDetails Chq on  Chq.PoshBillID=losposheader.PoshBillID
and Chq.PoshShopID=losposheader.PoshShopID
-- RefNo :07   ends
, losPosDetail, aItem a, aPackingType p,
vwItemDescription vw, aUnit u
WHERE losposheader.poshShopId = posdShopId and losposheader.poshBillId = posdBillId
and posdPackingTypeId = p.PackingTypeId
and posdItemId = a.ItemId
and a.ItemId = vw.ItemId
and u.unitid = a.unitsid
and (posdItemType <> ''K'' OR  posdItemType is null) --To exclude kit item.We will consider it separately in the below code.Yogesh Joe 31-07-2009
--Yogesh Joe 31-07-2009
--In the below code we are considering only kit items(ie,posdItemType = ''K'').Since kit item is stored in the losPosDetail table by splitting the
--items separately(Refer spInsertPOSDetail),we have to find out the corresponding kit name while taking it back for report.Instead of splitted items
--we are showing the corresponding kit name.
union all
SELECT posdItemType,posdKitID,poshBillAmount,isnull(spername, '''') spername,
case when (KIM.KitName is null or KIM.KitName ='''') then
KIM.KitCode
else KIM.KitName
end KitName, losposheader.poshBillId, poshBillNo, losposheader.poshShopId, poshBillDate,
KIM.KitId, posdKitQuantity, posdKitQuantity, sum(posdUnitPrice) posdUnitPrice,
cast((sum(posdUnitPrice)/posdKitQuantity) as numeric(8,2)) posdActualUnitPrice,--Since We can''t give discount to kit item in POS interface we are considering the selling price of kit item as actual selling price.
sum(posdCostPrice) posdCostPrice,
poshRecAddUser, poshRecModifyUser,u.UnitCode,p.PackingTypeCode, poshCustomerName,
Symbol,p.PackingTypeID,KIM.UnitId,KIM.KitCode,
u.UnitName,p.PackingTypeName, poshCancelledRemarks Remarks, posdFreeQuantity, poshCancelled ,
IRRegistrationID, IRRegistrationNo,IRRegistrationDate,IRShipment,IRMode,IRCancel,IRForSales,IRModelNo,
IREngineNo,IRFrameno, IRProduction,IRCase,IRLocation,IRCustomerID, IRRegNo,IRRoadWorthiness, IRSold,IRSoldColor,
IRRemarks,IRUserName, IRUpdateUser, IRUpdateTime,IREngineCapacity,IRSeatingCapacity,IRManufactureYear,
IRImportYear , IRTypeofVehicle,hirepurchase,address1,address2,
dbo.fnIssueSerialNos(1502, losposheader.poshShopId, losposheader.poshBillId, posdItemId) posdSerialNo,posdServWarrantyUpto,posdPartsWarrantyUpto, -- RefNo :01 ---added for warranty
-- RefNo :08 start commneted and added
	--CASE isnull(losPosHeader.poshcustomerid,0) WHEN 0 THEN losPosHeader.poshCustomerTIN    -- RefNo :06
	--ELSE CM.CUSTOMERTIN END  -- RefNo :06
	CASE ISNULL(CM.CUSTOMERTIN,'''') WHEN '''' THEN  losPosHeader.poshCustomerTIN
	ELSE CM.CUSTOMERTIN END
-- RefNo :08 ends
AS CUSTOMERTIN,posdItemTaxAmount,poshDiscount,     -- RefNo :02
posdbilldetailid,-- RefNo :03
--RefNo :04 ---------------start---------------------
poshCashAccID,
-- RefNo :07   start commented and added
--case ac.misc when ''CC'' then ''Credit Card''
--             when ''DC'' then ''Debit Card''
--             when ''CA'' then ''Cash''
--             when null then ''''
--			 else ''''		
--end
--+
--case poshChequeAccID when 0 then ''''
--                     when null then ''''
--			         else ''\Post Dated Cheque''		
--end
CASE losposheader.poshBillAmount - ISNULL(chq.PosBankAmount,0) when 0 then
	''Post Dated Cheque''
ELSE
	case ac.misc when ''CC'' then ''Credit Card''
				 when ''DC'' then ''Debit Card''
				 when ''CA'' then ''Cash''
				 when null then ''''
				 else ''''		
	end
	+
	case poshChequeAccID when 0 then ''''
						 when null then ''''
						 else ''\Post Dated Cheque''		
	end
END
-- RefNo :07  ends
Type,posdItemTaxPercentage   -- RefNo :05
--RefNo :04 ---------------end---------------------
FROM losPosHeader
LEFT OUTER JOIN aSalesPersonMaster sp ON sp.sperId = poshSalesPersonId
LEFT OUTER JOIN aAccountMaster ac ON ac.AccountId = poshCashAccId
LEFT OUTER JOIN aCurrencyMaster c ON ac.CurrencyId = c.CurrencyId
LEFT OUTER JOIN losPosDetail ON losPosHeader.poshBillID=losPosDetail.posdBillID ---and losPosHeader.poshShopID=losPosDetail.posdShopID
LEFT OUTER JOIN akitItemMaster KIM ON losPosDetail.posdKitID=KIM.KitID
LEFT OUTER JOIN aUnit u ON  KIM.UnitID=u.UnitID
LEFT OUTER JOIN aPackingType p ON p.PackingTypeID=KIM.PackingTypeID    left OUTER JOIN losHpItemRegistrationDetails  lhp ON --lhp.IRShopID=losPosHeader.poshShopID
lhp.IRTransactionID= losPosHeader.poshBillID and IrInterfaceID = 1502
left outer join acustomermaster cm on losPosHeader.poshcustomerid = cm.CustomerID
-- RefNo :07   start
left outer join losPosChequeDetails Chq on  Chq.PoshBillID=losposheader.PoshBillID
and Chq.PoshShopID=losposheader.PoshShopID
-- RefNo :07   ends
,aItem
WHERE
losposheader.poshShopId = posdShopId
and losposheader.poshBillId = posdBillId
and posdItemType = ''K''
GROUP BY losposheader.poshShopId,poshBillDate,losposheader.poshBillId,poshBillNo,KIM.KitId,KIM.KitCode,KIM.KitName,p.PackingTypeID,p.PackingTypeCode,p.PackingTypeName,
KIM.UnitId,UnitCode,UnitName,posdKitQuantity,Symbol,poshCustomerName,spername,poshRecAddUser,
poshRecModifyUser,poshCancelledRemarks,posdFreeQuantity,poshCancelled,poshBillAmount,posdItemType,posdKitID ,IRRegistrationID
,IRRegistrationNo,IRRegistrationDate,IRShipment,IRMode,IRCancel,IRForSales,IRModelNo,
IREngineNo,IRFrameno, IRProduction,IRCase,IRLocation,IRCustomerID, IRRegNo,IRRoadWorthiness, IRSold,IRSoldColor,
IRRemarks,IRUserName, IRUpdateUser, IRUpdateTime,IREngineCapacity,IRSeatingCapacity,IRManufactureYear,
IRImportYear , IRTypeofVehicle ,hirepurchase,address1,address2,posdItemID,posdSerialNo,posdServWarrantyUpto,posdPartsWarrantyUpto, -- RefNo :01 ---added for warranty
CUSTOMERTIN,posdItemTaxAmount,poshDiscount,posdbilldetailid, -- RefNo :03
poshCashAccID,ac.misc,poshChequeAccID,posdItemTaxPercentage, -- RefNo :04
losPosHeader.poshcustomerid,losPosHeader.poshCustomerTIN
,chq.PosBankAmount -- RefNo :07'
GO
/****** Object:  View [dbo].[vwPosSales]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosSales]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 23/02/03
-- Modified by 		: leo
-- Comments		: v3
-------------------------------------------------------------------------
-- Modified on		: 14/10/2003
-- Modified by		: Kishore
-- Comments		: Added posdFreeQuantity, UnitCode columns
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-------------------------------------------------------------------------
CREATE VIEW [dbo].[vwPosSales] AS
select vw.itemdescription, a.itemcode, poshbillid,poshBillNo,poshshopid,poshBillDate,posditemid, posdquantity,
posdpquantity, posdunitprice, posdactualunitprice, posdcostprice, UnitName, packingtypename, accountdesc,Symbol,
poshexchangerate, poshdepexrate, poshCustomerName, posdFreeQuantity, UnitCode
from losposheader, losposdetail, aitem a,
apackingtype p, vwitemdescription vw, aunit u, aaccountmaster ac, acurrencymaster c
where poshshopid = posdshopid
and poshbillid = posdbillid
and posdpackingtypeid = p.packingtypeid
and posditemid = a.itemid
and a.itemid = vw.itemid
and u.unitid = a.unitsid
and ac.accountid = poshcashaccid
and ac.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwservicedbookdetails]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicedbookdetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwservicedbookdetails    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader,losserviceinvheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE view [dbo].[vwservicedbookdetails] as
select li.serinvno, li.serinvhdate, sh.serinvhcompanyid, sh.serinvhshopid, sh.serinvhid,
a.brand, bk.*, vw.itemdescription, a.modelno from losservicebookingheader bk, loscallbookingheader los,
vwitemdescription vw, aitem a, losserviceheader sh ,losserviceinvheader li where sercallbkhitemid = vw.itemid and
vw.itemid = a.itemid and sh.serinvhbookingid = bk.serbookhid and
sh.serinvhcompanyid = bk.serbookhcompanyid and sh.serinvhshopid = bk.serbookhshopid and
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid and li.serinvhjobcardid=sh.serinvhid and sh.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=sh.serinvhcompanyid'
GO
/****** Object:  View [dbo].[vwservicebookinginvoices]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicebookinginvoices]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on                  : 20/08/2003, 10/01/2004
--Modified by                  : Reji Abraham, Hariharan R
--Comments                     : Additional tables loscallbookingheader ,losserivceinvheader are added  and modified fields, previous fields are alias names
--			       : referred customerid from the invoice table
--			       : as  booking and estimation may not have customerid mandatorily
----------------------------------------------------------------
CREATE view [dbo].[vwservicebookinginvoices] as
--view created for taking the details of service booking and service invoiceing
-- for customerwise whose invoices are completed. - hari 020222
select serbookhid, serbookhshopid, serbookhcompanyid, serinvhCustomerID serbookhcustomerid, sercallbkhno serbookhno,
sercallbkhdate serbookhdate, sercallbkhpurchdate serbookhpurchdate, serbookhdeldate,  sercallbkhslno serbookhslno,serinvno, serinvhdate,
li.serinvhamount, sercallbkhrecvdfrom serbookhrecvdfrom, sercallbkhaddress serbookhaddress, serbookadvanceamount,
serbookhserviceamt + serbookhpartscost serbookhestamount, serbookhremarks, li.serinvhpreparedby,
c.customername, v.itemdescription completedescription,
a.itemdescription itemname,a.itemcode, a.part_Code, a.modelno, a.brand,
isnull(sh.serinvhcompleted,0) serinvhcompleted,
case  isnull(serbooksermode,0) when 1 then ''Service Out'' else ''Service In'' end servicemode,
serbookconfirmed, serbookhstatus from losservicebookingheader bh inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid left outer join
acustomermaster c on los.sercallbkhcustomerid= c.customerid and
bh.serbookhcompanyid = c.companyid
left outer join losserviceheader sh on bh.serbookhid = sh.serinvhbookingid and
bh.serbookhshopid = sh.serinvhshopid and bh.serbookhcompanyid = sh.serinvhcompanyid
inner join losserviceinvheader li on  li.serinvhjobcardid=sh.serinvhid and
li.serinvhshopid=sh.serinvhshopid and li.serinvhcompanyid=sh.serinvhcompanyid ,
ashops s, aitem a, vwitemdescription v where
los.sercallbkhitemid = a.itemid and a.itemid = v.itemid and bh.serbookhshopid = s.shopid'
GO
/****** Object:  View [dbo].[vwServDeptRevenueSeperated]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServDeptRevenueSeperated]'))
EXEC dbo.sp_executesql @statement = N'
----Created By Sreejith G A
--Create On : 26/25/2010
--Purpose :  To show rptServCentrServandPartsAmtRev(Service Amount and Parts Amount Revenue)
CREATE view [dbo].[vwServDeptRevenueSeperated]
as
select lih.serinvhid,lih.serinvhcompanyid,lih.serinvhdepartmentid,lih.serinvhshopid,lih.serinvno,lc.serCallBkhno ,c.customername,
lih.serinvhitemname,lih.serinvhserviceamt,lih.serinvhpartsamt,lih.serinvhamount,lih.serinvhdate ,cm.Symbol ,lih.serinvhcmpexrate,lih.seinvhdepexrate
from losserviceinvheader lih
inner join losserviceheader lsh on lsh.serinvhid=lih.serinvhjobcardid and lsh.serinvhshopid=lih.serinvhshopid
and lih.serinvhcancelled=0
inner join losservicebookingheader l on   lsh.serinvhbookingid = l.serbookhid and lsh.serinvhshopid=l.serbookhshopid
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
inner join acustomermaster c on c.customerid=lc.serCallBkhcustomerid
inner join acurrencymaster cm on c.currencyid=cm.currencyid
inner join asalespersonmaster spm on lih.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lih.serinvhshopid=spd.SperShopid'
GO
/****** Object:  View [dbo].[vwserviceinvlisting]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserviceinvlisting]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwserviceinvlisting    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on  : 28/12/02
--Modified by   : dheena
--Comments   : add deptid]
---------------------------------
--Modified On:07/07/2011
--Modified By:Aadyakumar.D.V
--comment    :bug fixed in duplication in column remark
---------------------------------------
CREATE view [dbo].[vwserviceinvlisting] as
select si.companyid, si.customerid, invoicedate, customername, si.invoiceid, invoiceno, discount,
sum(serviceqty * amount) amount, si.remarks, referenceno,si.departmentid from accountsinvoiceheader si,
serviceinvoicedetails sd, acustomermaster c
where si.companyid = sd.companyid and si.invoiceid = sd.invoiceid and
si.companyid = c.companyid and si.customerid = c.customerid and si.product = 0
group by
si.companyid, si.customerid, invoicedate, customername, si.invoiceid, invoiceno,
discount, si.remarks, referenceno,si.departmentid'
GO
/****** Object:  View [dbo].[vwServiceHistory]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceHistory]'))
EXEC dbo.sp_executesql @statement = N'
--Created By Sreejith on 04/03/2010
--select * from vwServiceHistory
CREATE view [dbo].[vwServiceHistory]
as
select serCallBkhid as Id,serCallBkhid as Tid,serCallBkhshopid as shopid,serCallBkhcompanyid as companyid,
serCallBkhno as RefNo,serCallBkhdate as Date,''Service Booking'' as type,serCallBkhinformedby as Contactname ,
serCallBkhtelephone as contactno,serCallBkhenteredby as InCharge from loscallbookingheader
union all
select lc.serCallBkhid  as Id,serbookhid as Tid,serbookhshopid as shopid,serbookhcompanyid as companyid,
serbookhInspectionNo as RefNo,serbookhInspectionDate as Date,''Estimation/Inspection'' as type,
lc.serCallBkhinformedby as Contactname,lc.serCallBkhtelephone as contactno,spm.Spername as InCharge
from losservicebookingheader l
inner join loscallbookingheader lc on lc.serCallBkhid=l.serbookhRefId and lc.serCallBkhshopid=l.serbookhshopid
and l.serbookhinpcancelled=0
inner join asalespersonmaster spm on l.serbookhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and l.serbookhshopid=spd.SperShopid
union all
select lc.serCallBkhid as Id,seaAppId as Tid,seaAppShopId as shopid,seaAppcompanyID as companyid,seaAppNo as RefNo,
seaAppDate as Date,''Estimation Approval'' as type,lc.serCallBkhinformedby as Contactname,
lc.serCallBkhtelephone as contactno,seaApprovedBy as InCharge from losserestimateapproval la
inner join losservicebookingheader l on l.serbookhid=la.seaAppbookingId and l.serbookhshopid=la.seaAppShopId
and seaAppCancelled=0
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
union all
select lc.serCallBkhid as Id,serinvhid as Tid,serinvhshopid as shopid,serinvhcompanyid as companyid,
serinvhprocno as RefNo,serinvhprocdate as Date,''Job Card'' as type,lc.serCallBkhinformedby as Contactname,
lc.serCallBkhtelephone as contactno,spm.Spername as InCharge from losserviceheader lsh
inner join losservicebookingheader l on   lsh.serinvhbookingid = l.serbookhid  and lsh.serinvhshopid=l.serbookhshopid
inner join loscallbookingheader lc on   l.serbookhRefId=lc.serCallBkhid and l.serbookhshopid=lc.serCallBkhshopid
inner join asalespersonmaster spm on lsh.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lsh.serinvhshopid=spd.SperShopid
union all
select lc.serCallBkhid as Id,lih.serinvhid as Tid,lih.serinvhshopid as shopid,lih.serinvhcompanyid as companyid,
serinvno as RefNo,serinvhdate as Date,''Service Invoice'' as type,lc.serCallBkhinformedby as Contactname,
lc.serCallBkhtelephone as contactno,spm.Spername as InCharge from losserviceinvheader lih
inner join losserviceheader lsh on lsh.serinvhid=lih.serinvhjobcardid and lsh.serinvhshopid=lih.serinvhshopid
and lih.serinvhcancelled=0
inner join losservicebookingheader l on   lsh.serinvhbookingid = l.serbookhid and lsh.serinvhshopid=l.serbookhshopid
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
inner join asalespersonmaster spm on lih.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lih.serinvhshopid=spd.SperShopid'
GO
/****** Object:  View [dbo].[vwservicedoneforotherbranditems]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicedoneforotherbranditems]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwservicedoneforotherbranditems    Script Date: 06/03/2003 09:13:12 ******/
/****** Object:  View dbo.vwservicedoneforotherbranditems    Script Date: 26/01/2003 18:14:32 ******/
/****** Object:  View dbo.vwservicedoneforotherbranditems    Script Date: 14/09/2002 12:48:06 AM ******/
--created by 	  	:- Hariharan
--Last Modified date	:- 020828
--Alterby               :-Dheena
--Last Modified date	:- 020903
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table losserviceinvheader is added  and modified fields, previous fields are alias names
CREATE view [dbo].[vwservicedoneforotherbranditems] as
select repinvcompanyid,  repinvinvoiceid, repinvdshopid, m.itemcode, m.itemdescription,
repinvdsellrate, repinvdrate, repinvdqty, repinvdcomments, serinvno,
serinvhdate, serinvhprocno, serinvhprocdate, li.serinvhcustname, li.serinvhrefno, li.serinvhremarks,
serinvhbookingid, li.serinvhitemname, li.serinvhitemid,b.brand  from losinvoicedpartsreplacedetails, aitem m,
losserviceinvheader li,losserviceheader ls, aitem b  where repinvdpartsid = m.itemid and li.serinvhcompanyid = repinvcompanyid and
li.serinvhshopid = repinvdshopid and li.serinvhid = repinvinvoiceid and b.itemid = li.serinvhitemid
and m.brand<>b.brand and li.serinvhjobcardid=ls.serinvhid and ls.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=ls.serinvhcompanyid'
GO
/****** Object:  View [dbo].[vwShopCustomerDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCustomerDetails]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
--Last Modified on  : 28/11/2009
--Modified by  : jyothish
--Comments  : shopcreditlimit is added
--Modified by  : MANUNADH.U ON 14.06.2011
--Comments  : ShopCreditLimit and HQCreditLimit are added for the Customer Profile Report[rptshopcustomerdetails.rpt,rptshopcustomerdetailsalloutlets.rpt]
----------------------------------------------------------
--Modified by  : AADYA KUMAR D V
--Modified on  : 03.12.2011
--Comments     : Added Age field for report rptshopcustomerdetails
----------------------------------------------------------
CREATE view [dbo].[vwShopCustomerDetails] as
select DISTINCT acm.*,asd.shopid,isnull(asd.creditlimit,0) ShopCreditLimit,
isnull(acm.creditlimit,0) HQCreditLimit ,DATEDIFF(dd,registerdate,GETDATE()) Age
from ashopCustomerdetails asd
left outer join aCustomerMaster acm   on asd.customerid =acm.customerid'
GO
/****** Object:  View [dbo].[vwServiceReplacements]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceReplacements]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by     : Kishore
-- Modified on     : 24/12/2003
-- Comments        : Added CurrencySymbol column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwServiceReplacements] AS
select bid.repinvdqty, bid.repinvdrate, isnull(los.sercallbkhno,'''')  serbookhno,
isnull(bk.serbookhid,'''') serbookhid,
isnull(bk.serbookhshopid,'''') serbookhshopid,
isnull(bk.serbookhcompanyid,'''') serbookhcompanyid,
isnull(cu.customername,'''') serinvhcustname, bi.serinvhid,
bi.serinvhcompanyid, serinvhcategid,
bi.serinvhshopid, serinvno, serinvhdate, isnull(sercallbkhdate,'''') serbookhdate,
isnull(sercallbkhslno,'''') serbookhslno, v.itemdescription,
serinvhprocno, serinvhprocdate, isnull(ai.brand,'''') brand,
ai.itemid, v.code,  cm.Symbol CurrencySymbol
from losserviceinvheader bi
left outer join acustomermaster cu
on bi.serinvhCustomerId = cu.customerid
and bi.serinvhcompanyid = cu.companyid
left outer join losserviceheader ls
on bi.serinvhjobcardid = ls.serinvhid
and ls.serinvhshopid = bi.serinvhshopid
and bi.serinvhcompanyid = ls.serinvhcompanyid left outer join losservicebookingheader bk
on bk.serbookhcompanyid = bi.serinvhcompanyid
and bk.serbookhshopid = bi.serinvhshopid
and bk.serbookhid = ls.serinvhbookingid  left outer join loscallbookingheader los
on los.serCallBkhid = serbookhrefid
and los.serCallBkhcompanyid = bk.serbookhcompanyid
and bk.serbookhshopid = los.serCallBkhshopid left outer join aCurrencyMaster cm
on cu.CurrencyId = cm.CurrencyId,
losinvoicedpartsreplacedetails bid, vwitemdescription v, aitem ai
where bi.serinvhid = bid.repinvinvoiceid
and bi.serinvhshopid = bid.repinvdshopid
and bi.serinvhcompanyid = bid.repinvcompanyid
and bid.repinvdpartsid = v.itemid
and bid.repinvdpartsid =  ai.itemid'
GO
/****** Object:  View [dbo].[vwServiceInvoicePostAmount]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoicePostAmount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwServiceInvoicePostAmount    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwServiceInvoicePostAmount]
as
select sum(ServiceQty*Amount) as amount, sum(ServiceQty*Amount)* exchangerate camount,
sum(ServiceQty*Amount) * depexrate damount, sd.invoiceid as invoiceid ,
sd.companyid as companyid from serviceinvoicedetails sd ,
accountsinvoiceheader ah where sd.invoiceid=ah.invoiceid and sd.companyid=ah.companyid
and ah.posted=0 and ah.cancelled=0 and ah.product=0 group by sd.invoiceid, sd.companyid,
exchangerate, depexrate'
GO
/****** Object:  View [dbo].[vwServiceInvoiceDetails]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoiceDetails]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on : 28/12/2002
--Modified by : dheena
--Comments : add depid
--Modified by : venki 020903
--Comments : corrected due period
--jyothish  03/06/2010
-- comment : Pono,RegNo fild is added
--Modified By Sreejith G A
--Modified on 14/06/2010
--Purpose : Added a new field DummyAdvance(AccountsInvoiceHeader)
--Modified By Sreejith G A
--Modified on 13/07/2010
--Purpose : Added a new field Details (AccountsInvoiceHeader)
/*
Modified By: Shine
ON: 22.09.2011
Commented: Added fields in select ("c.customerid,TaxAmount ")
*/
-----------------------------------------------------------------------------
--Modified By : Benzigar S D
--Modified On : 30/09/2011
--Comment     : Added isnull for tax amount
-----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwServiceInvoiceDetails] AS
select aih.companyid, aih.invoiceid, aih.invoiceno, aih.invoicedate, aih.referenceno,
aih.remarks, aih.posted, aih.proforma, case when aih.proforma =0 then ''Service Invoice''
when aih.proforma =1 then ''Proforma Service Invoice'' end as Header,
case when aih.cashinvoice =0 then ''Credit'' when aih.cashinvoice =1 then ''Cash'' end as Cashorcredit,
case when aih.cashinvoice =0 then c.currencyid when aih.cashinvoice =1 then acc.currencyid end as Transcurrencyid,
isnull(acc.accountdesc,''N/A'') as bankcashname, c.customername, isnull(aih.chequeno,''-'') as chequeno,
servicename, serviceterm ServiceTerms , serviceqty, (sd.amount ) serviceamt, dacc.accountdesc as discountacc,
aih.exchangerate, (discount ) as discount, cancelled, duedate,
c.address1, c.address2, c.address3, dm.departmentname,aih.DepartmentID deptid,
UpdateTime  ,Pono,RegNo ,DummyAdvance ,sd.remarks ServiceDetailRem,Details,c.customerid,isnull(aih.TaxAmount,0) as TaxAmount
from accountsinvoiceheader aih
left outer join aaccountmaster acc on aih.companyid = acc.companyid and
aih.bankcashid = acc.accountid
left outer join aaccountmaster dacc on aih.companyid = dacc.companyid and
aih.bankcashid = dacc.accountid
, acustomermaster c, serviceinvoicedetails sd, adepartmentmaster dm where
aih.companyid = dm.companyid and aih.departmentid = dm.departmentid and
aih.product=0 and aih.companyid = c.companyid and aih.customerid
= c.customerid and aih.invoiceid = sd.invoiceid and aih.companyid = sd.companyid'
GO
/****** Object:  View [dbo].[vwserviceinvoiceamt]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserviceinvoiceamt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwserviceinvoiceamt    Script Date: 18/01/2003 9:45:35 PM ******/
----Last Modified on  : 09/12/2002
----Modified by  : leo
----Comments  : v3
----Modified : Yogesh Joe--To deduct discount amount from the total amount
----Modified By :	Nidheesh P V
----Modified on :	16/08/2010
----Comments	  :	Included Tax amount
create view [dbo].[vwserviceinvoiceamt] as
select ah.companyid, ah.invoiceid, isnull(sum(serviceqty * amount),0)-Discount+isnull(TaxAmount,0) Amount from
accountsinvoiceheader ah left outer join serviceinvoicedetails sd  on
ah.invoiceid = sd.invoiceid and ah.companyid = sd.companyid
where ah.product=0 group by ah.companyid, ah.invoiceid,Discount,TaxAmount
----------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwrqtohqforitem]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrqtohqforitem]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwrqtohqforitem    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwrqtohqforitem    Script Date: 14/09/2002 12:48:06 AM ******/
/****** Object:  View dbo.vwrqtohqforitem    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwrqtohqforitem    Script Date: 20/11/2001 9:58:58 AM ******/
/****** Object:  View dbo.vwrqtohqforitem    Script Date: 17/11/2001 9:21:25 PM ******/
CREATE view [dbo].[vwrqtohqforitem] as
select ''G'' location, godownid locationid, requestid, itemcode, itemdescription, barcode,
unitid, packingtypeid, colorid, sizeid from meirqtohqforitem
union all
select ''S'' location, shopid locationid, requestid, itemcode, itemdescription, barcode,
unitid, packingtypeid, colorid, sizeid from mesrqtohqforitem'
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlights]    Script Date: 10/06/2012 14:17: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].[spDeleteFlights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
--Created on 	: 08/Oct/2010
--Created by	: Praveen S
--Comments	: For Deleting the Details of Flights
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spDeleteFlights]
@flghtopcompanyid INT,
@flghtid INT,
@flghtopid INT
AS BEGIN
	 SET NOCOUNT ON
	 DELETE FROM Flights
	 WHERE FlightOpid = @flghtopid AND FlightID = @flghtid AND companyid = @flghtopcompanyid
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlightOperator]    Script Date: 10/06/2012 14:17: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].[spDeleteFlightOperator]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[spDeleteFlightOperator]
@flghtopcompanyid INT,
@flghtopid INT
AS BEGIN
	 SET NOCOUNT ON
	 DELETE FROM  FlightOperatorMaster
	 WHERE FlghtOpid = @flghtopid AND companyid = @flghtopcompanyid
	 SET NOCOUNT OFF
	 DELETE FROM Flights
	 WHERE FlightOpid = @flghtopid AND companyid = @flghtopcompanyid
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDeletePOSDetail]    Script Date: 10/06/2012 14:17: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].[spDeletePOSDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------
--Created By : Aneesh
--Created On : 14-09-2006
--Purpose    : To delete details in the POS Detail Table [losPosDetail]
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spDeletePOSDetail]
@intBillId As Int,
@intShopId As Int
As
	Begin
		Delete From losPosDetail Where posdShopId=@intShopId
	And posdbillID=@intBillId
	End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetOutPut]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetOutPut]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified by 	: Hariharan
--Modified Date	: 20/03/2004
CREATE Proc [dbo].[spBalanceSheetOutPut] @strFromDate as varchar(10), @strToDate as varchar(10),
@intDepId as int as
Set nocount on
Begin
Declare @numAstAmount as numeric(28, 8),
	@numLiaAmount as numeric(28, 8),
	@numAstOpAmount as numeric(28, 8),
	@numLiaOpAmount as numeric(28, 8),
	@numIEDebAmount as numeric(28, 8),	
	@numIECredAmount as numeric(28, 8)
	Set @numAstAmount = 0.0
	set @numLiaAmount  = 0.0
	set @numAstOpAmount = 0.0
	set @numLiaOpAmount= 0.0
	set @numIEDebAmount = 0.0
	set @numIECredAmount= 0.0
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup Int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
insert #Tempjournalheader
	Select H.* from moajournalheader h (nolock) where journaldate>= @strFromDate
	and JournalDate <=@strToDate
	--for DEPARTMENT WISE
if @intDepId <>0
Begin
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
	Journaldate>=@strFromDate and
	JournalDate <=@strToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0
select @numAstAmount = isnull(sum(amount),0) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>= @strFromDate and journaldate <= @strToDate
and departmentid = @intdepid
and (g.accounttype=''a'' )
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numAstAmount = @numAstAmount  - isnull(sum(amount),0) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and departmentid = @intdepid
and (g.accounttype=''a'' )
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numLiaAmount = isnull(sum(amount),0) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and departmentid = @intdepid
and (g.accounttype=''l'' )
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numLiaAmount = @numLiaAmount - isnull(sum(amount),0) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and departmentid = @intdepid
and (g.accounttype=''l'' )
select @numAstOpAmount = isnull(sum(o.openingamount),0) from aAccountFinYearOpening o, aAccountmaster m,
aGroupMaster g where  o.AccountId = m.AccountId and
m.Groupid = g.GroupId and g.AccountType =''a''
and departmentid = @intDepId
select @numLiaOpAmount = isnull(sum(o.openingamount),0) from aAccountFinYearOpening o, aAccountmaster m,
aGroupMaster g where  o.AccountId = m.AccountId and
m.Groupid = g.GroupId and g.AccountType =''l''
and departmentid = @intDepId
select @numIECredAmount = sum(amount) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and departmentid = @intdepid
and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numIEDebAmount = sum(amount) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and departmentid = @intdepid
and (g.accounttype=''i'' or g.accounttype=''e'' )
Set  @numIECredAmount = isnull(@numIECredAmount,0) - isnull(@numIEDebAmount ,0)
Select departmentname from adepartmentmaster where departmentid = @intdepid
if  @numIECredAmount >0
	Select @numAstOpAmount + @numAstAmount ASSET, @numLiaOpAmount + @numLiaAmount + @numIECredAmount LIABILITY
else
	Select @numAstOpAmount + @numAstAmount - @numIECredAmount ASSET, @numLiaOpAmount + @numLiaAmount LIABILITY
End
	--for company consolidation
If @intDepId = 0
Begin
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
	Journaldate>=@strFromDate and
	JournalDate <=@strToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
select @numAstAmount = isnull(sum(amount),0) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>= @strFromDate and journaldate <= @strToDate
and (g.accounttype=''a'' ) and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numAstAmount = @numAstAmount  - isnull(sum(amount),0) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and (g.accounttype=''a'' ) and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numLiaAmount = isnull(sum(amount),0) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and (g.accounttype=''l'' ) and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
--and (g.accounttype=''i'' or g.accounttype=''e'' )
select @numLiaAmount = @numLiaAmount - isnull(sum(amount),0) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and (g.accounttype=''l'' ) and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
select @numAstOpAmount = isnull(sum(o.openingamount),0) from aAccountFinYearOpening o, aAccountmaster m,
aGroupMaster g where  o.AccountId = m.AccountId and
m.Groupid = g.GroupId and g.AccountType =''a''
and departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
select @numLiaOpAmount = isnull(sum(o.openingamount),0) from aAccountFinYearOpening o, aAccountmaster m,
aGroupMaster g where  o.AccountId = m.AccountId and
m.Groupid = g.GroupId and g.AccountType =''l''
and departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
select @numIECredAmount = sum(amount) from #vwJournalDetails d, #Tempjournalheader h, aAccountMaster a,
aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 1 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and (g.accounttype=''i'' or g.accounttype=''e'' )
and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
select @numIEDebAmount = sum(amount) from #vwJournalDetails d,
	#Tempjournalheader h, aAccountMaster a, aGroupMaster g where
d.journalid = h.JournalId and h.Companyid = d.companyid and h.cancel = 0 and
d.journalcredit = 0 and d.accountid = a.accountid and h.financialid > 0
and a.groupId = g.GroupId and a.companyid = g.companyid
and journaldate>=@strFromDate and journaldate <=@strToDate
and (g.accounttype=''i'' or g.accounttype=''e'' )
and d.departmentid in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
Set  @numIECredAmount = isnull(@numIECredAmount,0) - isnull(@numIEDebAmount ,0)
Select departmentname from adepartmentmaster where departmentid = @intdepid
if  @numIECredAmount >0
	Select isnull(@numAstOpAmount,0) + isnull(@numAstAmount,0) ASSET, isnull(@numLiaOpAmount,0) + isnull(@numLiaAmount,0) + isnull(@numIECredAmount,0) LIABILITY
else
	Select isnull(@numAstOpAmount,0) + isnull(@numAstAmount,0) - isnull(@numIECredAmount,0) ASSET, isnull(@numLiaOpAmount,0) + isnull(@numLiaAmount,0) LIABILITY
End
drop table #vwJournalDetails
drop table #Tempjournalheader
End
Set nocount OFf' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCheckAlertOnMergeComplete]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCheckAlertOnMergeComplete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------
-- Create Date   : 23/08/2003
-- Created in v3 : Kishore
--------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spCheckAlertOnMergeComplete] @intCompanyid as int
AS
Begin
	Declare @intShopId  as int,
	@intGodownId  as int,
	@IntShopCount  as int,
	@intGdnCount  as int,
	@intShopTrCount  as int,
	@intGdnTrCount  as int,
	@intMergeId as int,
	@intNOOfRec as int,
	@numStockCount as numeric(18,3),
	@intSuccessOrFailure as int
	Declare curCheckMerge cursor for
	select mghId from aHQMergingHeader
	where isnull(mghCostPriceFixed,'''') <>''c'' and isnull(mghCostPriceFixed,'''') <>''r'' and mghCancelled = 0 and mghTransfinished =1
	and mghCompanyID =  @intCompanyid
	open curCheckMerge
	Fetch Next from curCheckMerge into @intMergeId
	While @@Fetch_Status<>-1
	Begin
		
		Select @intGdnTrCount = count(*), @intNOOfRec=lghNOofrec from  LoiMergeHeader , LoiMergeDetails
		where lghId = lgdId and lghCompanyID = lgdCompanyId and lghGodownid = lgdGodownID
		and lghCancelled =0 and lghTransfinished = 1
		and lghRefMergeID = @intMergeId group by lghNOofrec, lghRefMergeID having count(*) = lghNoofRec
		Select @intShopTrCount = count(*) from  LosMergeHeader , LosMergeDetails
		where lshId = lsdId and lshCompanyID = lsdCompanyId and lshShopID = lsdShopID
		and lshCancelled =0 and lshTransfinished = 1 and lshRefMergeID = @intMergeId
		group by lshNOofrec, lshRefMergeID having count(*) = lshNoofRec
		if @intNoofRec is null
			set @intNOofRec = 1
		select @IntShopCount = count(*) from ashops where companyId = @intCompanyID
		select @intGdnCount = count(*) from aGodown where companyId = @intCompanyID
		set @intShopTrCount = @intShopTrCount/@intNOofRec
		set @intGdnTrCount  = @intGdnTrCount/@intNOofRec
		if @IntShopCount = @intShopTrCount and @intGdnCount = @intGdnTrCount
		begin			
			update aHQMergingHeader set mghCostPriceFIxed = ''r'' where mghId = @intMergeId and
			mghCompanyID = @intCompanyID
		end
		else
		Begin
			set @intSuccessOrFailure  =1
			--CHECKING GODOWN WISE DATA-------------------------------------------------------------
			Declare CurCheckGdnStock Cursor for
			Select  godownid from aGodown where CompanyID = @IntCompanyID
			Open CurCheckGdnStock
			Fetch next from CurCheckGdnStock  into @intGodownID
			while @@Fetch_Status <>-1
			Begin
				Set @intGdnTrCount = 0
	
				Select @intGdnTrCount = count(*) from  LoiMergeHeader,
				LoiMergeDetails where lghId = lgdId and lghCompanyID = lgdCompanyId
				and lghCancelled = 0 and lghTransfinished = 1 and lghRefMergeID = @intMergeId
				and lghGodownid = lgdGodownID and lghGodownID = @intGodownID group by lghNOofrec, lgdID
				 having count(*) = lghNoofRec	
				if @intGdnTrCount = 0
				Begin
					set @numStockCount = 0.0
					Select @numStockCount = isnull(sum(isnull(gsStock,0)),0) from MoiGodownStock,
					AHQMergingHeader where gsGodownId =  @intGodownID and
					gsItemID = mghItemID and mghID = @intMergeId
					
					Select @numStockCount = @numStockCount + isnull(sum(isnull(gsStock,0)),0) from
					MoiGodownStock, AHQMergingDetails where gsGodownId =  @intGodownID and 	
					gsItemID = mgdItemID and mgdID = @intMergeId
					if @numStockCount >0
						Begin
							Set @intSuccessOrFailure = 0
							Break
						End
					if @intSuccessOrFailure = 0
						Break								
				End
			Fetch next from CurCheckGdnStock into @intGodownID
			End
			close CurCheckGdnStock
			deallocate CurCheckGdnStock 			
			--CHECKING GODOWN WISE DATA-------------------------------------------------------------			
			if @intSuccessOrFailure = 1
			Begin
				--CHECKING SHOP WISE DATA-------------------------------------------------------------
				Declare CurCheckShopStock Cursor for
				Select  ShopId from aShops where CompanyID = @IntCompanyID
				Open CurCheckShopStock
				Fetch next from CurCheckShopStock into @intShopID
				while @@Fetch_Status <>-1
				Begin
					Set @intShopTrCount = 0
--					print ''Entered in Shop Section''
					Select @intShopTrCount = count(*) from  LosMergeHeader,
					LosMergeDetails where lshId = lsdId and lshCompanyID = lsdCompanyId
					and lshSHopid = lsdShopID
					and lshCancelled = 0 and lshTransfinished = 1 and lshRefMergeID = @intMergeId
					and lshShopID = @intShopID group by lshNOofrec, lsdID having count(*) = lshNoofRec	
					
					if @intShopTrCount = 0
					Begin	
						set @numStockCount = 0.0
						Select @numStockCount = isnull(sum(isnull(stock,0)),0) from
						mosShopStock, AHQMergingHeader where ShopID =  @IntShopID and
						ItemID = mghItemID and mghID = @intMergeId
					
						Select @numStockCount = @numStockCount + isnull(sum(isnull(Stock,0)),0)
						from mosShopStock, AHQMergingDetails where ShopID =  @intShopID and 	
						ItemID = mgdItemID and mgdId = @intMergeId
--						print @numStockCount
						if @numStockCount >0
							Begin
								Set @intSuccessOrFailure = 0
								Break
							End
																
					End
					if @intSuccessOrFailure = 0
						Break
				Fetch next from CurCheckShopStock into @intShopID
				End			
				close CurCheckShopStock
				deallocate CurCheckShopStock
				
			End
			if @intSuccessOrFailure =1
				update aHQMergingHeader set mghCostPriceFIxed = ''r'' where mghId = @intMergeId and
				mghCompanyID = @intCompanyID
		End
	Fetch Next from curCheckMerge into @intMergeId
	End
	
	Close curCheckMerge
	DeAllocate curCheckMerge
end
---------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCFUserFormat]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCFUserFormat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on         : 09/06/2004
-- Created by         : Hariharan R
-- Comments           : Taken from v2 and then modified. Cash flow report generated depending
--		      :	on User Format Created
-- Comments           : Accountid taken from the table :-aRepFormatAccounts,
--		      : increased field size for repGroupname field
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/*
EXEC spCFUserFormat ''20100520'',1,1,14,1,1
*/
CREATE PROCEDURE [dbo].[spCFUserFormat] (@strToDate as varchar(10),
@intCompanyID as int,
@intformatid as int,
@intDepartmentId as int = 0, @intconsolidation  as int=0, @BitCons as int=0) as
Begin
set nocount on
Declare @AcCode as varchar(50),
	@AcID as int,
	@AccDesc as varchar(100),
	@AcType as varchar(1),
	@GroupDesc as varchar(50),
	@GroupID as int,
	@CompanyName as varchar(100),
	@dtFROMDate as datetime,
	@dtToDate as datetime,
	@strfromdate as varchar(12),
	@intrepgroupid as int,
	@striscaption as varchar(5),
	@intparentgroupid as int,
	@strrepgroupname as varchar(50),
	@strnote as varchar(50),
	@intcolwidth as int,
	@intdorder as int,
	@strpartcode as varchar(5),	--hari inserted
@bitInflow as bit,
@bitInflowValue as bit,
	@intFinId as int,
	@dtLastFinUnclosedEDate datetime,
	@intLastFinId as int,
	@dtPrevFinUnclosedSDate as datetime
	
Create table #Tempjournalheader
	(JournalID	int,
	CompanyID	int,
	JournalDate	smalldatetime,
--	ReferenceNo	varchar(100),
--	Remarks	varchar(250),
--	Type	char(10),
ReferenceNo	varchar(50),
Remarks	varchar(1000),
Type	varchar(10),
	Cancel	bit,
	Realised	bit,
	CurrencyId	int,
	FinancialID	int,
	chequedate	datetime,
	updatetime	datetime,
	bankdate	datetime)
Create table #vwJournalDetails
(companyid      int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	        numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup       int)
Create table #CashFlow(
	CompanyID int,
	DepartmentId int,
	DepartmentName varchar(100),	
	accountid int,
	AccCode varchar(50),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	Debit numeric(18,2),
	Credit numeric(18,2),
	OpDebit numeric(18,2),
	OpCredit Numeric(18,2),
	OpBal numeric(18,2),
	reportgroupid int,
	tmonth int,
	amount numeric(18,2),
	ParentGroupID int,
	iscaption varchar(5),
	repgroupname varchar(100),
	note varchar(50),
	dorder int,
	InFlow int,
	PrevOpDebit numeric(18,2),
	PrevOpCredit Numeric(18,2),
	PrevDebit numeric(18,2),
	PrevCredit Numeric(18,2),
	PrevOpBal numeric(18,2))
	-- get the partion char
	select @strpartcode = partionchar
from aAccRepFormat
where companyid = @intcompanyid
and formatid = @intformatid
and type = ''c''    -- c mean cash flow
	set @strpartcode = ''%''+ rtrim(ltrim(@strpartcode)) + ''%''
	-- create the temporary table to insert sub departments
	-- table name is given as #SubDepts1 to avoid conflicts
	-- with #SubDepts inside the sp
	create table #SubDepts1(DeptId int)
	 if @intconsolidation=0
	    insert into #SubDepts1 values(@intDepartmentId)
	 else
	    -- get the sub depts into the temporary table
	insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
	-- convert the @strToDate to DateTime field
SELECT @dtToDate = convert(datetime, @strToDate, 101)
	-- get the start date of financial year
	Select @intFinId = financialid, @dtFromDate = sdate,
	@strfromdate = convert(varchar, sdate, 112) from vwfinyearperiod
where convert(datetime, @strToDate, 101) between sdate and edate
	if @intFinId >1
	Begin
		Set @intFinId = @intFinId - 1
	End
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId		
	insert #Tempjournalheader
	Select H.* from MoajournalHeader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate
	and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
	if @intDepartmentId = 0
	begin
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
	JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
	h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
	h.CompanyId = @intCompanyId 	
	end
	else
	begin
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
	JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
	h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
	h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)
	end
	if @intdepartmentid > 0
		insert into #CashFlow(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,
		AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit,
		reportgroupid, tmonth , amount, ParentGroupID, iscaption, repgroupname, note,
		dorder, InFlow, PrevOpDebit , PrevOpCredit , PrevDebit , PrevCredit , PrevOpBal)	
		-- Query added by venkitesh on 130504
		Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,
		a.AccountDesc, 	g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,
		0, 0, gr.Groupid, null, 0,  isnull(ParentGroupID,0) ParentGroupID,gr.iscaption,
		gr.groupname, gr.groupcode, gr.displayorderid,	gr.Inflow, 0, 0, 0, 0, 0
		From aaccrepformat accFor,aAccRepGroup gr
		left outer Join
		(select a.companyid, a.accountcode,a.accountdesc,a.accountid,b.formatid,
		b.groupid RepGroupId, a.GroupId from
		aAccountMaster a, aRepFormatAccounts b
		 where a.accountid=b.accountid and a.companyid=b.companyid  )
		 a on gr.CompanyId = a.CompanyId
		 and @intCompanyID = a.CompanyId  and  gr.groupid = a.repgroupid and
		gr.formatid=a.formatid
	  	 LEFT outer join aGroupMaster g on a.GroupId = g.GroupID and
			a.CompanyId = g.CompanyId,
	 	 aDepartmentMaster m where gr.companyid = m.companyid and
		 gr.FormatId =accfor.formatid  and gr.companyid=accfor.companyid
		 and accfor.departmentid=m.departmentid and gr.formatid= @intformatid	
	else
		insert into #CashFlow(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,
		AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit,
		reportgroupid, tmonth , amount, ParentGroupID, iscaption, repgroupname, note,
		dorder, InFlow, PrevOpDebit , PrevOpCredit , PrevDebit , PrevCredit , PrevOpBal)	
		-- Query added by venkitesh on 130504
		Select a.CompanyId,daDepartmentId, Null, a.AccountId, a.AccountCode,
		a.AccountDesc, 	g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,
		0, 0, gr.Groupid, null, 0,  isnull(ParentGroupID,0) ParentGroupID,gr.iscaption,
		gr.groupname, gr.groupcode, gr.displayorderid,	gr.Inflow, 0, 0, 0, 0, 0
		From aaccrepformat accFor,aAccRepGroup gr
		left outer Join
		(select a.companyid, a.accountcode,a.accountdesc,a.accountid,b.formatid,
		b.groupid RepgroupId, a.Groupid from aAccountMaster a, aRepFormatAccounts b
		 where a.accountid=b.accountid and a.companyid=b.companyid  )
		 a on gr.CompanyId = a.CompanyId
		 and a.CompanyId = @intCompanyID and  gr.groupid =a.repgroupid and
		gr.formatid=a.formatid
	  	 LEFT outer join aGroupMaster g on a.GroupId = g.GroupID and
			a.CompanyId = g.CompanyId
		left outer join aDeptAccounts da on a.accountid = da.daaccountid
		and a.companyid = da.dacompanyid where gr.FormatId =accfor.formatid and
		gr.companyid=accfor.companyid and gr.formatid= @intformatid	
	-- get the start date of financial year
	Select @intFinId = financialid, @dtFromDate = sdate,
	@strfromdate = convert(varchar, sdate, 112) from vwfinyearperiod
where convert(datetime, @strToDate, 101) between sdate and edate
	select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	Update #CashFlow set OpBal = opening.Openingamount from (Select AccountId,
	DepartmentId, CompanyId, case when @BitCons = 1 then Openingamount else
	OpeningDepamount end Openingamount from aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #CashFlow.AccountId and
	opening.DepartmentId = #CashFlow.DepartmentId
	and opening.CompanyId = #CashFlow.CompanyID and opening.CompanyId = @intCompanyId
	Update #CashFlow set OpDebit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #CashFlow set OpCredit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v , #Tempjournalheader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #CashFlow set Debit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #CashFlow set Credit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Set @intFinId = @intFinId - 1
	if @intFinId >0 --FOR TAKING PREVIOUS YEAR CASH FLOW
	Begin
	-- get the start date of financial year
	Select @dtFromDate = sdate, @strfromdate = convert(varchar, sdate, 112),
	@dtToDate = edate from
	vwfinyearperiod where Financialid = @intFinId and CompanyID = @intCompanyID
	select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	/*Update #CashFlow set PrevOpBal = opening.Openingamount from (Select AccountId,
	DepartmentId, CompanyId, case when @BitCons = 1 then Openingamount else
	OpeningDepamount end Openingamount from aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #CashFlow.AccountId and
	opening.DepartmentId = #CashFlow.DepartmentId
	and opening.CompanyId = #CashFlow.CompanyID and opening.CompanyId = @intCompanyId
	Update #CashFlow set PrevOpDebit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #CashFlow set PrevOpCredit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v , #Tempjournalheader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId */
	Update #CashFlow set PrevDebit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #CashFlow set PrevCredit = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case when @BitCons = 1 then
	Sum(isnull(v.Amount,0)) else Sum(isnull(v.DepAmount,0)) end Amount From
	#vwJournalDetails v, #Tempjournalheader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #CashFlow.AccountId and
	trialDeb.DepartmentId = #CashFlow.DepartmentId
	and trialDeb.CompanyId = #CashFlow.CompanyID and trialDeb.CompanyId = @intCompanyId		
	End
	Delete  from #CashFlow from (Select accountid, Departmentid from #CashFlow
	where accountid is not null
	group by accountid, departmentid having sum(debit) = 0 and sum(credit) = 0 and
	sum(OpDebit) = 0 and sum(OpCredit)=0 and
	sum(OpBal)=0 ) chk where #CashFlow.accountid = chk.accountid and
	#CashFlow.departmentid = chk.departmentid
	if @intDepartmentId > 0
	Begin
	select ''d'' as summary, CompanyID, dorder, repgroupname, departmentname, tmonth, accdesc,
	max(accountid) acid, max(AccCode) acccode, max(AcType) actype, max(GroupID) groupid,
	max(GroupName) groupname,  max(note) note, max(iscaption) iscaption,
	sum(isnull(amount,0)) amount, max(ParentGroupID) parentgroupid,
	max(reportgroupid) reportgroupid,
	case AcType  when ''A'' then (isnull(OPBal,0)  + isnull(OPDebit,0) - isnull(OpCredit,0) + isnull(debit,0) - isnull(credit,0))
	when ''L'' then (isnull(OPBal,0)  + isnull(OpCredit,0) -  isnull(OPDebit,0) + isnull(Credit,0) - isnull(Debit,0))
	when ''E'' then (isnull(OPBal,0)  + isnull(OPDebit,0) - isnull(OpCredit,0) + isnull(Debit,0) - isnull(Credit,0))
	when ''I'' then (isnull(OPBal,0)  + isnull(OpCredit,0) -  isnull(OPDebit,0) + isnull(Credit,0) - isnull(Debit,0)) end Closing,
	OpBal Opening, InFlow,
	case when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (isnull(debit,0) - isnull(credit,0)) >0)
	then isnull(debit,0) - isnull(credit,0)
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (isnull(debit,0) - isnull(credit,0)) >0)
	then -(isnull(debit,0) - isnull(credit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and ( isnull(debit,0) - isnull(credit,0)) <0)
	then ( isnull(debit,0) - isnull(credit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (isnull(debit,0) - isnull(credit,0)) <0)
	then -( isnull(debit,0) - isnull(credit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (isnull(credit,0) - isnull(debit,0)) >0)
	then isnull(credit,0) - isnull(debit,0)
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (isnull(credit,0) - isnull(debit,0)) >0)
	then -(isnull(credit,0) - isnull(debit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (isnull(credit,0) - isnull(debit,0)) <0)
	then (isnull(credit,0) - isnull(debit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (isnull(credit,0) - isnull(debit,0)) <0)
	then -(isnull(credit,0) - isnull(debit,0))
	else 0 End CashFlow, isnull(OpCredit,0) opcr, isnull(OPDebit,0) opdr,
	isnull(credit,0) cr, isnull(debit,0) dr, InFlow, (isnull(credit,0) - isnull(debit,0)) bal,
	case when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (isnull(Prevdebit,0) - isnull(Prevcredit,0)) >0)
	then isnull(Prevdebit,0) - isnull(Prevcredit,0)
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (isnull(Prevdebit,0) - isnull(Prevcredit,0)) >0)
	then -(isnull(Prevdebit,0) - isnull(Prevcredit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (isnull(Prevdebit,0) - isnull(Prevcredit,0)) <0)
	then (isnull(Prevdebit,0) - isnull(Prevcredit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (isnull(Prevdebit,0) - isnull(Prevcredit,0)) <0)
	then -(isnull(Prevdebit,0) - isnull(Prevcredit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (isnull(Prevcredit,0) - isnull(Prevdebit,0)) >0)
	then isnull(Prevcredit,0) - isnull(Prevdebit,0)
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (isnull(Prevcredit,0) - isnull(Prevdebit,0)) >0)
	then -(isnull(Prevcredit,0) - isnull(Prevdebit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (isnull(Prevcredit,0) - isnull(Prevdebit,0)) <0)
	then (isnull(Prevcredit,0) - isnull(Prevdebit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and ( isnull(Prevcredit,0) - isnull(Prevdebit,0)) <0)
	then -(isnull(Prevcredit,0) - isnull(Prevdebit,0))
	else 0 End PrevCashFlow
	from #CashFlow where (DepartmentId = (Select DeptId from #SubDepts1)
	or DepartmentId is null)
	group by companyid, dorder,repgroupname, departmentname,tmonth,
	accdesc, OPBal, OpCredit, OPDebit, Credit, Debit, AcType, InFlow,
	PrevOpDebit , PrevOpCredit , PrevDebit , PrevCredit , PrevOpBal
	End
	else
	Begin
	select ''d'' as summary, CompanyID, dorder, repgroupname,null, tmonth, accdesc,
	max(accountid) acid, max(AccCode) acccode, max(AcType) actype, max(GroupID) groupid,
	max(GroupName) groupname,  max(note) note, max(iscaption) iscaption,
	sum(isnull(amount,0)) amount, max(ParentGroupID) parentgroupid,
	max(reportgroupid) reportgroupid,
	case AcType  when ''A'' then (sum(isnull(OPBal,0))  + sum(isnull(OPDebit,0)) - sum(isnull(OpCredit,0)) + sum(isnull(debit,0)) - sum(isnull(credit,0)))
	when ''L'' then (sum(isnull(OPBal,0))  + sum(isnull(OpCredit,0)) -  sum(isnull(OPDebit,0)) + sum(isnull(Credit,0)) - sum(isnull(Debit,0)))
	when ''E'' then (sum(isnull(OPBal,0))  + sum(isnull(OPDebit,0)) - sum(isnull(OpCredit,0)) + sum(isnull(Debit,0)) - sum(isnull(Credit,0)))
	when ''I'' then (sum(isnull(OPBal,0))  + sum(isnull(OpCredit,0)) -  sum(isnull(OPDebit,0)) + sum(isnull(Credit,0)) - sum(isnull(Debit,0))) end Closing,
	OpBal Opening, InFlow,
	case when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (sum(isnull(debit,0)) - sum(isnull(credit,0))) >0)
	then sum(isnull(debit,0)) - sum(isnull(credit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (sum(isnull(debit,0)) - sum(isnull(credit,0))) >0)
	then -(sum(isnull(debit,0)) - sum(isnull(credit,0)))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (sum(isnull(debit,0)) - sum(isnull(credit,0))) <0)
	then (sum(isnull(debit,0)) - sum(isnull(credit,0)))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (sum(isnull(debit,0)) - sum(isnull(credit,0))) <0)
	then -(sum(isnull(debit,0)) - sum(isnull(credit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (sum(isnull(credit,0)) - sum(isnull(debit,0))) >0)
	then sum(isnull(credit,0)) - sum(isnull(debit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (sum(isnull(credit,0)) - sum(isnull(debit,0))) >0)
	then -(sum(isnull(credit,0)) - sum(isnull(debit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (sum(isnull(credit,0)) - sum(isnull(debit,0))) <0)
	then (sum(isnull(credit,0)) - sum(isnull(debit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (sum(isnull(credit,0)) - sum(isnull(debit,0))) <0)
	then -(sum(isnull(credit,0)) - sum(isnull(debit,0)))
	else 0 End CashFlow, sum(isnull(OpCredit,0)) opcr, sum(isnull(OPDebit,0)) opdr,
	sum(isnull(credit,0)) cr, sum(isnull(debit,0)) dr, InFlow,
	(sum(isnull(credit,0)) - sum(isnull(debit,0))) bal,
	case when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0))) >0)
	then sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0))) >0)
	then -(sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0)))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 1 and (sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0))) <0)
	then (sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0)))
	when ((AcType = ''A'' or AcType = ''E'') and  InFlow = 0 and (sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0))) <0)
	then -(sum(isnull(Prevdebit,0)) - sum(isnull(Prevcredit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0))) >0)
	then sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0))) >0)
	then -(sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 1 and (sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0))) <0)
	then (sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0)))
	when ((AcType = ''L'' or AcType = ''I'') and  InFlow = 0 and (sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0))) <0)
	then -(sum(isnull(Prevcredit,0)) - sum(isnull(Prevdebit,0)))
	else 0 End PrevCashFlow
	from #CashFlow
	group by companyid, dorder,repgroupname,tmonth,
	accdesc, OPBal, OpCredit, OPDebit, Credit, Debit, AcType, InFlow ,
	PrevOpDebit , PrevOpCredit , PrevDebit , PrevCredit , PrevOpBal
	End
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpCashFlowSummary]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpCashFlowSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---exec  SpCashFlowSummary 1,4,''20070101'',''20080401''
---Created by  : Prasanth Joseph  ,Ref : Rajesh Kamalakshan(PM), Shinu Vaman(PL)
---Created on  : 26-04-2007
---Create dFor
CREATE proc [dbo].[SpCashFlowSummary] @intCompanyId as int,@strStartDate as varchar(10),@strEndDate as varchar(10),@intDepartmentID as int as
	begin
	declare @dtFromdate as datetime,
			@dtTodate as datetime,
			@dtFinYearFromdate as datetime,
			@intcashgroupid as int,
			@intbankgroupid as int
	set @dtFromdate=convert(datetime,@strStartDate)
	set @dtTodate=convert(datetime,@strEndDate)
SELECT @intcashgroupid=CashGroupID
		  ,@intbankgroupid=BankGroupID
	FROM aSettings where CompanyID=@intCompanyId
-----------Finidng the start day of the current Financila year
	select @dtFinYearFromdate=convert(datetime, convert(char(4),startyear)+case len(startmonth) when 1 then ''0''+convert(char(1) ,startmonth) when 2 then convert(char(2) ,startmonth) end +''01'' )
	from afinancialyear where companyid=@intCompanyId and curfinancialyear=1
-----------Finding the cash flow summary part
	---------------Cash Balance at End of Period---------------------------------------------------------------------------------------------------------------------------
if @intDepartmentID=0
begin
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,''A-Summary'' as cashflowgroup from (
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,0 Balance,isnull(sum(Debit),0) -isnull(sum(Credit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid) -- --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFinYearFromdate and @dtTodate and journalheader.cancel=0 and journalheader.financialid>0
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid)CCC group by groupid
union all
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,isnull(sum(Debit),0) -isnull(sum(Credit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12 --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFromdate and @dtTodate and journalheader.cancel=0 and journalheader.financialid>0
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
	)CCC group by groupid
union all
	--select accountid,caption,groupid,sum(balance) balance,sum(balance) YeartodateBalance from(
	select 0 as accountid,''Cash Balance at End of Period'' as caption,accountmaster.groupid,amount balance,amount YeartodateBalance
	from CashFlowOpenings,aGroupMaster GroupMaster
	left outer join aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12
	where
	CashFlowOpenings.accountid=accountmaster.accountid and CashFlowOpenings.companyid=@intCompanyId
	and CashFlowOpenings.financialyearid=1 and GroupMaster.companyid=@intCompanyId and GroupMaster.groupid=accountmaster.groupid--)ff group by accountid,caption,groupid
	)dd group by groupid
union all
-----------finding Cash Balance at Begining of Period----------------------------------------------------------------------------------------------------
	
	select  0 as accountid,''Cash Balance at Begining of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,''A-Summary'' as cashflowgroup from (
	select  0 as accountid,''Cash Balance at Begining of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,0 Balance,isnull(sum(Debit),0) -isnull(sum(Credit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12 --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFinYearFromdate and @strEndDate and journalheader.cancel=0 and journalheader.financialid>0
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid)CCC group by groupid
	union all
	select 0 as accountid,''Cash Balance at Begining of Period'' as caption,accountmaster.groupid,amount balance,amount YeartodateBalance
	from CashFlowOpenings,aGroupMaster GroupMaster
	left outer join aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)
	where
	CashFlowOpenings.accountid=accountmaster.accountid and CashFlowOpenings.companyid=@intCompanyId
	and CashFlowOpenings.financialyearid=1 and GroupMaster.companyid=@intCompanyId and GroupMaster.groupid=accountmaster.groupid--)ff group by accountid,caption,groupid
	)dd group by groupid
end
else
begin
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,''A-Summary'' as cashflowgroup from (
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,0 Balance,isnull(sum(Debit),0) -isnull(sum(Credit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid) -- --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFinYearFromdate and @dtTodate and journalheader.cancel=0 and journalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid)CCC group by groupid
union all
	select  0 as accountid,''Cash Balance at End of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,isnull(sum(Debit),0) -isnull(sum(Credit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12 --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFromdate and @dtTodate and journalheader.cancel=0 and journalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
	)CCC group by groupid
union all
	--select accountid,caption,groupid,sum(balance) balance,sum(balance) YeartodateBalance from(
	select 0 as accountid,''Cash Balance at End of Period'' as caption,accountmaster.groupid,amount balance,amount YeartodateBalance
	from CashFlowOpenings,aGroupMaster GroupMaster
	left outer join aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12
	where
	CashFlowOpenings.accountid=accountmaster.accountid and CashFlowOpenings.companyid=@intCompanyId
	and CashFlowOpenings.financialyearid=1 and GroupMaster.companyid=@intCompanyId and GroupMaster.groupid=accountmaster.groupid--)ff group by accountid,caption,groupid
	)dd group by groupid
union all
-----------finding Cash Balance at Begining of Period----------------------------------------------------------------------------------------------------
	
	select  0 as accountid,''Cash Balance at Begining of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,''A-Summary'' as cashflowgroup from (
	select  0 as accountid,''Cash Balance at Begining of Period'' as accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
	select accountid,accountdesc,groupid,0 Balance,isnull(sum(Debit),0) -isnull(sum(Credit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
	from
	(
	select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
	case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
	from vwJournalDetails ,moajournalheader journalheader
	left outer join  aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)--=12 --and accountmaster.accountid not in(22,47)
	where vwJournalDetails.accountid=accountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=journalheader.journalid
	and journalheader.journaldate between @dtFinYearFromdate and @strEndDate and journalheader.cancel=0 and journalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
	group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid)CCC group by groupid
	union all
	select 0 as accountid,''Cash Balance at Begining of Period'' as caption,accountmaster.groupid,amount balance,amount YeartodateBalance
	from CashFlowOpenings,aGroupMaster GroupMaster
	left outer join aaccountmaster accountmaster on accountmaster.groupid in(@intcashgroupid,@intbankgroupid)
	where
	CashFlowOpenings.accountid=accountmaster.accountid and CashFlowOpenings.companyid=@intCompanyId
	and CashFlowOpenings.financialyearid=1 and GroupMaster.companyid=@intCompanyId and GroupMaster.groupid=accountmaster.groupid--)ff group by accountid,caption,groupid
	)dd group by groupid
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpCashFlowStatement1]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpCashFlowStatement1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---exec SpCashFlowStatement1 1,4,''20070101'',''20080301''
---Created on  : 17/03/2008
---Created BY  :  Prasanth Joseph ,Ref: Rajesh Kamalakshan,Shinu Vaman
---Modified by :
---Modified on :
CREATE  proc [dbo].[SpCashFlowStatement1] @intCompanyId as int,@strStartDate as varchar(10),@strEndDate as varchar(10),@intDepartmentID as int as
begin
declare @dtFromdate as datetime,
@dtTodate as datetime,
@dtFinYearFromdate as datetime,
@intCurrassetid as int,
@intCurrliabiltyId as int,
@intGroupcount as int,
@GroupID as int,
@strsql as varchar(2000),
@parentgroupid as int,
@parentgroupidquerry as int,
@intfixedassetid as int,
@intshareCapitalid as int,
@intcashgroupid as int,
@intbankgroupid as int,
@cashflowgroup as varchar(3)
set @dtFromdate=convert(datetime,@strStartDate)
set @dtTodate=convert(datetime,@strEndDate)
---------------Finding the Group and Account Heads
SELECT @intfixedassetid=FixedAssetGroupID
,@intcashgroupid=CashGroupID
,@intbankgroupid=BankGroupID
,@intCurrassetid=CurrentAssetGroupId
,@intCurrliabiltyId=CurrentLiabilityGroupId
,@intshareCapitalid=CurrentShareCapitalGroupId
FROM aSettings where CompanyID=@intCompanyId
-----------------------------------------------------------
-----------Finidng the start day of the current Financila year
select @dtFinYearFromdate=convert(datetime, convert(char(4),startyear)+case len(startmonth) when 1 then ''0''+convert(char(1) ,startmonth) when 2 then convert(char(2) ,startmonth) end +''01'' )
from afinancialyear where companyid=@intCompanyId and curfinancialyear=1
create table #tempCashflowgroups(
groupid  int,
cashflowgroup  varchar(5))
declare grouopcursur cursor for select distinct GroupMaster.groupid  from aaccountmaster acc
left outer join aGroupMaster GroupMaster  on acc.groupid=GroupMaster.groupid
and GroupMaster.companyid=acc.companyid
where acc.companyid=@intCompanyId
open grouopcursur
fetch next from grouopcursur
into @GroupID
-----------grouping the above groups as per cash flow format
while @@fetch_status=0
begin
set @parentgroupid=0
set @cashflowgroup=''''
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@GroupID
set @parentgroupidquerry=@parentgroupid
if(@parentgroupid<>0)
begin
-----------for Current asset and Liability(OA ---Operational Activity)
if(@parentgroupid=@intCurrassetid or @parentgroupid=@intCurrliabiltyId)
begin
set @cashflowgroup=''OA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intCurrassetid or @parentgroupid=@intCurrliabiltyId)
begin
set @cashflowgroup=''OA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intCurrassetid or @parentgroupid=@intCurrliabiltyId)
begin
set @cashflowgroup=''OA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intCurrassetid or @parentgroupid=@intCurrliabiltyId)
begin
set @cashflowgroup=''OA''
end
end
end
end
-----------for current Sharecapital(FA ---Financing Activity)
print @parentgroupid
set @parentgroupid=@parentgroupidquerry
if(@parentgroupid=@intshareCapitalid and @cashflowgroup='''')
begin
set @cashflowgroup=''FA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intshareCapitalid)
begin
set @cashflowgroup=''FA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intshareCapitalid)
begin
set @cashflowgroup=''FA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intshareCapitalid)
begin
set @cashflowgroup=''FA''
end
end
end
end
-----------for current Fixed Asset(IA ---Investment Activity)
print @parentgroupid
set @parentgroupid=@parentgroupidquerry
if(@parentgroupid=@intfixedassetid and @cashflowgroup='''')
begin
set @cashflowgroup=''IA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intfixedassetid)
begin
set @cashflowgroup=''IA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intfixedassetid)
begin
set @cashflowgroup=''IA''
end
else
begin
select @parentgroupid=isnull(parentgroupid,0) from aGroupMaster where groupid=@parentgroupid
if(@parentgroupid=@intfixedassetid)
begin
set @cashflowgroup=''IA''
end
end
end
end
end
else
begin
if(@GroupID=@intfixedassetid)
begin
set @cashflowgroup=''IA''
end
else if(@GroupID=@intCurrassetid or @GroupID=@intCurrliabiltyId)
begin
set @cashflowgroup=''OA''
end
else if(@GroupID=@intshareCapitalid)
begin
set @cashflowgroup=''FA''
end
end
insert into #tempCashflowgroups values(@GroupID,@cashflowgroup)
fetch next from grouopcursur into @GroupID
end
close grouopcursur
deallocate grouopcursur
create table #Cashflow(
accountid  int,
Accountdesc  varchar(100),
groupid  int,
balance numeric(18,2),
yeartodatebalance numeric(18,2),
cashflowgroup  varchar(3))
-----------Finding the balance in each cash flow group accounts
declare Cashflowaccountscursor cursor for select groupid,cashflowgroup from #tempCashflowgroups where cashflowgroup<>'''' and groupid not in (@intcashgroupid,@intbankgroupid)
open Cashflowaccountscursor
fetch next from Cashflowaccountscursor
into @groupid,@cashflowgroup
while @@fetch_status=0
begin
if @intDepartmentID=0
begin
insert into #Cashflow
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,@cashflowgroup from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
from vwJournalDetails ,moajournalheader
left outer join  aaccountmaster on aaccountmaster.groupid=@groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
union all
select CashFlowOpenings.accountid,ac.accountdesc,ac.groupid,0 balance,amount YeartodateBalance
from CashFlowOpenings
left outer join aaccountmaster ac on ac.groupid=@groupid
where
CashFlowOpenings.accountid=ac.accountid and CashFlowOpenings.companyid=@intCompanyId
and CashFlowOpenings.financialyearid=1
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
from vwJournalDetails ,moajournalheader
left outer join  aaccountmaster on aaccountmaster.groupid=@groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid
end
else
begin
insert into #Cashflow
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance,@cashflowgroup from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
from vwJournalDetails ,moajournalheader
left outer join  aaccountmaster on aaccountmaster.groupid=@groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
union all
select CashFlowOpenings.accountid,ac.accountdesc,ac.groupid,0 balance,amount YeartodateBalance
from CashFlowOpenings
left outer join aaccountmaster ac on ac.groupid=@groupid
where
CashFlowOpenings.accountid=ac.accountid and CashFlowOpenings.companyid=@intCompanyId
and CashFlowOpenings.financialyearid=1
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,groupid
from vwJournalDetails ,moajournalheader
left outer join  aaccountmaster on aaccountmaster.groupid=@groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
group by journalcredit,vwJournalDetails.accountid,accountdesc,groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid
end
fetch next from Cashflowaccountscursor into @groupid,@cashflowgroup
end
close Cashflowaccountscursor
deallocate Cashflowaccountscursor
if @intDepartmentid=0
begin
select accountid,Accountdesc,groupid,balance,yeartodatebalance,cashflowgroup from #Cashflow --order by cashflowgroup desc
-----------Adding the net income part-----------------------------------------------------------------------------------
union all
select 0 as accountid,''Net Income'' as Accountdesc,0 as groupid,sum(Balance) as balance,sum(YeartodateBalance) as yeartodatebalance,''Z-income'' as cashflowgroup from (
select sum(Balance) as balance,sum(YeartodateBalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''I''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''I''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid)dd
union all
select sum(Balance) as balance,sum(YeartodateBalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''E''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''E''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid)dd )ee
end
else
begin
select accountid,Accountdesc,groupid,balance,yeartodatebalance,cashflowgroup from #Cashflow --order by cashflowgroup desc
-----------Adding the net income part-----------------------------------------------------------------------------------
union all
select 0 as accountid,''Net Income'' as Accountdesc,0 as groupid,sum(Balance) as balance,sum(YeartodateBalance) as yeartodatebalance,''Z-income'' as cashflowgroup from (
select sum(Balance) as balance,sum(YeartodateBalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''I''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
and vwJournalDetails.departmentid=@intDepartmentID
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''I''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
and vwJournalDetails.DepartmentID=@intDepartmentID
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid)dd
union all
select sum(Balance) as balance,sum(YeartodateBalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,sum(Balance) as Balance,sum(yeartodatebalance) as YeartodateBalance from (
select accountid,accountdesc,groupid,isnull(sum(Credit),0) -isnull(sum(Debit),0) as Balance,0 yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''E''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and moajournalheader.journaldate between @dtFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
and vwJournalDetails.Departmentid=@intDepartmentID
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
union all
select accountid,accountdesc,groupid,0 as Balance,isnull(sum(Credit),0) -isnull(sum(Debit),0) as yeartodatebalance--,@cashflowgroup1--,isnull(sum(Credit),0) as Credit,isnull(sum(Debit),0) as Debit
from
(
select case  journalcredit when 1 then sum(isnull(amount,0)) end as Credit ,
case  journalcredit when 0 then sum(isnull(amount,0))  end as Debit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid
from vwJournalDetails ,moajournalheader
left outer join aGroupMaster on aGroupMaster.companyid=@intCompanyId and accounttype=''E''
left outer join  aaccountmaster on aaccountmaster.groupid=aGroupMaster.groupid --and accountmaster.accountid not in(22,47)
where vwJournalDetails.accountid=aaccountmaster.accountid and vwJournalDetails.companyid=@intCompanyId and vwJournalDetails.journalid=moajournalheader.journalid
and vwJournalDetails.DepartmentID=@intDepartmentID
and moajournalheader.journaldate between @dtFinYearFromdate and @dtTodate and moajournalheader.cancel=0 and moajournalheader.financialid>0
group by journalcredit,vwJournalDetails.accountid,accountdesc,aaccountmaster.groupid) c group by  accountid,accountdesc,groupid
) cc group by accountid,accountdesc,groupid)dd )ee
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep_old]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDep_old]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 01/06/2004, 13/07/2004
-- Modified by   : Hariharan
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : included consolidation venki 261203
--   : Removed cursor and given temporary table names
--   : carry forwarding of unclosed financial year done
--   : Financialid considerations corrected
--   : consolidation option department wise is corrected
--   : Script Verified
CREATE PROCEDURE [dbo].[spBalanceSheetDep_old] (@strToDate as varchar(10),
@intCompanyID as int,
@intDepartmentId as int,
@bitcons as bit,
@intlevel as int = 0,
@intconsolidation as int =0 ) AS
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,
AccId int,
DepartmentId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int)
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
if @intLastFinId = 0
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
(Select Deptid from #SubDepts1)
--to change the parent group if level id > 0
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)
Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
daDepartmentid from (SELECT am.CompanyId, AccountID, AccountCode, AccountDesc,
AccountType, GM.GroupID, GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,
ParentGroupID, daDepartmentid FROM aAccountMaster AM,aGroupMaster GM,
adeptAccounts d, #SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND
(GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND
AM.CompanyID = @intCompanyID and am.Accountid = d.daAccountId and
am.CompanyId = d.daCompanyId AND d.dadepartmentid = dep.deptid
Union
SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, dd.deptid
FROM aAccountMaster AM,aGroupMaster GM,
vwGlobalAccounts d, #SubDepts1 dd WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId
group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
daDepartmentid ORDER BY GrpAcId.AccountID
Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
DepartmentId, CompanyId,
case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId
and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''L''
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''L''
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
Begin
select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
Begin
Update #BalSheet set OBDr = isnull(OBDr,0) +
(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
where AccId = (Select RetainedEarningsAcc from aSettings where
CompanyId = @intCompanyId)
End
End
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
--SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b
--where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
--order by b.parentgroupid
if @intConsolidation = 0
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
End
Else
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
End
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, departmentid, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, sum(b.OBDr),
sum(b.OBCr), sum(b.DebitAmt), sum(b.CreditAmt), b.AccId, 0, r.OrderNo,
r.LevelCode,  0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from
#FilteredResult r left outer join #balsheet b on  ((r.GroupId = b.GroupId  and
r.AccountId is null) or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and
r.AccountId is not null))
group by b.CompanyId, r.OrderNo, r.AccType, r.GroupId, r.GroupDesc,
r.LevelCode, r.ParentGroupId, b.AccId, b.AccCode, b.AcDesc
having ((((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(debitamt,0)) - sum(isnull(creditamt,0))) <> 0 and
isnull(r.AccType,'''') =''A'') or ((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(creditamt,0))) -  sum(isnull(debitamt,0))
<> 0 and isnull(r.AccType,'''') =''L'') and b.accCode is not null) or b.accCode is null)
and (r.AccType =''A'' or r.AccType =''L'' )
order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #BalSheetFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
if @intLevel>0
Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
Select * from #BalSheetFinal order by OrderNo
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
Drop Table #BalSheet
Drop Table #FilteredResult
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 01/06/2004, 13/07/2004
-- Modified by   : Hariharan
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : included consolidation venki 261203
--   : Removed cursor and given temporary table names
--   : carry forwarding of unclosed financial year done
--   : Financialid considerations corrected
--   : consolidation option department wise is corrected
--   : Script Verified
--Ref.No:1
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
/*
exec spBalanceSheetDep ''20100520'',1,0,0,0,0
*/
CREATE PROCEDURE [dbo].[spBalanceSheetDep] (@strToDate as varchar(10),
@intCompanyID as int,
@intDepartmentId as int,
@bitcons as bit,
@intlevel as int = 0,
@intconsolidation as int =0 ) AS
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(50),
Remarks varchar(1000),
Type varchar(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,
AccId int,
DepartmentId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int)
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0  --Ref.No:1 Commented
if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Commented
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert into #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
(Select Deptid from #SubDepts1)
------------------------------------------------OK
--to change the parent group if level id > 0
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)
Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
daDepartmentid from (SELECT am.CompanyId, AccountID, AccountCode, AccountDesc,
AccountType, GM.GroupID, GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,
ParentGroupID, daDepartmentid FROM aAccountMaster AM,aGroupMaster GM,
adeptAccounts d, #SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND
(GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND
AM.CompanyID = @intCompanyID and am.Accountid = d.daAccountId and
am.CompanyId = d.daCompanyId AND d.dadepartmentid = dep.deptid
Union
SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, dd.deptid
FROM aAccountMaster AM,aGroupMaster GM,
vwGlobalAccounts d, #SubDepts1 dd WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId
group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
daDepartmentid ORDER BY GrpAcId.AccountID
Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
DepartmentId, CompanyId,
case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId
and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''L''
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''L''
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.DepartmentId = #BalSheet.DepartmentId
and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
Begin
select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
Begin
Update #BalSheet set OBDr = isnull(OBDr,0) +
(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
where AccId = (Select RetainedEarningsAcc from aSettings where
CompanyId = @intCompanyId)
End
End
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
--SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b
--where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
--order by b.parentgroupid
if @intConsolidation = 0
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
End
Else
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
End
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, departmentid, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, sum(b.OBDr),
sum(b.OBCr), sum(b.DebitAmt), sum(b.CreditAmt), b.AccId, 0, r.OrderNo,
r.LevelCode,  0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from
#FilteredResult r left outer join #balsheet b on  ((r.GroupId = b.GroupId  and
r.AccountId is null) or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and
r.AccountId is not null))
group by b.CompanyId, r.OrderNo, r.AccType, r.GroupId, r.GroupDesc,
r.LevelCode, r.ParentGroupId, b.AccId, b.AccCode, b.AcDesc
having ((((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(debitamt,0)) - sum(isnull(creditamt,0))) <> 0 and
isnull(r.AccType,'''') =''A'') or ((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(creditamt,0))) -  sum(isnull(debitamt,0))
<> 0 and isnull(r.AccType,'''') =''L'') and b.accCode is not null) or b.accCode is null)
and (r.AccType =''A'' or r.AccType =''L'' )
order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #BalSheetFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
if @intLevel>0
Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
Select * from #BalSheetFinal order by OrderNo
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
Drop Table #BalSheet
Drop Table #FilteredResult
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Liability_Comp]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Liability_Comp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------
--CREATED BY   : PRASANTH JOSEPH
--CREATED ON   : 05/12/2009
--CREATED FOR  : GETING COMPARATIVE BALANCE SHEET, SELECTED FINANCILA YEAR ACCOUNT BALANCE DETAILS WILL GIVE.
--MODIFIED BY  :
--MODIFIED ON  :
--USAGE        : EXEC  spBalanceSheet_Asset_Comp ''2'',1,1
----------------------------------------------------------------------------
CREATE  proc [dbo].[spBalanceSheet_Liability_Comp](@strFinId as varchar(10), @intCompanyID as int,@intlevel as int =0) as
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(100),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int,
@strTodate as datetime
Create table #vwJournalDetails (companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int
---balance numeric(18,2)
)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int,
FinYearID int,
AccBalance numeric(18,2) )
CREATE TABLE #TEMP_FINID
(
FINID INT
)
CREATE TABLE #BalanceSheet_Groupwise
(
CompanyID INT,
AcType  VARCHAR(10),
GroupID INT,
GroupName VARCHAR(100),
ParentGroupID INT,
FinYerID INT,
AccBalance NUMERIC(18,2)
)
INSERT INTO #temp_finid SELECT * FROM  fnSplit(@strFinId,'','')
WHILE  (SELECT COUNT(*) FROM  #temp_finid)<>0
BEGIN
SELECT @intFinId=max(FINID) FROM #temp_finid
SELECT  @dtFromDate = sdate, @strfromdate = CONVERT(varchar,sdate,120),@strtodate=edate FROM vwfinyearperiod
WHERE financialid=@intFinId
/*
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
*/
SELECT @dtLastFinUnclosedEDate = DATEADD(dd, -1, @dtFromDate )
SELECT @intLastFinId = MAX(FinancialId) FROM aAccountFinYearOpening
WHERE CompanyId = @intCompanyId and FinancialId <= @intFinId
IF @intLastFinId = 0
SELECT  @dtPrevFinUnclosedSDate = sdate FROM vwFinYearPeriod
WHERE financialid = (SELECT min(financialid) FROM afinancialyear WHERE
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
SELECT  @dtPrevFinUnclosedSDate = sdate FROM vwFinYearPeriod
WHERE financialid = @intLastFinId and CompanyId= @intCompanyId
INSERT #Tempjournalheader
SELECT H.* FROM moajournalheader h (nolock) WHERE journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
INSERT #vwJournalDetails
SELECT d.* FROM #Tempjournalheader h, vwJournalDetails d (nolock) WHERE
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
INSERT INTO #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId)
SELECT am.CompanyId, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, AccountID
FROM aAccountMaster AM, aGroupMaster GM WHERE GM.GroupID = AM.GroupID AND
(GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid
AND AM.CompanyID = @intCompanyID
UPDATE #BalSheet set OBDr = opening.Openingamount FROM (SELECt AccountId,
CompanyId, Sum(Openingamount) Openingamount FROM aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId GROUP BY CompanyId,
AccountId) opening WHERE opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
UPDATE #BalSheet SET OBDr = OBDr + ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId ) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
UPDATE #BalSheet SET OBCr = OBDr + ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v ,
#TempJournalHeader h WHERE v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
UPDATE #BalSheet SET OBCr = OBDr - ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v ,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
UPDATE #BalSheet SET DebitAmt = trialDeb.amount FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate GROUP BY v.CompanyId, v.AccountId) trialDeb WHERE
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId
UPDATE #BalSheet SET CreditAmt = trialDeb.amount FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM
#vwJournalDetails v, #TempJournalHeader h WHERE v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
GROUP BY v.CompanyId, v.AccountId) trialDeb WHERE
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
IF @intFinId > (SELECT MAX(financialid) FROM aAccountfinyearopening WHERE
CompanyId = @intCOmpanyId )
BEGIN
SELECT @dtPrevFinUnclosedSDate = sdate FROM vwfinyearperiod WHERE
CompanyId = @intCompanyId
and FinancialId = (SELECT MAX(financialid) FROM aAccountfinyearopening WHERE
CompanyId = @intCOmpanyId )
SELECT @dblDebit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
SELECT @dblCredit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
IF ISNULL(@dblDebit,0) + ISNULL(@dblCredit,0) >0
BEGIN
UPDATe #BalSheet SET OBDr = ISNULL(OBDr,0) +
(ISNULL(@dblCredit,0)) - ISNULL(@dblDebit,0) , OBCr = 0
WHERE AccId = (SELECT RetainedEarningsAcc FROM aSettings WHERE
CompanyId = @intCompanyId)
END
END
SET @dblDebit = 0.0
SET @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
SELECT @dblDebit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
SELECT @dblCredit = SUM(ISNULl(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
INSERT #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
EXEC SpGroupLevelOrdering @intCompanyId, 0
INSERT #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId,FinYearID,AccBalance)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.OrderNo, r.LevelCode,
0,  ISNULL(@dblDebit,0) - ISNULL(@dblCredit,0) Bal, r.ParentGroupId,@intFinId,
CASE WHEN r.AccType=''A'' THEN  OBDr+DebitAmt-CreditAmt  ELSE OBDr+CreditAmt-DebitAmt END AccBalance
FROM #FilteredResult r
left outer join #balsheet b ON  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))
WHERE ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
<> 0 and isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''L'') and
b.accCode is not null) or b.accCode is null) and (r.AccType =''A'' or r.AccType =''L'' )
ORDER BY r.orderno
SET @GroupId = 0
-- TO avoid the groups which does not have any accounts information
SELECT TOP 1 @GroupID = GroupId FROM #BalSheetFinal WHERE Checked = 0
ORDER BY OrderNo DESC
WHILE @GroupID <>0
BEGIN
set @intCount = 0
SELECT @intCount = COUNT(*) FROM #BalSheetFinal WHERE
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
IF @intCount = 0
DELETE FROM #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
DELETE FROM #BalSheetFinal where LevelCode >= @intLevel and AccId is null
DELETE FROM  #temp_finid where FINID=@intFinId
END
INSERT #BalanceSheet_Groupwise (CompanyID,Actype,GroupID,GroupName,FinYerID,AccBalance )
SELECT CompanyID,AcType,GroupID,GroupName,FinYearID,SUM(AccBalance)
FROM #BalSheetFinal GROUP BY CompanyID,AcType,GroupID,GroupName,FinYearID
--delete from #BalanceSheet_Groupwise where GroupID in (25)
--Select * from #BalSheetFinal where groupid=40 order by OrderNo
select #BalanceSheet_Groupwise.*,a.StartYear from #BalanceSheet_Groupwise  inner join aFinancialYear a on  FinYerID=a.FinancialID where AcType=''L'' --and  GroupID in (25)
order by GroupName
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop Table #FilteredResult
Drop table #BalSheetFinal
drop table #BalanceSheet_Groupwise
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Detail]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By :Benzigar S D
--Created On :26/07/2010
--Details    :To get Balance sheet teport with Department waise splitup
--Modified By :Sreejith G A
--Created On :28/07/2010
--Details    :To get Balance sheet teport with Department waise splitup
--Ref.No:2
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
CREATE proc [dbo].[spBalanceSheet_Detail] (@strToDate as varchar(10), @intCompanyID as int,
@intlevel as int =0) as
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(100),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(1000),  --jyothish changed 250 to 1000
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int,departmentid int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int,DepartmentName varchar(50))
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(day, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0    --Ref.No:2  Commented
if ISNULL(@intLastFinId,0) = 0    --Ref.No:2 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, ------NEW MODIFIED
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, departmentid)
select  vss.CompanyId, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,
vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.AccountID,vss.departmentid
from
(SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid
from aaccountfinyearopening ad
left outer join   aaccountmaster AM on AM.accountid=ad.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
union all
SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid
from  #vwJournalDetails v
left outer join   aaccountmaster AM on AM.accountid=v.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
)vss
where
(VSS.AccountType = ''A'' OR VSS.AccountType = ''L'')
AND VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc,ParentGroupID
Update #BalSheet set  OBDr = opening.Openingamount from (Select AccountId,
CompanyId, Sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,
AccountId,departmentid) opening Where opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
and opening.departmentid= #BalSheet.departmentid
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A'' and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set  OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.Departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId, v.Departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and trialDeb.Departmentid=#BalSheet.departmentid
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.CompanyId, v.AccountId, v.departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid = #BalSheet.departmentid
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
Begin
select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where
CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
select @dblDebit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
select @dblCredit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
Begin
Update #BalSheet set OBDr = isnull(OBDr,0) +
(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
where AccId = (Select RetainedEarningsAcc from aSettings where
CompanyId = @intCompanyId)
End
End
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
select @dblCredit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
--   exec SpGroupLevelOrdering_DETAIL @intCompanyId, 0
exec SpGroupLevelOrdering @intCompanyId, 0
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, Departmentid, DepartmentName, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId,b.Departmentid, ad.DepartmentName, r.OrderNo, r.LevelCode,
0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r
left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null  )
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null ))
left outer join adepartmentmaster ad on ad.departmentid=b.departmentid
where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
<> 0 and isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''L'') and
b.accCode is not null) or b.accCode is null) and (r.AccType =''A'' or r.AccType =''L'' )
--and r.departmentid=b.departmentid
order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #BalSheetFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
Select * from #BalSheetFinal order by OrderNo
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop Table #FilteredResult
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Asset_Comp]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet_Asset_Comp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------
--CREATED BY   : PRASANTH JOSEPH
--CREATED ON   : 05/12/2009
--CREATED FOR  : GETING COMPARATIVE BALANCE SHEET, SELECTED FINANCILA YEAR ACCOUNT BALANCE DETAILS WILL GIVE.
--MODIFIED BY  :
--MODIFIED ON  :
--USAGE        : EXEC  spBalanceSheet_Asset_Comp ''2'',1,0
----------------------------------------------------------------------------
CREATE  proc [dbo].[spBalanceSheet_Asset_Comp] (@strFinId as varchar(10), @intCompanyID as int,
@intlevel as int =0) as
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(100),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int,
@strTodate as datetime
Create table #vwJournalDetails (companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int
---balance numeric(18,2)
)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int,
FinYearID int,
AccBalance numeric(18,2) )
CREATE TABLE #TEMP_FINID
(
FINID INT
)
CREATE TABLE #BalanceSheet_Groupwise
(
CompanyID INT,
AcType  VARCHAR(10),
GroupID INT,
GroupName VARCHAR(100),
ParentGroupID INT,
FinYerID INT,
AccBalance NUMERIC(18,2)
)
INSERT INTO #temp_finid SELECT * FROM  fnSplit(@strFinId,'','')
WHILE  (SELECT COUNT(*) FROM  #temp_finid)<>0
BEGIN
SELECT @intFinId=max(FINID) FROM #temp_finid
SELECT  @dtFromDate = sdate, @strfromdate = CONVERT(varchar,sdate,120),@strtodate=edate FROM vwfinyearperiod
WHERE financialid=@intFinId
/*
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
*/
SELECT @dtLastFinUnclosedEDate = DATEADD(dd, -1, @dtFromDate )
SELECT @intLastFinId = MAX(FinancialId) FROM aAccountFinYearOpening
WHERE CompanyId = @intCompanyId and FinancialId <= @intFinId
IF @intLastFinId = 0
SELECT  @dtPrevFinUnclosedSDate = sdate FROM vwFinYearPeriod
WHERE financialid = (SELECT min(financialid) FROM afinancialyear WHERE
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
SELECT  @dtPrevFinUnclosedSDate = sdate FROM vwFinYearPeriod
WHERE financialid = @intLastFinId and CompanyId= @intCompanyId
INSERT #Tempjournalheader
SELECT H.* FROM moajournalheader h (nolock) WHERE journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
INSERT #vwJournalDetails
SELECT d.* FROM #Tempjournalheader h, vwJournalDetails d (nolock) WHERE
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
INSERT INTO #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId)
SELECT am.CompanyId, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, AccountID
FROM aAccountMaster AM, aGroupMaster GM WHERE GM.GroupID = AM.GroupID AND
(GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid
AND AM.CompanyID = @intCompanyID
UPDATE #BalSheet set OBDr = opening.Openingamount FROM (SELECt AccountId,
CompanyId, Sum(Openingamount) Openingamount FROM aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId GROUP BY CompanyId,
AccountId) opening WHERE opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
UPDATE #BalSheet SET OBDr = OBDr + ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId ) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
UPDATE #BalSheet SET OBCr = OBDr + ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v ,
#TempJournalHeader h WHERE v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
UPDATE #BalSheet SET OBCr = OBDr - ISNULL(trialDeb.amount,0) FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v ,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate GROUP BY v.CompanyId, v.AccountId) trialDeb
WHERE trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
UPDATE #BalSheet SET DebitAmt = trialDeb.amount FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM #vwJournalDetails v,
#TempJournalHeader h WHERE v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate GROUP BY v.CompanyId, v.AccountId) trialDeb WHERE
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId
UPDATE #BalSheet SET CreditAmt = trialDeb.amount FROM (SELECT v.AccountId,
v.CompanyId, SUM(ISNULL(v.Amount,0)) Amount FROM
#vwJournalDetails v, #TempJournalHeader h WHERE v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
GROUP BY v.CompanyId, v.AccountId) trialDeb WHERE
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
IF @intFinId > (SELECT MAX(financialid) FROM aAccountfinyearopening WHERE
CompanyId = @intCOmpanyId )
BEGIN
SELECT @dtPrevFinUnclosedSDate = sdate FROM vwfinyearperiod WHERE
CompanyId = @intCompanyId
and FinancialId = (SELECT MAX(financialid) FROM aAccountfinyearopening WHERE
CompanyId = @intCOmpanyId )
SELECT @dblDebit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
SELECT @dblCredit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
IF ISNULL(@dblDebit,0) + ISNULL(@dblCredit,0) >0
BEGIN
UPDATe #BalSheet SET OBDr = ISNULL(OBDr,0) +
(ISNULL(@dblCredit,0)) - ISNULL(@dblDebit,0) , OBCr = 0
WHERE AccId = (SELECT RetainedEarningsAcc FROM aSettings WHERE
CompanyId = @intCompanyId)
END
END
SET @dblDebit = 0.0
SET @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
SELECT @dblDebit = SUM(ISNULL(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
SELECT @dblCredit = SUM(ISNULl(Amount,0))
FROM #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
WHERE g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
INSERT #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
EXEC SpGroupLevelOrdering @intCompanyId, 0
INSERT #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId,FinYearID,AccBalance)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.OrderNo, r.LevelCode,
0,  ISNULL(@dblDebit,0) - ISNULL(@dblCredit,0) Bal, r.ParentGroupId,@intFinId,
CASE WHEN r.AccType=''A'' THEN  OBDr+DebitAmt-CreditAmt  ELSE OBDr+CreditAmt-DebitAmt END AccBalance
FROM #FilteredResult r
left outer join #balsheet b ON  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))
WHERE ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
<> 0 and isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''L'') and
b.accCode is not null) or b.accCode is null) and (r.AccType =''A'' or r.AccType =''L'' )
ORDER BY r.orderno
SET @GroupId = 0
-- TO avoid the groups which does not have any accounts information
SELECT TOP 1 @GroupID = GroupId FROM #BalSheetFinal WHERE Checked = 0
ORDER BY OrderNo DESC
WHILE @GroupID <>0
BEGIN
set @intCount = 0
SELECT @intCount = COUNT(*) FROM #BalSheetFinal WHERE
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
IF @intCount = 0
DELETE FROM #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
DELETE FROM #BalSheetFinal where LevelCode >= @intLevel and AccId is null
DELETE FROM  #temp_finid where FINID=@intFinId
END
INSERT #BalanceSheet_Groupwise (CompanyID,Actype,GroupID,GroupName,ParentGroupID,FinYerID,AccBalance )
SELECT CompanyID,AcType,GroupID,GroupName,ParentGroupId,FinYearID,SUM(AccBalance)
FROM #BalSheetFinal GROUP BY CompanyID,AcType,GroupID,GroupName,ParentGroupId,FinYearID
--delete from #BalanceSheet_Groupwise where GroupID in (25)
select * from #BalSheetFinal  where groupid=6 order by groupname
--select #BalanceSheet_Groupwise.*,a.StartYear from #BalanceSheet_Groupwise  inner join aFinancialYear a on  FinYerID=a.FinancialID where AcType=''A'' --and  GroupID in (25)
--order by GroupName
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop Table #FilteredResult
Drop table #BalSheetFinal
drop table #BalanceSheet_Groupwise
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 28/04/2004, 02/06/2004, 13/07/2004
-- Modified by   : Hariharan R
--Comments  : Taken from dep wise sp avoiding loooping for acccount balances
--   : verified the script
/*
exec spBalanceSheet ''20100520'',1,1
*/
-----------------------------------------------------
--Ref.No:1
--Modifted By:Aadyakumar.D.V
--Modified On:03/11/2011
--Reason      :String or binary data would be truncated,bug came so field length is increased
-----------------------------------------------------
--Ref.No:2
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
-----------------------------------------------------
CREATE proc [dbo].[spBalanceSheet] (@strToDate as varchar(10), @intCompanyID as int,
@intlevel as int =0) as
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(100),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
--ReferenceNo varchar(100),
--Remarks varchar(250),
--Type char(10),
--ReferenceNo varchar(50),--Ref.No:1
ReferenceNo varchar(100),--Ref.No:1
Remarks varchar(1000),
Type varchar(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AccId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ProfitLoss Numeric(18,2),
ParentGroupId int)
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
--if @intLastFinId = 0   --Ref.No:2 Commented
if ISNULL(@intLastFinId,0) = 0      --Ref.No:2 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId)
SELECT am.CompanyId, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, AccountID
FROM aAccountMaster AM, aGroupMaster GM WHERE GM.GroupID = AM.GroupID AND    (GM.AccountType = ''A'' OR GM.AccountType = ''L'') AND GM.CompanyID = am.companyid
AND AM.CompanyID = @intCompanyID
Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
CompanyId, Sum(Openingamount) Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,
AccountId) opening Where opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId ) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A''
Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.CompanyId, v.AccountId) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
Begin
select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where
CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCOmpanyId )
select @dblDebit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
select @dblCredit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and
h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and
(journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
and (accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
Begin
Update #BalSheet set OBDr = isnull(OBDr,0) +
(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
where AccId = (Select RetainedEarningsAcc from aSettings where
CompanyId = @intCompanyId)
End
End
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
select @dblCredit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' ) and h.financialid > 0
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AccId, orderno, levelcode, Checked,
ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.OrderNo, r.LevelCode,
0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r
left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))
where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
<> 0 and isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''L'') and
b.accCode is not null) or b.accCode is null) and (r.AccType =''A'' or r.AccType =''L'' )
order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #BalSheetFinal where
((AcDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #BalSheetFinal where GroupId = @GroupID
else
Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
Select * from #BalSheetFinal order by OrderNo
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop Table #FilteredResult
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  View [dbo].[vwchequereportprint]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwchequereportprint]'))
EXEC dbo.sp_executesql @statement = N'
--CREATED BY: NIDHEESH PV
--CREATED ON:18-05-2010
--COMMENTS: TO LOAD CHEQUE REPORT FOR PAYMENT,HPPAYMENT,FP FEE PAY,& CONTRA ALSO
CREATE view [dbo].[vwchequereportprint]
as
SELECT phPaymentID, phCompanyID, phPaymentDate, convert(varchar(250),phPayee)payee, phAmount,''PAY'' type
FROM aHqPaymentVoucherHeader
union all
select hphPaymentID,hphCompanyID,hphPaymentDate,convert(varchar(250),hpCustName),hphPaymentAmount,''HPP'' type
from ahpPaymentHeader inner join loshpcustomerdetails on hpCustID=hphCustomerID
union all
select HpHPaymentID,HpHCompanyID,HpHPaymentDate,convert(varchar(250),HpHPayee),HpHAmount,''HPFP'' type
from aHPFeePaymentHeader
union all
select ContraID,c.CompanyID,ContraDate,AccountDesc,ContraAmount,''CON'' type
from Contra c inner join aaccountmaster on fromaccountid=accountid'
GO
/****** Object:  StoredProcedure [dbo].[spMag_getInvoiceByNumber]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_getInvoiceByNumber]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Regin T.
-- Create date: 17-07-2010
-- Description: Returns the details of invoice by matching invoice number.
-- =============================================
-- spMag_getInvoiceByNumber 1, ''06/H3/ICS/10''
CREATE PROCEDURE [dbo].[spMag_getInvoiceByNumber]
@intCompanyId int
, @strInvoiceNo varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
''CashSale'' SaleType, poshShopId ShopId, poshBillId InvoiceId
, poshBillDate InvoiceDate, poshCustomerName CustomerName
FROM
losPosHeader
WHERE
poshCancelled=0
and poshCompanyId=@intCompanyId
and poshBillNo=@strInvoiceNo
UNION ALL
SELECT
''CreditSale'', ihShopId, ihInvoiceId
, ihInvoiceDate, c.CustomerName
FROM
losInvoiceHeader ih
INNER JOIN aCustomerMaster c ON ih.ihCustomerId=c.CustomerId
WHERE
ihCancelled=0
and ihCompanyId=@intCompanyId
and ihInvoiceNo=@strInvoiceNo
END' 
END
GO
/****** Object:  View [dbo].[vwGodownTranferFlow]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownTranferFlow]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwGodownTranferFlow] AS
select gthDespatchId,gthDespatchNo,gthFromGodownID ,GodownName FromGodownName,gthDespatchDate,gthRemarks,
	ahArrivalId,ahArrivalNo,ahArrivalDate,ahLocalGodownId, ToGodownName,ahRemarks
from MEiGodownTransferheader
Left Outer join aGodown On GodownId=gthFromGodownID
Left Outer Join
	(select ahArrivalId,ahArrivalNo,ahArrivalDate,ahLocalGodownId,ahDespatchNoteId ,
	Godownname ToGodownName,ahRemarks,ahGodownID from
	LOiArrivalHeader Left Outer Join aGodown ON  GodownId=ahLocalGodownId where ahArrivalType=''G'' and ahCancelled=0)Arrival
	on gthDespatchId=ahDespatchNoteId And ahGodownID=gthFromGodownID
where gthCancelled=0'
GO
/****** Object:  View [dbo].[vwExpiryItemDetails]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwExpiryItemDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Object type: View
--Object name: vwExpiryItemDetails
--Description: This view is created to prepare reports on expiry items.
-- This view takes data from four tables names losexpiryarrivaldetails, losexpiryissuedetails
-- loiexpiryarrivaldetails and loiexpiryissuedetails
-- It calculates item quantity based on shopid/godownid, itemid and batchno.
--------------------------------------
--Created by: Regin T.
--Created on: 04-Aug-2008
--------------------------------------
--Ref.No    :01
--Altered by: AADYAKUMAR.D.V
--Altered on: 15-07-2011
--Comment   : For bug fixing ticket WRN-160616
--------------------------------------
CREATE view [dbo].[vwExpiryItemDetails] as
-- Fetching data from shops starts
select * from
(
select ea.eaditemid,--Ref.No:01
i.itemcode, i.itemdescription, i.itemCategoryID, ic.CategoryNameDescription,
ea.eadbatchno batchNo, b.itemQty, u.unitname,
max(ea.eadexpirydate) expiryDate,--Ref.No:01
ea.eadshopid shopid, NULL godownid, s.departmentID, s.CompanyID
from losexpiryarrivaldetails ea
left outer join aitem i on ea.eaditemid=i.itemid and i.active=1
left outer join aShops s on ea.eadshopid=s.shopID
left outer join aItemCategory ic on i.itemCategoryID=ic.ItemCategoryID
left outer join aunit u on i.unitsid=u.unitid
left outer join
(
-- Calculating itemQty starts
select shopID, itemID, batchNO, sum(itemQty) itemQty from
(select eadshopid shopID, eaditemid itemID, eadbatchno batchNO, eadItemQty itemQty
from losexpiryarrivaldetails
where eadCancel=0
union all
select eidShopID shopID, eidItemID itemID, eidBatchNo batchNO, -eidItemQty itemQty
from losexpiryissuedetails
where eidCancel=0
) a
group by shopID, itemID, batchNO
-- Calculating itemQty ends
) b on b.shopid=ea.eadshopid and b.itemid=i.itemid and b.batchno=ea.eadbatchno
--where eadshopid = 2 and eadexpirydate >=''20101115'' and eadexpirydate <=''20101121''
--Ref.No:01---starts-------------------------------
group by ea.eaditemid,ea.eadbatchno,ea.eadshopid,i.itemcode, i.itemdescription, i.itemCategoryID,
ic.CategoryNameDescription,b.itemQty, u.unitname, s.departmentID, s.CompanyID
--Ref.No:01---end-------------------------------
-- Fetching data from shops ends
) abc
where abc.itemQty <>0
union all
-- Fetching data from Godown starts
select ea.eaditemid, i.itemcode, i.itemdescription, i.itemCategoryID, ic.CategoryNameDescription,
ea.eadbatchno batchNo, b.itemQty, u.unitname,
ea.eadexpirydate expiryDate, NULL shopid, ea.eadgodownid, g.departmentID, g.CompanyID
from loiexpiryarrivaldetails ea left outer join aitem i
on ea.eaditemid=i.itemid and i.active=1
left outer join aGodown g on ea.eadgodownid=g.godownID
left outer join aItemCategory ic on i.itemCategoryID=ic.ItemCategoryID
left outer join aunit u on i.unitsid=u.unitid
left outer join
(
-- Calculating itemQty starts
select godownID, itemID, batchNO, sum(itemQty) itemQty from
(select eadgodownid godownID, eaditemid itemID, eadbatchno batchNO, eadItemQty itemQty
from loiexpiryarrivaldetails
union all
select eidgodownID godownID, eidItemID itemID, eidBatchNo batchNO, -eidItemQty itemQty
from loiexpiryissuedetails) a
group by godownID, itemID, batchNO
-- Calculating itemQty ends
) b on b.godownid=ea.eadgodownid and b.itemid=i.itemid and b.batchno=ea.eadbatchno
-- Fetching data from Godown ends'
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLoginShop]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckLoginShop]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : Rajesh Kamalakshan
-- Create date : 18/03/2010
-- Description : To check the user name and password for shops
-- =============================================
create PROCEDURE [dbo].[spMagnolia_CheckLoginShop]--  ''fies'','''',1
-- Add the parameters for the stored procedure here
@UserName varchar(50),
@Password varchar(50),
@shopid int,
@Outs int =null output
AS
BEGIN
SELECT @Outs=UserId
FROM [dbo].lousers
WHERE
UserName=@UserName and
UserPwd=@Password and
shopid=@shopid
END' 
END
GO
/****** Object:  View [dbo].[vwcustomerlisting]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerlisting]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcustomerlisting    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwcustomerlisting    Script Date: 14/09/2002 12:48:06 AM ******/
/****** Object:  View dbo.vwcustomerlisting    Script Date: 31/07/2002 2:00:27 PM ******/
/****** Object:  View dbo.vwcustomerlisting    Script Date: 20/11/2001 9:58:55 AM ******/
/****** Object:  View dbo.vwcustomerlisting    Script Date: 17/11/2001 9:21:19 PM ******/
CREATE view [dbo].[vwcustomerlisting] as
select c.customerid, customername, address1, c.phoneno, c.faxno,
emailid, sc.creditlimit, shopname, s.shopid  from acustomermaster c, ashopcustomerdetails sc,
ashops s
where c.customerid = sc.customerid and s.shopid = sc.shopid'
GO
/****** Object:  View [dbo].[vwcustomerwiseservicepending]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomerwiseservicepending]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwcustomerwiseservicepending] as
select serinvhcancelled, serbookhid, serbookhshopid, serbookhcompanyid, sercallbkhno serbookhno,sercallbkhdate serbookhdate,sercallbkhslno serbookhslno,
serinvhCustomerId serbookhcustomerid, sercallbkhrecvdfrom serbookhrecvdfrom, sercallbkhaddress serbookhaddress, serbookadvanceamount,
serbookhremarks, serbookhpreparedby,  c.customername, v.itemdescription completedescription,
a.itemdescription itemname, a.itemcode, a.part_Code, a.modelno, a.brand, los.sercallbkhpurchdate serbookhpurchdate,
bh.serbookhdeldate, case serbooksermode when 0 then ''Service In'' else ''Service Out'' end sermode,
serbooksermode, spername, a.ItemCategoryID, CategoryNameDescription
from losservicebookingheader bh inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid
and bh.serbookhshopid=los.serCallBkhshopid
left outer join  asalespersonmaster sa on serbookhpreparedby=Sperid
and  bh.serbookhcompanyid=sa.Companyid
inner join losserviceheader on serbookhid = serinvhbookingid  and serinvhcompleted=0 and
serbookhshopid = serinvhshopid   and  serbookhcompanyid = serinvhcompanyid and serinvhjobinvcancelled=0
left outer join losserviceinvheader li   on losserviceheader.serinvhid=li.serinvhjobcardid and losserviceheader.serinvhshopid=li.serinvhshopid
and losserviceheader.serinvhcompanyid=li.serinvhcompanyid
left outer join acustomermaster c on li.serinvhCustomerId= c.customerid
and li.serinvhcompanyid = c.companyid,
ashops s, aitem a, vwitemdescription v, aItemCategory aic where los.sercallbkhitemid = a.itemid and
a.itemid = v.itemid and bh.serbookhshopid = s.shopid
and a.ItemCategoryId = aic.ItemCategoryId
union
select 0, serbookhid, serbookhshopid, serbookhcompanyid, sercallbkhno serbookhno,sercallbkhdate serbookhdate,sercallbkhslno serbookhslno,
sercallbkhcustomerid serbookhcustomerid, sercallbkhrecvdfrom serbookhrecvdfrom, sercallbkhaddress serbookhaddress, serbookadvanceamount,
serbookhremarks, serbookhpreparedby,  c.customername, v.itemdescription completedescription,
a.itemdescription itemname, a.itemcode, a.part_Code, a.modelno, a.brand, los.sercallbkhpurchdate serbookhpurchdate,
bh.serbookhdeldate, case serbooksermode when 0 then ''Service In'' else ''Service Out'' end sermode,
serbooksermode, spername, a.ItemCategoryID, CategoryNameDescription
from losservicebookingheader bh inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid
and bh.serbookhshopid=los.serCallBkhshopid
inner join losserestimateapproval lop on lop.seaappcompanyid=bh.serbookhcompanyid and
lop.seaappshopid=bh.serbookhshopid and lop.seaappbookingid=bh.serbookhid and seaappcancelled=0
left outer join  asalespersonmaster sa on serbookhpreparedby=Sperid
and  bh.serbookhcompanyid=sa.Companyid
left outer join acustomermaster c on los.sercallbkhcustomerid= c.customerid
and bh.serbookhcompanyid = c.companyid  ,
ashops s, aitem a, vwitemdescription v, aItemCategory aic where los.sercallbkhitemid = a.itemid and
a.itemid = v.itemid and bh.serbookhshopid = s.shopid
and a.ItemCategoryId = aic.ItemCategoryId and serbookhid not in(select serinvhbookingid from losserviceheader where
serinvhjobinvcancelled=0)'
GO
/****** Object:  View [dbo].[vwCustomerWiseService]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerWiseService]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwCustomerWiseService] AS
SELECT serbookhid, serbookhShopId, serbookhCompanyId,
sercallbkhno serbookhno, sercallbkhdate serbookhdate, sercallbkhslno serbookhslno,
serinvhCustomerId serbookhcustomerid , sercallbkhrecvdfrom serbookhrecvdfrom,
sercallbkhaddress serbookhaddress, serbookadvanceamount,
serbookhremarks, serinvno, serinvhdate, li.serinvhpreparedby,
c.customername, v.itemdescription completedescription, a.itemdescription itemname,
a.itemcode, a.part_Code, a.modelno, a.brAND, li.serinvhamount,
isnull(serbooksermode,0) serbooksermode, a.ItemCategoryID, CategoryNameDescription
FROM losServiceBookingHeader bh inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid
and bh.serbookhshopid=los.serCallBkhshopid
, losServiceHeader sh inner join losserviceinvheader li
on li.serinvhjobcardid=sh.serinvhid and sh.serinvhshopid=li.serinvhshopid
and li.serinvhcompanyid=sh.serinvhcompanyid
left outer join aCustomerMaster c
ON li.serinvhCustomerId = c.CustomerId AND
li.serinvhcompanyid = c.CompanyId,
aShops s, aItem a, vwItemDescription v , aItemCategory aic
WHERE bh.serbookhid = sh.serinvhbookingid AND
bh.serbookhShopId = sh.serinvhShopId AND
bh.serbookhCompanyId = sh.serinvhCompanyId AND
los.sercallbkhItemId = a.ItemId AND
a.ItemId = v.ItemId AND
bh.serbookhShopId = s.ShopId
and a.ItemCategoryId = aic.ItemCategoryID'
GO
/****** Object:  View [dbo].[vwDepWiseItems]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDepWiseItems]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[vwDepWiseItems] as
Select d.Itemid, d.departmentid from
(
select A.Itemid, b.departmentid from ashopitemdetail a,ashops b
where a.shopid=b.shopid
union all
select A.Itemid, b.departmentid from agodowndetail a,agodown b
where a.godownid=b.godownid
union all
Select itemid, 0 from aitem) d group by d.Itemid, d.departmentid'
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOutCompanyWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spStockOutCompanyWise
-- ===================================================
-- Author:  Shibin Sundar
-- Create Date: 26-06-2008
-- Description: To Get The Stockout Items Company Wise
-- Purpose : Stock Out Items Automated Mailing.
-- ===================================================
CREATE Procedure [dbo].[spStockOutCompanyWise] As
Begin
Select top 10 cstout.categorynamedescription, cstout.itemdescription, cstout.itemid,
isnull(cstout.stock,0) stock, cstout.reorderlevel, cstout.reorderquantity,
cstout.itemcategoryid, cstout.colorname, cstout.sizename, cstout.active, poqty ,itemcode, brand ,UnitName
From (Select ic.categorynamedescription, a.itemdescription, a.itemid, IsNull(stock,0) stock,
a.reorderlevel, a.reorderquantity, a.itemcategoryid,
IsNull(colorname,'''''''') colorname,
IsNull(sizename,'''''''') sizename,active, IsNull(poqty,0) poqty, itemcode, brand,UnitName
From aitem a
Left Outer Join aUnit au On a.unitsID=au.UnitID
Left Outer Join acolor cr On a.colorid= cr.colorid
Left Outer Join asize z On a.sizeid=z.sizeid
Left Outer Join vwsellingtotalstock vs On a.itemid = vs.itemid
Left Outer Join vwitemorderedinpo On a.itemid = poditemid,
aitemcategory ic, vwDepWiseItems dep  Where ic.itemcategoryid=a.itemcategoryid And a.active=1
And  a.itemid=dep.itemid And a.onetimeshipment=0 And dep.departmentid=0 ) cstout
Where IsNull(cstout.stock,0)  <= cstout.reorderlevel And cstout.reorderlevel>=0
End' 
END
GO
/****** Object:  View [dbo].[vwDailyDeliveryNote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailyDeliveryNote]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------
--Created By : Yogesh Joe
--Created On : 09-06-2010
--Purpose :
--	To use in the reports - Daily Delivery Report,Not Confirmed Delivery Notes
-----------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailyDeliveryNote] as
SELECT DnShopid,DndnId,DndnNo,s.StatusName,DndnDate,ISNULL(dnCustomerName,cm.CustomerName) CustomerName,DnDeliveredBy,DnVesselName,DnDeliveryTime= LTRIM(SUBSTRING(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 10, 5) + RIGHT(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 3)),Dncancelled,DnCustomerID,dnConfirmed
FROM LosDeliveryNoteHeader dnh
LEFT OUTER JOIN (SELECT * FROM aStatus WHERE StatusGroupId=1) s ON dnh.dnStatus=s.StatusId
LEFT OUTER JOIN aCustomerMaster cm ON dnh.DnCustomerID=cm.CustomerID'
GO
/****** Object:  StoredProcedure [dbo].[spFixCostPriceAfterMerging]    Script Date: 10/06/2012 14:17: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].[spFixCostPriceAfterMerging]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- Created by  : Kishore, Hariharan R
-- Created on  : 10/02/2003, 17/03/2003
-- Comments    : Fixes the cost price
--        : Setting pricechanged bit if the cost price changes on fixing.
--Modified by  : Shinu
--Comments     : Defined conditions for Cost Price calculation
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spFixCostPriceAfterMerging] (@intMergeId as int, @intCompanyId as int) AS
Begin
	Declare @numHeaderQty as Numeric(18, 2)
	Declare @numHeaderCostPrice as Numeric(18, 2)
	Declare @numDetailQty as numeric(18, 2)
	Declare @numDetailCostPrice as Numeric(18, 2)
	Declare @numAvgCostPrice as Numeric(18, 2)
	Declare @intItemId as int
	Declare @numOldCostPrice as numeric(18,2)
	
	set @numHeaderCostPrice = 0.0   	
	set @numAvgCostPrice = 0.0
	set @numOldCostPrice= 0.0
-- get header qty
	SELECT @numHeaderQty = SUM(Qty)
	FROM (
		SELECT lghQty Qty FROM loiMergeHeader
		WHERE lghRefMergeId = @intMergeId
		AND lghCompanyId = @intCompanyId
		UNION ALL
		SELECT lshQty FROM losMergeHeader
		WHERE lshRefMergeId = @intMergeId
		) A
-- get header cost price and item id
	SELECT @numHeaderCostPrice = mghItemCostPrice,@intItemId = mghItemId
	FROM aHqMergingHeader
	WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
	SELECT @numDetailQty = SUM(Quantity), @numDetailCostPrice = SUM(Quantity * mgdCostPrice)
		FROM aHqMergingDetails hq
		LEFT OUTER JOIN vwAllMergeDetails vw  ON hq.mgdId = vw.HeaderId AND hq.mgdCompanyId = vw.CompanyId
		AND hq.mgdItemId = vw.ItemId
		WHERE hq.mgdId = @intMergeId AND hq.mgdCompanyId = @intCompanyId
	 set @numAvgCostPrice = isnull(@numAvgCostPrice,0)
	 set @numHeaderQty = isnull(@numHeaderQty,0)
	 set @numHeaderCostPrice = isnull(@numHeaderCostPrice, 0)
	 set @numDetailCostPrice = isnull(@numDetailCostPrice,0)
	 set @numDetailQty = isnull(@numDetailQty,0)
	If @numDetailCostPrice >= 0  AND @numHeaderQty + @numDetailQty<>0
	begin
		set @numAvgCostPrice = (  (@numHeaderQty * @numHeaderCostPrice) + @numDetailCostPrice  ) /
							(@numHeaderQty + @numDetailQty)
	end
	else if @numHeaderQty >0
	begin
		set @numAvgCostPrice = @numHeaderCostPrice
	end
	else if @numDetailQty <>0
	begin
		set @numAvgCostPrice =  @numDetailCostPrice/@numDetailQty
	end
	set @numOldCostPrice = 0.0
	
	select @numOldCostPrice = isnull(itemRate,0) from aItem where Itemid = @intItemId
-- update Cost price in aHqMergingHeader
	UPDATE aHqMergingHeader  SET mghItemCostPrice = @numAvgCostPrice, mghOldCostPrice = @numOldCostPrice
	WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
	if @numAvgCostPrice=0
	begin
		set @numAvgCostPrice =@numOldCostPrice
	end
-- update cost price in aItem
	UPDATE aItem SET ItemRate = @numAvgCostPrice WHERE ItemId = @intItemId
	
	if  @numOldCostPrice <> @numAvgCostPrice
	Begin
		Update losShopItemShipmentDetail set pricechanged = 1 where Itemid = @intItemId
	End
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpEOQProcessing]    Script Date: 10/06/2012 14:17: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].[SpEOQProcessing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified By : Hariharan
-- Modified Date: 29/09/2004
--Exec SpEOQProcessing 1,1,''20040101'',''20041231'',''20040101'',''20041231'',1,0,1
-- Code GIven for converting the ordering cost to Department Currency
CREATE proc [dbo].[SpEOQProcessing]
(
@intcompanyid integer,@intdepartmentid as integer,
@strPurchaseFrom varchar(20),
@strPurchaseTo varchar(20),
@strSalesFrom varchar(20),
@strSalesTo varchar(20),
@intprocessid integer,
@intcategoryid integer = 0 ,
@intsave integer =0
)
as
begin
set nocount on
set ansi_warnings off
declare
@strcondition as varchar(2000),
@strsql as nvarchar(4000),
@strshopid as varchar(500),
@strcreate as varchar(1000)
Create table #TempEoq
(
FixedCostId int,
companyid int,
departmentid int,
ItemCategoryid  int,
itemid   int,
fixedcost numeric(18,4),
orderingcost numeric(18,8),
Demandqty  numeric(18,4),
Reorderqty  numeric(18,4),
Type Char(1))
Create table #TempEOQFinal
(
FixedCostId int,
companyid int,
departmentid int,
ItemCategoryid  int,
itemid   int,
fixedcost numeric(18,4),
orderingcost numeric(18,8),
Demandqty  numeric(18,4),
Reorderqty  numeric(18,4),
Type Char(1))
Declare @intInvCurrId as int, @intDepCurrId as int, @numExchangeRate as numeric(18,8)
Select @intInvCurrId = m.CurrencyId from aPackageSettings a, aAccountMaster m where
a.InventoryId = m.AccountId and a.CompanyId = m.CompanyId and a.COmpanyId = @intCompanyId
Select @intDepCurrId = depCurrencyId from aDepartmentMaster where DepartmentId =
@intDepartmentID  and CompanyId =   @intCompanyID
exec spGetExchangeRate @intCompanyId, @intInvCurrId, @intDepCurrId, @numExchangeRate OUTPUT
set @strcondition =''''
if @intdepartmentid >0
set  @strCondition = '' and fixedcostdepartmentid= ''+ convert(varchar(2), @intdepartmentid)
if @intcategoryid>0
set  @strCondition = @strcondition + '' and dFixedCostCategoryId= ''+ convert(varchar(2), @intcategoryid)
set @strsql =''Insert into  #TempEoq
select FixedCostId, fixedcostCompanyid,FixedCostDepartmentid,
dFixedCostCategoryId,dFixedCostItemId,dFixedCostValue,0.0,0.0,0.0, '''''' + ''I'' + ''''''
from loafixedcostheader ch,loafixedcostdetail cd where
ch.fixedcostid=cd.dFixedCostId and
ch.fixedcostcompanyid=cd.dfixedcompanyid and
cd.dFixedCostItemId>0 and dFixedCostValue<>0 '' + @strCondition
exec sp_executesql @strsql
set @strsql = ''Insert into  #TempEoq
select FixedCostId, fixedcostCompanyid,FixedCostDepartmentid,
dFixedCostCategoryId,ItemId,dFixedCostValue,0.0,0.0,0.0, '''''' + ''C''+ ''''''
from loafixedcostheader ch, loafixedcostdetail cd, aitem where
ch.fixedcostid=cd.dFixedCostId and
ch.fixedcostcompanyid=cd.dfixedcompanyid and
cd.dFixedCostItemId = 0 and dFixedCostValue<>0 and cd.dFixedCostCategoryId =
aitem.ItemCategoryID '' + @strCondition
exec sp_executesql @strsql
Delete from #TempEoq where #TempEoq.ItemId =
(Select a.ItemId from #TempEoq a where #TempEoq.ItemId =
a.ItemId and #TempEoq.FixedCostId = a.FixedCostId and
a.Type =''I'' Group By a.ItemId) and #TempEoq.Type =''C''
Insert #TempEOQFinal
Select a.*  from #TempEoq a where a.fixedCostId = (Select max(FixedCostId) from
#TempEoq b where a.ItemId = b.ItemID)
set @strshopid=''''
if @intdepartmentid >0
select @strshopid =@strshopid +case when @strshopid <>'''' then '','' else '''' end + convert(varchar(3),shopid)  from ashops where departmentid = @intdepartmentid
else
select @strshopid =@strshopid +case when @strshopid <>'''' then '','' else '''' end + convert(varchar(3),shopid)  from ashops where departmentid > @intdepartmentid
set @strsql = ''update #TempEOQFinal set Demandqty=qty from (
select posditemid,sum(posdquantity)qty from vwShopItemsales
where poshBilldate > =''''''+ @strsalesFrom  +
'''''' and poshBilldate<=''''''+ @strsalesTo + '''''''' + ''and  poshShopID in (''+@strshopid+ '')
group by posditemid)a
where #TempEOQFinal.itemid=a.posditemid ''
exec sp_executesql @strsql
set @strcondition=''''
if @intdepartmentid > 0
set @strcondition ='' and chDepartmentID =''+ convert(varchar(2), @intdepartmentid)
set @strsql = ''update #TempEOQFinal  set orderingcost = a.costprice from(
Select CdItemId, cdCostingPrice costprice, UpdateTime from loaCostingDetail cd,
loaCostingHeader ch where cdCostingId = chCostingId and ChCancelled = 0
and chCostingId = (Select  max(ChCostingId) from loaCostingHeader ch1,
loaCostingDetail cd1 where ch1.chCostingId = cd1.cdCostingId and ch1.ChCancelled = 0
and cd1.cdItemId = cd.cdItemId and chCostingDate >='''''' + @strPurchaseFrom +
'''''' and chCostingDate <= ''''''+ @strPurchaseto +''''''''+ @strcondition +
''))a where a.cdItemID =  #TempEOQFinal.itemid and orderingcost=0 ''
exec sp_executesql @strsql
set @strsql = ''update #TempEOQFinal  set orderingcost = a.costprice from (
Select CdItemId, cdCostingPrice costprice, UpdateTime from loaCostingDetail cd,
loaCostingHeader ch where cdCostingId = chCostingId and ChCancelled = 0
and chCostingId = (Select  max(ChCostingId) from loaCostingHeader ch1,
loaCostingDetail cd1 where ch1.chCostingId = cd1.cdCostingId
and cd1.cdItemId = cd.cdItemId and chCostingDate <='''''' + @strPurchaseFrom +''''''''+
+ @strcondition + ''))a where a.cdItemID = #TempEOQFinal.itemid and orderingcost=0 ''
exec sp_executesql @strsql
set @strsql = ''update #TempEOQFinal  set orderingcost = a.costprice from (
Select CdItemId, cdCostingPrice costprice, UpdateTime from loaCostingDetail cd,
loaCostingHeader ch where cdCostingId = chCostingId and ChCancelled = 0
and chCostingId = 0 ) a where a.cdItemID = #TempEOQFinal.itemid and orderingcost=0 ''
exec sp_executesql @strsql
set @strsql = ''update #TempEOQFinal set orderingcost = costprice from(
select ItemID, ItemRate costprice  from aitem) a
where a.itemid = #TempEOQFinal.itemid and orderingcost=0 ''
exec sp_executesql @strsql
Update #TempEOQFinal set orderingcost = orderingcost * @numExchangeRate
set @strsql = ''update #TempEOQFinal set Reorderqty = SqRt((2 * orderingcost * Demandqty)/fixedcost)''
exec sp_executesql @strsql
set @strsql =''select x.*,cate.CategoryNameDescription,
isnull(a.ItemDescription,'''''''')itemdesc
from aitemcategory cate,#TempEOQFinal x left outer join aitem a
on x.itemid = a.itemid where cate.ItemCategoryID=x.ItemCategoryid''
exec sp_executesql @strsql
if @intsave = 1
Begin
SET @STRSQL = ''insert into  loaeoqprocessdetail
SELECT ''+ Convert(varchar(2),@intprocessid) + '',ItemCategoryid, itemid,
fixedcost, Reorderqty from #TempEOQFinal ''
exec sp_executesql @strsql
--Updating the EOQ to the ShopItemDetail table
Update aShopItemDetail set ReorderQuantity = EoqdReorderQty
from loaEoqProcessDetail Where EodItemId = itemid and
shopid in (Select shopid from aShops where Departmentid = @intdepartmentid)
and EoqDProcessId = @intprocessid
End
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPLdep]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLdep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 1/03/2004, 15/04/2004, 27/04/2004, 13/07/2004, 03/08/2004, 09/08/2004 ,,04/06/2010
-- Modified by   : Hariharan, Hariharan R  ,jyothish
-- comments   : included level (30/05/03)
--               : used spopeningbalance for getting the opening balances
--                 (On comparison with v2) (13/06/2003)
--               : removed account head filteration deptwise (25/08/2003)
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : given consolidation paramter 261203 venki
--   : Removed Cursor and looping to get report fast.
--   : CORRECTED filtering criteria
-----------------------------------------------------------------------------------------
-----  ref1:previous month has to be added in the report
--exec spPLdep ''20090101'',''20091231'',1,18,0
create PROCEDURE [dbo].[spPLdep] (@strFROMDate as varchar(10),
@strToDate as varchar(10),
@intCompanyID as int,
@intdepartmentid as int,
@bitcons as bit,
@intlevel as int = 0,
@intconsolidation as int =0 ) AS
Begin
set nocount on
Set ansi_warnings off
Declare @AcCode as varchar(100),
@strFROMDateBeforeOneMonth as varchar(100),
@strFROMDateToOneMonth as varchar(100),
@AcID as int,
@AccDesc as varchar(100),
@GroupId as int,
@CompanyName as varchar(100),
@dtFROMDate as datetime,
@dtToDate as datetime,
@dtfinstartdate as datetime,
@AccountOBCr as numeric(18,2),
@AccountOBDr as numeric(18,2),
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intRecCount as int,
@intFromFinId as int,
@intLastFinId as int,
@intCount as int
---ref-1
set  @strFROMDateBeforeOneMonth=DateAdd(month,-1,@strFROMDate)
set  @strFROMDateToOneMonth=DateAdd (day, -1 ,@strFROMDate)
---ref-1
Create table #PL(
CompanyID int,
AcID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CrEDitAmt numeric(18,2),
ParentGroupID int,
DepartmentId int,DebitAmtMonthBefore numeric(18,2),
CreditAmtMonthBefore numeric(18,2))  --ref-1 DebitAmtMonthBefore,CreditAmtMonthBefore added
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup Int)
Create table #vwJournalDetails_Month(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup Int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #Tempjournalheader_Month
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
orderno int, levelcode int, departmentid int,
DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #PLFinal(
CompanyID int,
AccCode varchar(100),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
AcId int, DepartmentId int, orderno int,
levelcode int,
Checked int,
ParentGroupId int,DebitAmtMonthBefore numeric(18,2),
CreditAmtMonthBefore numeric(18,2))
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
SELECT @dtFROMDate = convert(datetime, @strFromDate)
SELECT @dtToDate = convert(datetime, @strToDate)
select @intFromFinId = FinancialId from vwfinyearperiod where companyid = @intcompanyid and
@strFROMDate between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFromFinId
if @intLastFinId = 0
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
---ref1
insert #Tempjournalheader_Month
Select H.* from moajournalheader h (nolock) where journaldate>=@strFROMDateBeforeOneMonth
and JournalDate <=@strFROMDateToOneMonth  and h.CompanyId = @intCompanyId
-----
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
--ref1
insert #vwJournalDetails_Month
Select d.* from #Tempjournalheader_Month  h, vwJournalDetails d (nolock) where
Journaldate>=@strFROMDateBeforeOneMonth and
JournalDate <=@strFROMDateToOneMonth and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
---
Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName , OBDr ,
OBCr , DebitAmt , CrEDitAmt , ParentGroupID , DepartmentId )
SELECT GrpAcId.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GrpAcId.GroupID, GrpAcId.GroupDesc,
0, 0, 0, 0, ParentGroupID, departmentid  from
(SELECT AM.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
GM.GroupDesc, 0 OpDebit, 0 OpCredit, 0 Debit, 0 Credit, ParentGroupID,
daDepartmentid departmentid
FROM aAccountMaster AM,
aGroupMaster GM, adeptAccounts d, #SubDepts1 dep
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'') AND
GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
and am.Accountid = d.daAccountId and am.CompanyId = d.daCompanyId
AND d.dadepartmentid = dep.deptid
Union
SELECT AM.Companyid, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID, GM.GroupDesc,
0, 0, 0, 0, ParentGroupID, deptid departmentid FROM
aAccountMaster AM, aGroupMaster GM, vwGlobalAccounts d, #SubDepts1 dep
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'') AND
GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId
group by GrpAcId.Companyid, GrpAcId.AccountID, GrpAcId.GroupID, GrpAcId.GroupDesc,
GrpAcId.AccountCode, GrpAcId.AccountDesc, GrpAcId.AccountType, GrpAcId.ParentGroupID,
GrpAcId.GroupID, GrpAcId.GroupDesc, OpDebit, OpCredit, Debit, Credit,
ParentGroupID, departmentid
Update #PL set OBDr = abs(opening.Openingamount) from (Select AccountId,
DepartmentId, CompanyId,
case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #PL.AcId and opening.DepartmentId = #PL.DepartmentId
and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
and ((#PL.ACType = ''E''  and opening.Openingamount >0) or (#PL.ACType = ''I''  and
opening.Openingamount <0))
Update #PL set OBCr = abs(opening.Openingamount) from (Select AccountId,
DepartmentId, CompanyId, case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount
from aaccountfinyearopening where Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #PL.AcId and opening.DepartmentId = #PL.DepartmentId
and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
and ((#PL.ACType = ''E''  and opening.Openingamount <0) or (#PL.ACType = ''I''  and
opening.Openingamount >0))
Update #PL set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.DepartmentId = #PL.DepartmentId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #PL set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId and
trialDeb.DepartmentId = #PL.DepartmentId and trialDeb.CompanyId = #PL.CompanyID
and trialDeb.CompanyId = @intCompanyId
Update #PL set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.DepartmentId = #PL.DepartmentId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #PL set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and
trialDeb.DepartmentId = #PL.DepartmentId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
-------------------------------------------ref1-------------------------------------------
Update #PL set DebitAmtMonthBefore = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails_Month v, #Tempjournalheader_Month h
where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
and h.JournalDate >= @strFROMDateBeforeOneMonth and h.JournalDate <= @strFROMDateToOneMonth
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and trialDeb.DepartmentId = #PL.DepartmentId
and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
Update #PL set CreditAmtMonthBefore = trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId,
case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails_Month v, #Tempjournalheader_Month h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @strFROMDateBeforeOneMonth and h.JournalDate <= @strFROMDateToOneMonth
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #PL.AcId and
trialDeb.DepartmentId = #PL.DepartmentId
-------------------------------------------------------------------------------------------
--  SELECT * FROM #PL
--   where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
--   order by groupid, acid
if @intConsolidation = 0
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked,
AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
End
Else
Begin
Insert #FilteredResult(groupid , AccountCode ,
AccountDesc , groupdesc , parentGroupid ,
orderno , levelcode , departmentid , DepartmentName, Checked,
AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, 0
End
Insert #PLFinal(CompanyID, AccCode, AccDesc, AcType, GroupID, GroupName, OBDr,
OBCr, DebitAmt, CreditAmt, AcId, DepartmentId, orderno, levelcode, Checked
, ParentGroupId,DebitAmtMonthBefore,CreditAmtMonthBefore)
SELECT b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, sum(b.OBDr),
sum(b.OBCr), sum(b.DebitAmt), sum(b.CreditAmt), b.AcId, min(r.DepartmentId),
r.OrderNo, r.LevelCode, 0,  r.ParentGroupId ,sum(b.DebitAmtMonthBefore),sum(b.CreditAmtMonthBefore )
from #FilteredResult r
left outer join #PL b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AcId and r.AccountId is not null))
group by b.CompanyId, r.OrderNo,r.LevelCode, r.AccType, r.GroupId, r.GroupDesc,
b.AcId, b.AccCode, b.AccDesc,  r.ParentGroupId
HAVING
((((((sum(isnull(creditamt,0)) - sum(isnull(debitamt,0))) <> 0 or
(sum(isnull(obcr,0)) - sum(isnull(obdr,0))) <> 0) and isnull(r.AccType ,'''') =''I'')
or (((sum(isnull(debitamt,0)) - sum(isnull(creditamt,0))) <> 0 or
(sum(isnull(obdr,0)) - sum(isnull(obcr,0))) <> 0) and isnull(r.AccType ,'''') =''E'')
) and b.accCode is not null) or b.accCode is null)  order by r.orderno
set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
Order by OrderNo Desc
While @GroupID <>0
Begin
set @intCount = 0
Select @intCount = count(*) from #plFinal where
((AccDesc is not Null and Groupid= @GroupID)
or ParentGroupid = @GroupID)
if @intCount = 0
Delete from #plFinal where GroupId = @GroupID
else
Update #plFinal set Checked = 1 where Groupid = @GroupID
Set @GroupID  = 0
Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
Order by OrderNo Desc
End
Set @GroupID  = 0
if @intLevel>0
Delete from #plFinal where LevelCode >= @intLevel and AcId is null
Select CompanyID,AccCode,AccDesc,AcType,GroupID,
GroupName,OBDr,OBCr,DebitAmt,CreditAmt,AcId,
DepartmentId,orderno,levelcode,Checked,ParentGroupId,
isnull(DebitAmtMonthBefore,0)DebitAmtMonthBefore ,isnull(CreditAmtMonthBefore,0)CreditAmtMonthBefore from #plFinal
order by OrderNo
Drop Table #SubDepts1
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
drop table #plFinal
drop table #FilteredResult
drop table #PL
drop table #Tempjournalheader_Month
Drop Table #vwJournalDetails_Month
set nocount on
Set ansi_warnings on
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPopulateHpInterestDetails]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPopulateHpInterestDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by: Nidheesh P V
--Created on: 18/07/2010
--Comments: To populate interest details for hp cheques
-----------------------------------------------------------------------------
--Modified by: Nidheesh P V
--Modified on: 18/07/2010
--Comments: added isnull condition
--Reference : RefNo-1
-----------------------------------------------------------------------------
--spPopulateHpInterestDetails 2,1,168,''20100808''
CREATE proc [dbo].[spPopulateHpInterestDetails]
(
@DepartmentID as int,
@CompanyID as int,
@ProcessId as int,
@AsonDate as datetime
)
as
declare @Nrcptdate as datetime
declare @NproId as int
declare @NProDetId as int
declare @NDepId as int
declare @NChqDate as datetime
declare @NCustId as int
declare @IntrstDate as datetime
declare @Count as int
declare @MaxProDetId as int
declare @TempVar table
(
ChequeDate datetime,
SettledDate datetime,
ProcessId int,
ProcessDetailId int,
Performer char(1),
PendingChequCount int,
InterestDate datetime,
DepId int
)
begin
set nocount on
declare newcurs cursor for
select distinct hprhReceiptDate,hpdChequeDate,hphProcessingId,hprdProcessingDetailId,hpdDepartmentID,hphCustomerID
from ahpprocessingdetail inner join ahpprocessingheader h
on hpdProcessingId=hphProcessingId and hpdDepartmentID=hphDepartmentID and hpdCompanyID=hphCompanyID and hphProcessingId=@ProcessId
and (hphDepartmentID=@DepartmentID or @DepartmentID=0)
inner join vwhpSettlementDetails v
on hpdDetailID=hprdProcessingDetailId and hpdCompanyID=hprhCompanyID and hpdDepartmentID=DepartmentID
and (hpdDepartmentID=@DepartmentID or @DepartmentID=0)
and ((isnull(hphreprocessaftersettlement,0)=0 and v.hprdProcessingId=h.hphProcessingId)or(hphreprocessaftersettlement=1 and v.hprdProcessingId=h.hphReferenceID))
where isnull(hpdPosted,0)=0 and hphCancel=0 and hphAmended=0 and hpdChequedate<=@AsonDate and hpdCompanyID=@CompanyID
--and hphProcessingId=642  RefNo-1
order by hphProcessingId,hprdProcessingDetailId
open newcurs
fetch next from newcurs into @Nrcptdate,@NChqDate,@NproId,@NProDetId,@NDepId,@NCustId
while @@fetch_status=0
begin
set @Count=(select count(*) from ahpprocessingdetail where hpdProcessingId=@NproId
and  hpdChequeDate<=@Nrcptdate and hpdDetailID>=@NProDetId and hpdDepartmentID=@NDepId)
select @MaxProDetId=max(hprdProcessingDetailId) from vwhpSettlementDetails where hprdProcessingId=@NproId
and DepartmentID=@NDepId and hprhCompanyID=@CompanyID and DepartmentID=@NDepId
------If count>=3 then the customer will be non performer------
------but Interset for the first 3 cheque should be posted as in Chequedate----
if @Count>=3
begin
if @NProDetId>3
begin
insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,''N'',@Count,@Nrcptdate,@NDepId)
end
else
begin
insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,''P'',@Count,@NChqDate,@NDepId)
end
end
else
begin
insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,''P'',@Count,@NChqDate,@NDepId)
end
if @MaxProDetId=@NProDetId
begin
if (select Performer from @TempVar where ProcessId=@NproId and ProcessDetailId=@NProDetId and DepId=@NDepId)=''P''
begin
if (select count(*) from aHPCustomerPerfomance where hpProcessingID=@NproId)>0
begin
delete from aHPCustomerPerfomance where hpProcessingID=@NproId
end
end
else
begin
if (select count(*) from aHPCustomerPerfomance where hpProcessingID=@NproId)<0
begin
insert into aHPCustomerPerfomance values(@NCustId,@NproId)
end
end
end
fetch next from newcurs into @Nrcptdate,@NChqDate,@NproId,@NProDetId,@NDepId,@NCustId
end
close newcurs
deallocate newcurs
select  hphProcessingNo + ''-''+ cast(hpdDetailID as nvarchar)RefNo,hpCustName,
ChequeDate,SettledDate,ProcessId,ProcessDetailId,Performer,InterestDate,hpdInterest
from @TempVar left outer join
ahpprocessingdetail inner join ahpprocessingheader on hphDepartmentID=hpdDepartmentID
and hphProcessingID=hpdProcessingID and hphCompanyID=hpdCompanyID
and hphCancel=0 and hphCompanyID=@CompanyID and hphAmended=0 and (hpdDepartmentID=@DepartmentID or @DepartmentID=0)
on ProcessId=hpdProcessingId and ProcessDetailId=hpdDetailID and DepId=hphDepartmentID
left outer join losHpCustomerDetails on hphCustomerID=hpCustID and hpCompanyID=hphCompanyID
order by ProcessId,ProcessDetailId
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[machinerepairegister]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[machinerepairegister]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[machinerepairegister] as
select c.customername,serCallBkhCallType ,serinvhprocdate,serinvhduedate,
seaAppDate  from losservicebookingheader bh inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid and
bh.serbookhshopid=los.serCallBkhshopid
left outer join losserviceheader sh on bh.serbookhid = sh.serinvhbookingid and
bh.serbookhshopid = sh.serinvhshopid and bh.serbookhcompanyid = sh.serinvhcompanyid
inner join losserestimateapproval ap on ap.seaAppbookingId=sh.serinvhbookingid and
seaAppShopId= sh.serinvhshopid and seaAppcompanyID=sh.serinvhcompanyid
inner join losserviceinvheader li on  li.serinvhjobcardid=sh.serinvhid and li.serinvhshopid=sh.serinvhshopid
and li.serinvhcompanyid=sh.serinvhcompanyid left outer join
acustomermaster c on li.serinvhCustomerId= c.customerid
and li.serinvhcompanyid = c.companyid ,
ashops s, aitem a, vwitemdescription v where
los.sercallbkhitemid = a.itemid and a.itemid = v.itemid and bh.serbookhshopid = s.shopid
-------------------------'
GO
/****** Object:  View [dbo].[vwGodownExpirywiseStock]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExpirywiseStock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGodownExpirywiseStock    Script Date: 18/01/2003 9:45:35 PM ******/
--Created By   : Hariharan
--Created Date : 26/12/2002
CREATE view [dbo].[vwGodownExpirywiseStock] as
select godownname, eadgodownid, eaditemid, ItemDescription, Code, eadexpirydate,
sum(Stock ) Stock from
(select godownname, eadgodownid, eaditemid, ItemDescription, Code, eadexpirydate,
eaditemqty Stock from loiexpiryarrivaldetails ad,
vwitemdescription vw, agodown g
where ad.eaditemid = vw.itemid and eadgodownid = g.godownid
union all
select godownname, eidgodownid, eiditemid, ItemDescription, Code, eidexpirydate,
eiditemqty Stock from loiexpiryIssuedetails ad,
vwitemdescription vw, agodown g where ad.eiditemid = vw.itemid  and
eidgodownid = g.godownid ) Expirystock group by
godownname, eadgodownid, eaditemid, itemDescription,  Code, eadexpirydate'
GO
/****** Object:  View [dbo].[vwGodownExpiryAlertItems]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownExpiryAlertItems]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------
-- Created by	: Kishore
-- Created on	: 10/08/2003
-- Comments	: This view lists items in stock which expire within
--                ExpiryNoOfDays (in aItem) from package date. Typically
--		  used to display alerts
-------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwGodownExpiryAlertItems] AS
SELECT b.GodownId, b.itemid, vw.Code ItemCode, vw.ItemDescription,
b.ExpiryDate, b.qty Stock, vw.vwActive --, p.PackageDate, i.ExpiryNoOfDays, b.ExpiryDate
FROM (SELECT ExpiryDate, GodownId,  ItemId, SUM(qty) qty
	FROM (SELECT eadExpiryDate ExpiryDate,  eadGodownId GodownId,
		eadItemId ItemId , SUM(eadItemQty) qty
		FROM loiExpiryArrivalDetails
		WHERE eadCancel = 0
		GROUP BY eadExpiryDate, eadGodownId, eadItemId
		UNION ALL
		SELECT eidExpiryDate, eidGodownId, eidItemId, - SUM(eidItemQty)
		FROM loiExpiryIssueDetails
		WHERE eidCancel = 0
		GROUP BY eidExpiryDate, eidGodownId, eidItemId) a
	GROUP BY ExpiryDate, ItemId, GodownId
	HAVING SUM(qty) <> 0 ) b,
vwItemDescription vw, aItem i, aPackageSettings p
WHERE b.ItemId = vw.ItemId
AND vw.ItemId = i.ItemId
AND p.PackageDate + i.ExpiryNoOfDays >= b.ExpiryDate
------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwGetWarntyDtlsForReplacedItem]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGetWarntyDtlsForReplacedItem]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwGetWarntyDtlsForReplacedItem]
as
select sbk.serCallBkhid BookingID,sbk.serCallBkhno BookingNo,sbk.serCallBkhitemid ItemId,sbk.serCallBkhSerialNo OldItemSlNo,
Invprlcd.repinvdpartsid ReplacedItem, Invprlcd.repinvdserialno ReplacedSlNo
from
losInvoicedPartsReplacedetails Invprlcd inner join
losserviceinvheader InvH on Invprlcd.repinvinvoiceid=InvH.serinvhid and Invprlcd.repinvdshopid=
InvH.serinvhshopid
inner join losserviceheader lsh on lsh.serinvhid=InvH.serinvhjobcardid and InvH.serinvhshopid=lsh.serinvhshopid
inner join loscallbookingheader sbk on lsh.serinvhbookingid=sbk.serCallBkhid and lsh.serinvhshopid=sbk.serCallBkhshopid'
GO
/****** Object:  View [dbo].[TestView_2]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TestView_2]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TestView_2] as
select   posditemid, ItemDescription,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) cUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) dUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) posdUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshExchangeRate) cActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshDepExRate) dActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice)) posdActualUnitPrice,
posdquantity,posdRateType, poshBilldate,poshbillID,
poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,
posdcostprice * poshExchangeRate ccostprice, ''S'' as type,
((posdUnitPrice / posdquantity) - posdcostprice) margin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount
from
losposdetail, losposheader, aitem
where
poshBillid = posdBillid and
ItemID=posditemid and
poshShopid = posdshopid AND POSHCANCELLED = 0 and (poshbilldate between ''2008/08/30'' and ''2008/11/01'')'
GO
/****** Object:  StoredProcedure [dbo].[spPLBudget]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLBudget]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by   : Aneesh
-----------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spPLBudget]
		(@strFromDate As VarChar(10),
		 @strToDate As VarChar(10),
		 @IntCompanyID As Int,
		 @Intlevel As Int =0) As
Begin
Set Nocount On
Set ansi_warnings Off
Declare @AcCode As VarChar(100),
	@AcID 		As Int,
	@AccDesc 	As VarChar(100),
	@GroupId 	As Int,
	@CompanyName 	As VarChar(100),
	@dtFromDate 	As Datetime,
	@dtToDate 	As Datetime,
	@dtfinstartdate As Datetime,
	@AccountOBCr 	As Numeric(18,2),
	@AccountOBDr 		As Numeric(18,2),
	@dtPrevFinUnclosedSDate As Datetime,
	@dtLAstFinUnclosedEDate As Datetime,
	@IntRecCount 	As Int,
	@IntFromFinId	As Int,
	@IntLAstFinId 	As Int,
	@IntCount 	As Int
Create Table #PL
	(CompanyID 	Int,
	AcID 		Int,
	AccCode 	VarChar(100),
	AccDesc 	VarChar(100),
	AcType 		VarChar(1),
	GroupID 	Int,
	GroupName 	VarChar(100),
	OBDr 		Numeric(18,2),
	OBCr 		Numeric(18,2),
	DeBitAmt 	Numeric(18,2),
	CrEDitAmt 	Numeric(18,2),
prvDeBitAmt 	Numeric(18,2),
prvCreditAmt 	Numeric(18,2),
BudgetBal 	Numeric(18,2),
	ParentGroupID 	Int)
Create Table #vwJournalDetails
	(companyid 	Int,
	journalid	Int,
	journaldetailid	Int,
	journalcredit	Bit,
	accountid	Int,
	Amount		Numeric(18,2),
	ActualAmount	Numeric(18,2),
	departmentid	Int,
	depamount	Numeric(18,2),
	PostGroup 	Int)
Create Table #Tempjournalheader
	(JournalID	Int,
	CompanyID	Int,
	JournalDate	SmallDatetime,
	ReferenceNo	VarChar(100),
	Remarks		VarChar(250),
	Type		Char(10),
	Cancel		Bit,
	Realised	Bit,
	CurrencyId	Int,
	FinancialID	Int,
	chequedate	Datetime,
	upDatetime	Datetime,
	bankdate	Datetime)
Create Table #FilteredResult
	(groupid 	Int ,
	AccountCode 	VarChar(50),
	AccountDesc 	VarChar(100),
	groupdesc 	VarChar(100),
	parentGroupid 	Int,
	orderno 	Int,
	levelcode 	Int,
	departmentid 	Int,
	DepartmentName 	VarChar(50),
	Checked 	Int,
	AccountId 	Int,
	AccType 	VarChar(50))
Create Table #PLFinal
	(CompanyID 	Int,
	AccCode 	VarChar(100),
	AcDesc 		VarChar(100),
	AcType 		VarChar(1),
	GroupID 	Int,
	GroupName 	VarChar(100),
	OBDr 		Numeric(18,2),
	OBCr 		Numeric(18,2),
	DeBitAmt 	Numeric(18,2),
	CreditAmt 	Numeric(18,2),
	prvDeBitAmt 	Numeric(18,2),
prvCreditAmt 	Numeric(18,2),
BudgetBal 	Numeric(18,2),
	AcId 		Int,
	DepartmentId 	Int,
	orderno 	Int,
	levelcode 	Int,
	Checked 	Int,
	ParentGroupId 	Int)
Select @dtFromDate = Convert(Datetime, @strFromDate)
Select @dtToDate = Convert(Datetime, @strToDate)
Select @IntFromFinId = FinancialId From vwfinyearperiod Where companyid = @Intcompanyid And
@strFromDate between sdate And edate
Select @dtLAstFinUnclosedEDate = Dateadd(dd, -1, @dtFromDate )
Select @IntLAstFinId = Max(FinancialId) From aAccountFinYearOpening
Where CompanyId = @IntCompanyId And FinancialId <= @IntFromFinId
If @IntLAstFinId = 0
	Select 	@dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
	Where financialid = (Select Min(financialid) From afinancialyear Where
	companyid = @IntCompanyId) And CompanyId= @IntCompanyId
Else
	Select 	@dtPrevFinUnclosedSDate = sdate From vwFinYearPeriod
	Where financialid = @IntLAstFinId And CompanyId= @IntCompanyId
	Insert #Tempjournalheader
	Select H.* From moajournalheader h (nolock) Where journaldate>=@dtPrevFinUnclosedSDate
	And JournalDate <=@dtToDate And h.CompanyId = @IntCompanyId
	Insert #vwJournalDetails
	Select d.* From #Tempjournalheader h, vwJournalDetails d (nolock) Where
	Journaldate>=@dtPrevFinUnclosedSDate And
	JournalDate <=@dtToDate And h.JournalId = d.JournalId And h.CompanyId = d.CompanyId
	And h.Cancel = 0 And h.CompanyId = @IntCompanyId
	Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName , OBDr ,
	OBCr , DeBitAmt , CrEDitAmt , ParentGroupID )
	Select AM.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
	GM.GroupDesc, 0 OpDeBit, 0 OpCredit, 0 DeBit, 0 Credit, ParentGroupID From
	aAccountMAster AM, aGroupMAster GM
	Where GM.GroupID = AM.GroupID And (GM.AccountType = ''I'' Or GM.AccountType = ''E'') And
	GM.CompanyID = am.companyid And AM.CompanyID = @IntCompanyID
	Update #PL Set OBDr = Abs(opening.Openingamount) From (Select AccountId,
	CompanyId, Sum(Openingamount) Openingamount From aaccountfinyearopening Where
	Financialid = @IntLAstFinId And CompanyId = @IntCompanyId Group By CompanyId, AccountId) opening Where
	opening.Accountid = #PL.AcId And opening.CompanyId = #PL.CompanyID And
	opening.CompanyId = @IntCompanyId And
	((#PL.ACType = ''E''  And opening.Openingamount >0) Or (#PL.ACType = ''I''  And
	opening.Openingamount <0))
	Update #PL Set OBCr = Abs(opening.Openingamount) From (Select AccountId,
	CompanyId, Sum(Openingamount) Openingamount
	From aaccountfinyearopening Where Financialid = @IntLAstFinId And
	CompanyId = @IntCompanyId Group By AccountId, CompanyId) opening Where
	opening.Accountid = #PL.AcId And opening.CompanyId = #PL.CompanyID And opening.CompanyId = @IntCompanyId
	And ((#PL.ACType = ''E''  And opening.Openingamount <0) Or (#PL.ACType = ''I''  And
	opening.Openingamount >0))
	Update #PL Set OBDr = OBDr + IsNull(trialDeb.amount,0) From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From #vwJournalDetails v, #TempJournalHeader h
	Where v.JournalCredit = 0 And h.JournalId = v.JournalId And h.CompanyId = v.CompanyId
	And h.JournalDate >= @dtPrevFinUnclosedSDate And h.JournalDate <= @dtLAstFinUnclosedEDate
	Group By v.AccountId, v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId
	And trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
	Update #PL Set OBCr = OBCr + IsNull(trialDeb.amount,0) From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From #vwJournalDetails v ,
	#TempJournalHeader h Where v.JournalCredit = 1 And h.JournalId = v.JournalId And
	h.CompanyId = v.CompanyId And h.JournalDate >= @dtPrevFinUnclosedSDate And
	h.JournalDate <= @dtLAstFinUnclosedEDate Group By v.AccountId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId And
	trialDeb.CompanyId = #PL.CompanyID And trialDeb.CompanyId = @IntCompanyId
	Update #PL Set DeBitAmt = trialDeb.amount From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From #vwJournalDetails v,
	#TempJournalHeader h Where v.JournalCredit = 0 And h.JournalId = v.JournalId
	And h.CompanyId = v.CompanyId And h.JournalDate >= @dtFromDate And
	h.JournalDate <= @dtToDate Group By v.AccountId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId And trialDeb.CompanyId = #PL.CompanyID
	And trialDeb.CompanyId = @IntCompanyId
	Update #PL Set CreditAmt = trialDeb.amount From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From
	#vwJournalDetails v, #TempJournalHeader h Where v.JournalCredit = 1 And
	h.JournalId = v.JournalId And h.CompanyId = v.CompanyId And
	h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate
	Group By v.AccountId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId And trialDeb.CompanyId = #PL.CompanyID
	And trialDeb.CompanyId = @IntCompanyId
	
--Aneesh
	Update #PL Set prvDebitAmt = trialDeb.amount From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From #vwJournalDetails v,
	#TempJournalHeader h Where v.JournalCredit = 0 And h.JournalId = v.JournalId
	And h.CompanyId = v.CompanyId And h.JournalDate >= @dtFromDate And
	h.JournalDate <= @dtToDate Group By v.AccountId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId And trialDeb.CompanyId = #PL.CompanyID
	And trialDeb.CompanyId = @IntCompanyId
	Update #PL Set prevCreditAmt = trialDeb.amount From (Select v.AccountId,
	v.CompanyId, Sum(IsNull(v.Amount,0)) Amount From
	#vwJournalDetails v, #TempJournalHeader h Where v.JournalCredit = 1 And
	h.JournalId = v.JournalId And h.CompanyId = v.CompanyId And
	h.JournalDate >= @dtFromDate And h.JournalDate <= @dtToDate
	Group By v.AccountId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId And trialDeb.CompanyId = #PL.CompanyID
	And trialDeb.CompanyId = @IntCompanyId
	Insert #FilteredResult(groupid , AccountCode , AccountDesc , groupdesc ,
		parentGroupid , orderno , levelcode , departmentid , DepartmentName,
		Checked, AccountId, AccType) Exec SpGroupLevelOrdering @IntCompanyId, 0
--Aneesh
	Insert #plFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
		OBCr, DeBitAmt, CreditAmt,prvDebitAmt, prvCreditAmt , AcId, orderno, levelcode, Checked, ParentGroupId)
		Select b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
		b.OBCr, b.DeBitAmt, b.CreditAmt, IsNull(sum(prvDebitAmt),0),IsNull(sum(prvCreditAmt),0), b.AcId, r.OrderNo, r.LevelCode,
		0,  r.ParentGroupId From #FilteredResult r
		Left Outer Join #PL b On  ((r.GroupId = b.GroupId  And r.AccountId Is Null)
		Or (r.GroupId = b.GroupId  And r.AccountId  = b.AcId And r.AccountId is not null))
		Where ((((((IsNull(creditamt,0) - IsNull(deBitamt,0)) <> 0 Or
		(IsNull(obcr,0) - IsNull(obdr,0)) <> 0) And IsNull(r.AccType ,'''') =''I'') Or
		(((IsNull(deBitamt,0) - IsNull(creditamt,0)) <> 0 Or
		(IsNull(obdr,0) - IsNull(obcr,0)) <> 0) And IsNull(r.AccType ,'''') =''E''))
		And b.accCode is not null) Or b.accCode Is Null)  Order By r.orderno
--Aneesh
	Update #PL Set BudgetBal = IsNull(PlanBal.PlanAmt,0)  From (Select bpdBudgetHeadID,
	IsNull(Sum(bpdAmount),0) As PlanAmt From budgetplanheader bh, budgetplandetail bd Where
	bh.bphCompanyID= @intCompanyId And bh.bphcompanyid=bd.bpdcompanyid And
	bh.bphBudgetPlanID=bd.bpdBudgetPlanID And bpdrevised=0 And bphcancelled=0  And
	--bphdepartmentid = @intDepartmentid and
	bh.bphPlanYear  <= Year(@dttodate) And
	bpdMonthNo >= Month(@strFromdate) and bpdMonthNo <= Month(@dttodate) And
(bphtype =''A'' Or bphtype =''L'') Group By bpdBudgetHeadID) PlanBal
	where #PL.AccId = bpdBudgetHeadID
	Set @GroupId = 0
-- TO avoid the groups which does not have any accounts informatiOn
	Select top 1 @GroupID = GroupId From #PLFinal Where Checked = 0
	Order By OrderNo Desc
	While @GroupID <>0
	Begin
		Set @IntCount = 0
		Select @IntCount = count(*) From #PLFinal Where
		((AcDesc is not Null And Groupid= @GroupID)
		 Or ParentGroupid = @GroupID)
		If @IntCount = 0
		    Delete From #PLFinal Where GroupId = @GroupID
		Else
		    Update #PLFinal Set Checked = 1 Where Groupid = @GroupID
		Set @GroupID  = 0
		Select top 1 @GroupID = GroupId From #plFinal Where Checked = 0
		Order By OrderNo Desc
	End
	Set @GroupID  = 0
	If @IntLevel>0
	Delete From #PLFinal Where LevelCode >= @IntLevel And AcId Is Null
	Select * From #PLFinal Order By OrderNo
	
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
drop Table #PLFinal	
drop Table #PL
drop Table #FilteredResult
Set nocount On
Set ansi_warnings On
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPlannedTB]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedTB]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spPlannedTB ''20040101'',''20041231'',1,1,1,1,0
-- sptrialbalancedep ''20040101'',''20041231'',1,1,1
--select sum(bpdamount) from budgetplandetail where bpdbudgetplanid=15 and bpdbudgetheadid=536
--and bpdmonthno >3
-- Last Modified : 25/05/2004, 14/07/2004
-- Modified by   : venkitesh, Hariharan
-- Comments	 : Planned TB, verified
CREATE PROC [dbo].[spPlannedTB] (@strFromDate as varchar(10),
@strToDate as varchar(10),
@intCompanyId as int,
@intDepartmentId as int,
@bitCons as bit,
@intLevel as int = 0,
				    @intconsolidation as int =0) AS
begin
set nocount on
--    set ansi_warnings off
Declare
	@dtFROMDate as datetime,
	@dtToDate as datetime,
	@intParentGroupID int,
	@intFinId as int,
	@dtPrevFinUnclosedSDate as datetime,
	@dtLastFinUnclosedEDate as datetime,
	@intCount as int,
	@intLastFinId as int,
	@Plantodate as datetime,
	@continueplan as integer,
	@dtpackagedate as datetime,
	@strtext as nvarchar(2000),
	@strcondition as varchar(500),
	@strquery as nvarchar(2000),
	@intFrommonth as varchar(5),
	@inttomonth as  varchar(5),
	@intFromYear as  varchar(5),
	@inttoYear as  varchar(5)
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
Create table #TrialBal(
	CompanyID int,
	AccCode varchar(100),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CrEDitAmt numeric(18,2),
	OpDebit numeric(18,2),
	OpCredit Numeric(18,2),
	AccountId int,
	DepartmentId int )
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
	
Create table #DepExrate(
	departmentid int,
	ExrateDiff numeric(18,8))	
	if @intdepartmentid = 0
		set @bitcons=1	
		
create table #SubDepts1(DeptId int)
if @intDepartmentId=0
insert into #SubDepts1
select departmentid from adepartmentmaster
else
begin
if @intconsolidation=0
	    insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
end
	
	insert into #depexrate --Getting  companyrate/depcurrency for the calculation for
	select departmentid, m.Sellingrate/c.SellingRate from adepartmentmaster a,
	acurrencymaster b, ExchangeRateDetail c, ExchangeRateDetail m, acompanyMaster z		
	where a.depcurrencyid=b.currencyid and a.companyid=b.companyid and
	b.currencyid=c.currencyid and b.companyid=c.companyid
	and a.companyid = z.companyid and z.currencyid = m.CurrencyId
	and z.Companyid = m.CompanyId		
	
	select @dtpackagedate=convert(varchar,PAckageDate,120) from
	apackagesettings where companyid= @intCompanyID
	set @plantodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dttodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dtfromdate=CONVERT(DATETIME,@strfromDate) -- Plan To date
	print @dttodate
	print @plantodate
	print @dtfromdate
	if @dttodate <= @dtpackagedate 			
		set @continueplan=0
		
	else
		set @continueplan=1
	
		
--	    SELECT @dtFROMDate = convert(datetime, @strFROMDate)
--	    SELECT @dtToDate = convert(datetime, @strToDate)
		print @dtFROMDate		print @dttodate
		print @dtpackagedate
		print @continueplan
		
	Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
	select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	select @intCount = count(*) from aAccountfinyearOpening where
	CompanyId = @intCompanyId and FinancialId = @intFinId
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
	(Select Deptid from #SubDepts1)
begin
insert into #TrialBal
SELECT acc.CompanyId, acc.AccountCode, acc.AccountDesc, acc.accounttype,
acc.GroupID, acc.GroupDesc, OpDr, OpCr, Debit, Credit, OpDebit, OpCredit,
acc.AccountId, acc.Departmentid from
(SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,
GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,
am.AccountId, d.DaDepartmentid Departmentid
FROM aaccountmaster AM, aGroupMaster GM, adeptAccounts d
WHERE GM.GroupID = AM.GroupID
AND GM.CompanyID = AM.CompanyID
AND AM.CompanyID = @intcompanyid
and am.accountid = d.daAccountid
and am.companyid = d.dacompanyid
and d.daDepartmentId in  (Select DeptId from #SubDepts1) 	
union all
SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,
GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,
am.AccountId,d.DaDepartmentid Departmentid
FROM aaccountmaster AM, aGroupMaster GM, vwGlobalAccounts vg,adeptAccounts d
WHERE GM.GroupID = AM.GroupID
AND GM.CompanyID = AM.CompanyID
AND AM.CompanyID = @intcompanyid
and am.accountid = vg.AccountId
and am.companyid = vg.CompanyId
and am.accountid = d.daAccountid
and am.companyid = d.dacompanyid
and d.dadepartmentid in (select deptid from #subdepts1)) acc
group by acc.CompanyId,  acc.accounttype,   acc.GroupID, acc.GroupDesc, acc.AccountCode,
acc.AccountDesc, acc.AccountId, acc.Departmentid,	
OpDr, OpCr, Debit, Credit, OpDebit, OpCredit order by acc.accountid asc
end
	Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
	aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #TrialBal.AccountId and
	opening.DepartmentId = #TrialBal.DepartmentId
	and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
	and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
	opening.Openingamount >0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
	opening.Openingamount <0))
	Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount
	from aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #TrialBal.AccountId and
	opening.DepartmentId = #TrialBal.DepartmentId
	and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
	and (((#TrialBal.ACType = ''A'' or #TrialBal.ACType = ''E'' ) and
	opening.Openingamount <0) or ((#TrialBal.ACType = ''L'' or #TrialBal.ACType = ''I'' ) and
	opening.Openingamount >0))
	Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #TrialBal.AccountId and
	trialDeb.DepartmentId = #TrialBal.DepartmentId
	and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v , #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #TrialBal.AccountId and
	trialDeb.DepartmentId = #TrialBal.DepartmentId
	and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #TrialBal.AccountId and
	trialDeb.DepartmentId = #TrialBal.DepartmentId
	and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #TrialBal.AccountId and
	trialDeb.DepartmentId = #TrialBal.DepartmentId
	and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
-- Planned Budget Starts Here
if @continueplan=1
begin
	set @intfrommonth =month(@dtpackagedate)
	set @intfromyear  =year(@dtpackagedate)
	set @inttomonth = month(@plantodate)
	set @inttoyear    = year(@plantodate)
	-- update from packagedate to Fromdate if fromdate>packagedate
	if @dtfromdate >= @dtpackagedate
	begin
	 set @strtext = ''insert into #TrialBal
	 select acc.CompanyId, acc.AccountCode, acc.AccountDesc, b.accounttype,
	 b.GroupID, b.GroupDesc, 0 OpDr,  0 OpCr,0  Debit, 0 Credit,0 OpDebit,0  OpCredit,
	 acc.AccountId, bphDepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar , dateadd(month,1,@dtpackagedate) ,112)+'''''' and ''''''+  convert(varchar,@dtfromdate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1) group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #trialbal tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.accountid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.accountid is null''
	 exec sp_executesql  @strtext
	 set @strtext ='' bpdamount from(select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(budgplan.bpdAmount),0)bpdamount from
	 (select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
	 from  budgetplanheader, budgetplandetail
	 where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0
	 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar ,dateadd(month,1,@dtpackagedate) ,112)+'''''' and ''''''+  convert(varchar,@dtfromdate,112)
	 +  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,
	 aGroupMaster b
	 where a.companyid=b.companyid and a.groupid=b.groupid and
	 budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=a.accountid''
	-- Expense and amt >0 (ie debit)
	set @strcondition=''  and Accounttype=''''E'''' group by bphdepartmentid,bpdbudgetheadid,bphcompanyid
	having sum(budgplan.bpdAmount)>0)main
	where bpdbudgetheadid=#trialbal.AccountId and
	bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
	
	set @strquery =''update #TrialBal set OBDr=OBDr+''+@strtext+ @strcondition
	print @strquery
	exec sp_executesql  @strquery
	--	print @strquery
	--	Expesne and amt <0 (ie credit)
	--	print @strquery	
	set @strcondition= '' and Accounttype=''''E'''' group by bphdepartmentid,bpdbudgetheadid ,bphcompanyid
	having sum(budgplan.bpdAmount)<0) main where bpdbudgetheadid=#trialbal.AccountId and
	bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''			
	
	set @strquery = ''update #TrialBal set OBcr=OBcr+''+@strtext+@strcondition
	
	exec sp_executesql @strquery
	
	-- Income and amt >0 (ie credit)
	
	set @strcondition= ''  and Accounttype=''''I'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
	having sum(budgplan.bpdAmount) >0) main where  bpdbudgetheadid=#trialbal.AccountId and
	bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
	
	set @strquery = ''update #TrialBal set OBcr=OBcr+''+@strtext+@strcondition
	
	--print @strquery
	exec sp_executesql @strquery
	-- Income and amt <0 (ie Debit)
	
	set @strcondition= ''  and Accounttype=''''I'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
	having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
	bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
	
	set @strquery = ''update #TrialBal set OBDr=OBDr+''+@strtext+@strcondition
	
	--print @strquery
	exec sp_executesql @strquery
	-- Asset and amt >0 (ie debit)
	set @strcondition= ''   and Accounttype=''''A'''' group by bphdepartmentid,  bpdbudgetheadid ,bphcompanyid
having sum(budgplan.bpdAmount)>0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
	         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set OBDr=OBDr+'' +@strtext+ @strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Asset and amt <0 (ie credit)
			set @strcondition= ''   and Accounttype=''''A'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set OBcr=OBcr+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Liability and amt >0 (ie credit)
			set @strcondition= ''  and Accounttype=''''L'''' group by Budgplan.bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount) >0)  main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set OBcr=OBcr+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Liability and amt <0 (ie Debit)
			set @strcondition= '' and Accounttype=''''L'''' group by bphdepartmentid,  bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set OBDr=OBDr+''+@strtext+@strcondition
			--print @strquery
		exec sp_executesql @strquery
		
	end	
	
	if @dtfromdate <=@dtpackagedate	
		set @dtfromdate =@dtpackagedate
	 -- Updating  From date to todate planned date
	 set @strtext = ''insert into #TrialBal
	 select acc.CompanyId, acc.AccountCode, acc.AccountDesc, b.accounttype,
	 b.GroupID, b.GroupDesc, 0 OpDr,  0 OpCr,0  Debit, 0 Credit,0 OpDebit,0  OpCredit,
	 acc.AccountId, bphDepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar ,dateadd(month,1, @dtfromdate) ,112)+'''''' and ''''''+  convert(varchar,@plantodate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1) group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #trialbal tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.accountid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.accountid is null''
	exec sp_executesql  @strtext
	set @strtext ='' bpdamount from(select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(budgplan.bpdAmount),0)bpdamount from
	(select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
	from  budgetplanheader, budgetplandetail
	where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	and bpdrevised=0 and bphcancelled=0
	and cast(cast(bphPlanYear as varchar)+
	cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	+ cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar , dateadd(month,1,@dtfromdate) ,112)+'''''' and ''''''+  convert(varchar,@plantodate,112)
	+  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,
	aGroupMaster b
	where a.companyid=b.companyid and a.groupid=b.groupid and
	budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=a.accountid''
			-- Expense and amt >0 (ie debit)
			set @strcondition=''  and Accounttype=''''E'''' group by bphdepartmentid,bpdbudgetheadid,bphcompanyid
			    having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery =''update #TrialBal set DebitAmt=debitamt+''+@strtext+ @strcondition
			print @strquery
			exec sp_executesql  @strquery
--			print @strquery
			-- Expesne and amt <0 (ie credit)
			--print @strquery	
			set @strcondition= '' and Accounttype=''''E'''' group by bphdepartmentid,bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''			
			set @strquery = ''update #TrialBal set creditAmt=creditamt+''+@strtext+@strcondition
			exec sp_executesql @strquery
			-- Income and amt >0 (ie credit)
			set @strcondition= ''  and Accounttype=''''I'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount) >0) main where  bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set creditAmt=creditamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Income and amt <0 (ie Debit)
			set @strcondition= ''  and Accounttype=''''I'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set DebitAmt=debitamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Asset and amt >0 (ie debit)
			set @strcondition= ''   and Accounttype=''''A'''' group by bphdepartmentid,  bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)>0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set DebitAmt=debitamt+'' +@strtext+ @strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Asset and amt <0 (ie credit)
			set @strcondition= ''   and Accounttype=''''A'''' group by bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set creditAmt=creditamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Liability and amt >0 (ie credit)
			set @strcondition= ''  and Accounttype=''''L'''' group by Budgplan.bphdepartmentid, bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount) >0)  main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set creditAmt=creditamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Liability and amt <0 (ie Debit)
			set @strcondition= '' and Accounttype=''''L'''' group by bphdepartmentid,  bpdbudgetheadid ,bphcompanyid
			    having sum(budgplan.bpdAmount)<0) main where 	 bpdbudgetheadid=#trialbal.AccountId and
		         bphcompanyid=#trialbal.companyid and bphdepartmentid=#trialbal.departmentid''
			set @strquery = ''update #TrialBal set DebitAmt=debitamt+''+@strtext+@strcondition
			--print @strquery
		exec sp_executesql @strquery
	end		
--Insert  #LevelOrdering
--exec SpGroupLevelOrdering  @intcompanyid,@intDepartmentId
if @intdepartmentid =0
	SELECT max(CompanyID),AccCode,AccDesc,AcType,a.GroupID,
	GroupName,sum(OBDr)obdr,sum(OBCr)obcr,sum(DebitAmt)debitamt,sum(CrEDitAmt)creditamt,
	sum(OpDebit)opdebit,sum(OpCredit)opcredit,AccountId,NULL  FROM #TrialBal a
--	left outer join   #LevelOrdering b on a.groupid=b.groupid
	group by accountid,acccode,accdesc,actype,a.groupid,groupname
	Having sum(obcr)+ sum(obdr) + sum(debitamt) +sum(creditamt)>0
	--ORDER BY orderno
else
SELECT CompanyID,a.AccCode,a.AccDesc,a.AcType,a.GroupID,
a.GroupName,sum(a.OBDr)obdr,sum(a.OBCr)obcr,sum(a.DebitAmt)debitamt,sum(a.CrEDitAmt)creditamt,
sum(a.OpDebit)opdebit,sum(a.OpCredit)opcredit,a.AccountId,departmentid FROM #TrialBal  a
--   left outer join   #LevelOrdering b on a.groupid=b.groupid
group by accountid,acccode,accdesc,actype,a.groupid,groupname,companyid,departmentid
having(isnull(sum(obcr), 0)+ isnull(sum(obdr), 0) +isnull(sum(debitamt), 0) +isnull(sum(creditamt), 0)) <> 0
	
drop table #SubDepts1
drop table #vwJournalDetails
drop table #Tempjournalheader
Drop Table #TrialBal
set nocount on
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPlannedPL]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedPL]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spPlannedPL ''20040401'',''20041231'',1,1,1,4,1
-----------------------------------------------------------------------------------------
-- Last Modified : 240504, 14/07/2004
-- Modified by   : Venkitesh, Hariharan
--		 : modified to remove unwanted queries
CREATE PROCEDURE [dbo].[spPlannedPL] (@strFROMDate as varchar(10),
@strToDate as varchar(10),
@intCompanyID as int,
@intdepartmentid as int,
@bitcons as bit,
@intlevel as int = 0,
@intconsolidation as int =0 ) AS
Begin
set nocount on
Set ansi_warnings off
Declare @AcCode as varchar(100),
	@AcID as int,
	@AccDesc as varchar(100),
	@GroupId as int,
	@CompanyName as varchar(100),
	@dtFROMDate as datetime,
	@dtToDate as datetime,
	@dtfinstartdate as datetime,
	@AccountOBCr as numeric(18,2),
	@AccountOBDr as numeric(18,2),
	@dtPrevFinUnclosedSDate as datetime,
	@dtLastFinUnclosedEDate as datetime,
	@intRecCount as int,
	@intFromFinId as int,
	@intLastFinId as int,
	@Plantodate as datetime,
	@continueplan as integer,
	@dtpackagedate as datetime,
	@strtext as nvarchar(2000),
	@strcondition as nvarchar(350),
	@strquery as nvarchar(2000),
	@intFrommonth as varchar(5),
	@inttomonth as  varchar(5),
	@intFromYear as  varchar(5),
	@inttoYear as  varchar(5),
	@intCount as int
	
Create table #PL(
	CompanyID int,
	AcID int,
	AccCode varchar(100),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CrEDitAmt numeric(18,2),
	ParentGroupID int,
	DepartmentId int)
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup Int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
			AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
			orderno int, levelcode int, departmentid int,
			DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #PLFinal(
	CompanyID int,
	AccCode varchar(100),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	AcId int, DepartmentId int, orderno int,
	levelcode int,
	Checked int,
	ParentGroupId int)
Create table #DepExrate(
departmentid int,
ExrateDiff numeric(18,8))	
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intDepartmentId=0
insert into #SubDepts1
select departmentid from adepartmentmaster
else
begin
if @intconsolidation=0
	    insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
end
	if @intdepartmentid = 0
		set @bitcons=1	
	insert into #depexrate --Getting  companyrate/depcurrency for the calculation for
	select departmentid, m.Sellingrate/c.SellingRate from adepartmentmaster a,
	acurrencymaster b, ExchangeRateDetail c, ExchangeRateDetail m, acompanyMaster z		
	where a.depcurrencyid=b.currencyid and a.companyid=b.companyid and
	b.currencyid=c.currencyid and b.companyid=c.companyid
	and a.companyid = z.companyid and z.currencyid = m.CurrencyId
	and z.Companyid = m.CompanyId		
	
	select @dtpackagedate=convert(varchar,PAckageDate,120) from
	apackagesettings where companyid= @intCompanyID
		set @plantodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dttodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dtfromdate=CONVERT(DATETIME,@strfromDate) -- Plan To date
--	print @dttodate
--	print @plantodate
--	print @dtfromdate
	if @dttodate <= @dtpackagedate 			
		set @continueplan=0
		
	else
		set @continueplan=1
select @intFromFinId = FinancialId from vwfinyearperiod where companyid = @intcompanyid and
@strFROMDate between sdate and edate
	select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFromFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	insert #Tempjournalheader
	Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
	and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
	Journaldate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and h.CompanyId = @intCompanyId
	Insert #PL(CompanyID , AcID , AccCode , AccDesc , AcType , GroupID , GroupName , OBDr ,
	OBCr , DebitAmt , CrEDitAmt , ParentGroupID, DepartmentId )
	SELECT GrpAcId.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GrpAcId.GroupID, GrpAcId.GroupDesc,
	0, 0, 0, 0, ParentGroupID, departmentid from
	(SELECT AM.Companyid, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
	GM.GroupDesc, 0 OpDebit, 0 OpCredit, 0 Debit, 0 Credit, ParentGroupID,
	'''' pg1, '''' pg2, '''' pg3, '''' pg4, '''' pg5, '''' pg6, '''' pg7,DeptId departmentid FROM aAccountMaster AM,
	aGroupMaster GM, adeptAccounts d, #SubDepts1 dep
	WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'') AND
	GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
	and am.Accountid = d.daAccountId and am.CompanyId = d.daCompanyId
	AND d.dadepartmentid = dep.deptid
	Union
	SELECT AM.Companyid, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID, GM.GroupDesc,
	0, 0, 0, 0, ParentGroupID, '''', '''', '''', '''', '''', '''', '''',DeptId  FROM aAccountMaster AM,
	aGroupMaster GM, vwGlobalAccounts d,#SubDepts1 dep, adeptAccounts dac
	WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''I'' OR GM.AccountType = ''E'') AND
	GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
	and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId
	and am.Accountid = dac.daAccountId and am.CompanyId = dac.daCompanyId
	AND dac.dadepartmentid = dep.deptid 	) GrpAcId
	group by GrpAcId.Companyid, GrpAcId.AccountID, GrpAcId.GroupID, GrpAcId.GroupDesc,
	GrpAcId.AccountCode, GrpAcId.AccountDesc, GrpAcId.AccountType, GrpAcId.ParentGroupID,
	GrpAcId.GroupID, GrpAcId.GroupDesc, OpDebit, OpCredit, Debit, Credit,
	ParentGroupID, pg1, pg2, pg3, pg4, pg5, pg6, pg7,GrpAcId.departmentid
	Update #PL set OBDr = abs(opening.Openingamount) from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
	aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #PL.AcId and opening.DepartmentId = #PL.DepartmentId
	and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
	and ((#PL.ACType = ''E''  and opening.Openingamount >0) or (#PL.ACType = ''I''  and
	opening.Openingamount <0))
	Update #PL set OBCr = abs(opening.Openingamount) from (Select AccountId,
	DepartmentId, CompanyId, case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount
	from aaccountfinyearopening where Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #PL.AcId and opening.DepartmentId = #PL.DepartmentId
	and opening.CompanyId = #PL.CompanyID and opening.CompanyId = @intCompanyId
	and ((#PL.ACType = ''E''  and opening.Openingamount <0) or (#PL.ACType = ''I''  and
	opening.Openingamount >0))
	Update #PL set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId and trialDeb.DepartmentId = #PL.DepartmentId
	and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #PL set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #PL.AcId and
	trialDeb.DepartmentId = #PL.DepartmentId and trialDeb.CompanyId = #PL.CompanyID
	and trialDeb.CompanyId = @intCompanyId
	Update #PL set DebitAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId and trialDeb.DepartmentId = #PL.DepartmentId
	and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #PL set CreditAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #PL.AcId and
	trialDeb.DepartmentId = #PL.DepartmentId
	and trialDeb.CompanyId = #PL.CompanyID and trialDeb.CompanyId = @intCompanyId
--inserting addtional headers
	if @continueplan=1 and  @dtfromdate >= @dtpackagedate
	 begin
	 set @strtext = ''insert into #PL
	 select acc.companyid, AccountID, AccountCode, AccountDesc, AccountType, b.GroupID,b.GroupDesc,
	 0, 0, 0, 0,b.ParentGroupID, bphdepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount
	from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+
	 convert(varchar ,dateadd(month,1,@dtpackagedate) ,112)+'''''' and ''''''+
	 convert(varchar,@dtfromdate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1)
	 group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #PL tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.acid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.acid is null and (accounttype =''''E'''' or Accounttype =''''I'''')''
	
--	print @strtext
	exec sp_executesql  @strtext
	end
	if @continueplan=1 and @dtfromdate <=@dtpackagedate	
	begin
	 set @dtfromdate =@dtpackagedate
	 set @strtext = ''insert into #PL
	 select acc.companyid, AccountID, AccountCode, AccountDesc, AccountType, b.GroupID,b.GroupDesc,
	 0, 0, 0, 0,b.ParentGroupID, bphdepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount
	from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+
	 convert(varchar ,dateadd(month,1,@dtfromdate) ,112)+'''''' and ''''''+
	 convert(varchar,@dttodate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1)
	 group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #PL tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.acid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.acid is null and (accounttype =''''E'''' or Accounttype =''''I'''')''
	end
if @continueplan=1
begin
	set @intfrommonth= month(@dtpackagedate)
	set @intfromyear = year(@dtpackagedate)
	set @inttomonth  =  month(@plantodate)
	set @inttoyear   = year(@plantodate)
	if @dtfromdate >= @dtpackagedate
	begin
	set @strtext =''+  bpdamount from(select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(budgplan.bpdAmount),0)bpdamount from
	(select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
	from  budgetplanheader, budgetplandetail
	where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	and bpdrevised=0 and bphcancelled=0
	and cast(cast(bphPlanYear as varchar)+
	cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	+ cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar , dateadd(month,1,@dtpackagedate ),112)+'''''' and ''''''+  convert(varchar,@dtfromdate,112)
	+  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,
	aGroupMaster b
	where
	a.companyid=b.companyid and a.groupid=b.groupid and
	budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=a.accountid''
	        -- Expense and amt >0 (ie debit)
			set @strcondition= '' and Accounttype=''''E'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid ,bpdbudgetheadid
			    having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''		
			set @strquery =''update #PL set obdr=obdr+''+ @strtext + @strcondition
			exec sp_executesql @strquery
			-- Expesne and amt <0 (ie credit)
			set @strcondition=  '' and Accounttype=''''E'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set obcr=obcr+''+@strtext+ @strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Income and amt >0 (ie credit)
			set @strcondition= ''  and Accounttype=''''I'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set obcr=obcr+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Income and amt <0 (ie Debit)
			set @strcondition=''  and Accounttype=''''I'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set obDr=obdr+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
	end
	if  @continueplan=1 and @dtfromdate <=@dtpackagedate	
	begin
		set @dtfromdate =@dtpackagedate
	set @strtext =''+  bpdamount from(select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(budgplan.bpdAmount),0)bpdamount from
	(select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
	from  budgetplanheader, budgetplandetail
	where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	and bpdrevised=0 and bphcancelled=0
	and cast(cast(bphPlanYear as varchar)+
	cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	+ cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar , @dtfromdate ,112)+'''''' and ''''''+  convert(varchar,@dttodate,112)
	+  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,
	aGroupMaster b
	where
	a.companyid=b.companyid and a.groupid=b.groupid and
	budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=a.accountid''
	        -- Expense and amt >0 (ie debit)
			set @strcondition= '' and Accounttype=''''E'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid ,bpdbudgetheadid
			    having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''		
			set @strquery =''update #PL set DebitAmt=debitamt+''+ @strtext + @strcondition
			exec sp_executesql @strquery
			-- Expesne and amt <0 (ie credit)
			set @strcondition=  '' and Accounttype=''''E'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set creditAmt=creditamt+''+@strtext+ @strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Income and amt >0 (ie credit)
			set @strcondition= ''  and Accounttype=''''I'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set creditAmt=creditamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
			-- Income and amt <0 (ie Debit)
			set @strcondition=''  and Accounttype=''''I'''' group by Budgplan.bphcompanyid,Budgplan.bphdepartmentid, bpdbudgetheadid
			    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid=#pl.AcId and
		         bphcompanyid=#pl.companyid and bphdepartmentid=#pl.departmentid''			
			set @strquery = ''update #PL set DebitAmt=debitamt+''+@strtext+@strcondition
			--print @strquery
			exec sp_executesql @strquery
	end		
end
Insert #FilteredResult(groupid , AccountCode ,
		AccountDesc , groupdesc , parentGroupid ,
			orderno , levelcode , departmentid , DepartmentName, Checked,
			AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
Insert #PLFinal(CompanyID, AccCode, AccDesc, AcType, GroupID, GroupName, OBDr,
	OBCr, DebitAmt, CreditAmt, AcId, DepartmentId, orderno, levelcode, Checked
	, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AccDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
	b.OBCr, b.DebitAmt, b.CreditAmt, b.AcId, r.DepartmentId, r.OrderNo, r.LevelCode,
	0,  r.ParentGroupId
from #FilteredResult r
left outer join #PL b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AcId and r.AccountId is not null))
where
((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0)) <> 0 and
isnull(AcType,'''') =''I'') or ((isnull(obdr,0) + isnull(obcr,0) + isnull(creditamt,0)) -  isnull(debitamt,0)
<> 0 and isnull(AcType,'''') =''E'') and b.accCode is not null) or b.accCode is null)
and (r.AccType =''I'' or r.AccType =''E'' )
order by orderno
	set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
	Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
	Order by OrderNo Desc
	While @GroupID <>0
	Begin
		set @intCount = 0
		Select @intCount = count(*) from #plFinal where
		((AccDesc is not Null and Groupid= @GroupID)
		 or ParentGroupid = @GroupID)
		if @intCount = 0
			Delete from #plFinal where GroupId = @GroupID
		else
			Update #plFinal set Checked = 1 where Groupid = @GroupID
		Set @GroupID  = 0
		Select top 1 @GroupID = GroupId From #plFinal where Checked = 0
		Order by OrderNo Desc
	End
	Set @GroupID  = 0
if @intLevel>0
	Delete from #plFinal where LevelCode >= @intLevel and AcId is null
	
if @intdepartmentid >0
	Select * from #plFinal where departmentid = @intdepartmentid or isnull(companyid,0)= 0  order by OrderNo
else
	Select * from #plFinal order by OrderNo
Drop Table #SubDepts1
Drop Table #Tempjournalheader
Drop Table #vwJournalDetails
set nocount on
Set ansi_warnings on
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPlannedBsheet]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPlannedBsheet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---	spplannedbsheet ''20041231'',1,0,1,1,0
-- 	Last Modified : 24/05/2004, 14/07/2004
-- 	Modified by   : venkitesh, Hariharan R
--	Comments      : planned BsheetF
CREATE proc [dbo].[spPlannedBsheet] (@strToDate as varchar(10), @intCompanyID as int,
@intlevel as int =0, @intDepartmentid as int=0, @bitcons as bit=0,
@intconsolidation as int =0) as
Begin
set nocount on
Declare @AcCode as varchar(100),
	@AcID as int,
	@dblDebit as numeric(18,2),
	@dblCredit as numeric(18,2),
	@AccountOBCr as numeric(18,2),
	@AccountOBDr as numeric(18,2),
	@JournalOBDr as numeric(18,2),
	@JournalOBCr as numeric(18,2),
	@GroupDesc as varchar(100),
	@GroupID as int,
	@dtToDate as datetime,
	@dtFromDate as datetime,
	@strFromdate as varchar(10),
	@intCount as integer,
	@intFinId as int,
	@dtPrevFinUnclosedSDate as datetime,
	@dtLastFinUnclosedEDate as datetime,
	@intLastFinId as int,
	@Plantodate as datetime,
	@continueplan as integer,
	@dtpackagedate as datetime,
	@strtext as nvarchar(2000),
	@strcondition as nvarchar(500),
	@strquery as nvarchar(2000),
	@intFrommonth as varchar(5),
	@inttomonth as  varchar(5),
	@intFromYear as  varchar(5),
	@inttoYear as  varchar(5)
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
Create table #BalSheet(
	CompanyID int,
	AccCode varchar(100),
	AcDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	ParentGroupID int,
	AccId int, DepartmentId int  )
	
Create table #DepExrate(
	departmentid int,
	ExrateDiff numeric(18,8))	
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
		AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
		orderno int, levelcode int, departmentid int,
		DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
	CompanyID int,
	AccCode varchar(100),
	AcDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	AccId int, DepartmentId int, orderno int,
	levelcode int,
	Checked int,
	ProfitLoss Numeric(18,2),
	ParentGroupId int)
	if @intdepartmentid = 0
		set @bitcons=1	
create table #SubDepts1(DeptId int)
if @intDepartmentId=0
insert into #SubDepts1
select departmentid from adepartmentmaster
else
begin
if @intconsolidation=0
	    insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
end
	insert into #depexrate --Getting  companyrate/depcurrency for the calculation for
	select departmentid, m.Sellingrate/c.SellingRate from adepartmentmaster a,
	acurrencymaster b, ExchangeRateDetail c, ExchangeRateDetail m, acompanyMaster z		
	where a.depcurrencyid=b.currencyid and a.companyid=b.companyid and
	b.currencyid=c.currencyid and b.companyid=c.companyid
	and a.companyid = z.companyid and z.currencyid = m.CurrencyId
	and z.Companyid = m.CompanyId		
	
	select @dtpackagedate=convert(varchar,PAckageDate,120) from
	apackagesettings where companyid= @intCompanyID
	set @plantodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dttodate =CONVERT(DATETIME,@strToDate) -- Plan To date
	set @dtfromdate=CONVERT(DATETIME,@strfromDate) -- Plan To date
	if @dttodate <= @dtpackagedate 			
		set @continueplan=0
		
	else
		set @continueplan=1
	
	select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
	 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	if @intdepartmentid=0 		
	begin
		insert #Tempjournalheader
		Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
		and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
		insert #vwJournalDetails
		Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
		Journaldate>=@dtPrevFinUnclosedSDate and
		JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
		and h.Cancel = 0 and h.CompanyId = @intCompanyId
	end
	else
	begin
		insert #Tempjournalheader
		Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
		and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
		insert #vwJournalDetails
		Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
		Journaldate>=@dtPrevFinUnclosedSDate and
		JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
		and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
		(Select Deptid from #SubDepts1)
	end
	
		Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
		OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)	
		Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
		GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
		DepartmentId from
		(SELECT am.CompanyId, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID, GM.GroupDesc,
		0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, '''' pg1, '''' pg2,
		'''' pg3, '''' pg4, '''' pg5, '''' pg6, '''' pg7, deptid departmentid FROM
		aAccountMaster AM,aGroupMaster GM, adeptAccounts d,
		#SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
		GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
		and am.Accountid = d.daAccountId and am.CompanyId = d.daCompanyId
		AND d.dadepartmentid = dep.deptid
		Union
		SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
		GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID,
		'''' pg1, '''' pg2, '''' pg3, '''' pg4, '''' pg5, '''' pg6, '''' pg7, deptid
		DepartmentId FROM aAccountMaster AM,aGroupMaster GM,
		vwGlobalAccounts d ,adeptAccounts dac,
		#SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
		GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
		and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId and
		am.Accountid = dac.daAccountId and am.CompanyId = dac.daCompanyId
		AND dac.dadepartmentid = dep.deptid
		) GrpAcId	
		group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
		GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,
		departmentid ORDER BY GrpAcId.AccountID
	Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
	aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId
	and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
	
	Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	set  @intCount = 0
	--inserting addtional headers
	if @continueplan=1 and  @dtfromdate >= @dtpackagedate
	 begin
	 set @strtext = ''insert into #BalSheet
	 select acc.companyid, AccountCode, AccountDesc, AccountType, b.GroupID,b.GroupDesc,
	 0, 0, 0, 0,b.ParentGroupID,accountid,bphdepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount
	 from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+
	 convert(varchar , dateadd(month,1,@dtpackagedate) ,112)+'''''' and ''''''+
	 convert(varchar,@dtfromdate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1)
	 group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #BalSheet tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.accid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.accid is null and (accounttype =''''A'''' or Accounttype =''''L'''')''
		exec sp_executesql  @strtext
	end
	if @continueplan=1 and @dtfromdate <=@dtpackagedate	
	begin
	 set @dtfromdate =@dtpackagedate
	 set @strtext = ''insert into #BalSheet
	 select acc.companyid, AccountCode, AccountDesc, AccountType, b.GroupID,b.GroupDesc,
	 0, 0, 0, 0,b.ParentGroupID, accountid,bphdepartmentid
	 from (select bphcompanyid, bpdbudgetheadid,bphdepartmentid,isnull(sum(bpdAmount),0)bpdamount
	 from budgetplanheader a,budgetplandetail where
	 bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
	 and bpdrevised=0 and bphcancelled=0 and cast(cast(bphPlanYear as varchar)+
	 cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
	 + cast(''''01'''' as varchar) as datetime)  between ''''''+
	 convert(varchar ,dateadd(month,1, @dtfromdate) ,112)+'''''' and ''''''+
	 convert(varchar,@plantodate,112)
	 +''''''  and bphdepartmentid in (select deptid from #subdepts1)
	 group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )budgplan
left outer join #BalSheet tb on
	 bphcompanyid=tb.companyid and bphdepartmentid=tb.departmentid and
	 bpdbudgetheadid=tb.accid,
	 aaccountmaster acc, aGroupMaster b
	 where acc.companyid=b.companyid and acc.groupid=b.groupid and
	 budgplan.bphcompanyid=acc.companyid and budgplan.bpdBudgetHeadID=acc.accountid
	 and tb.accid is null and (accounttype =''''A'''' or Accounttype =''''L'''')''
	exec sp_executesql  @strtext
	end	
SET @dblDebit = 0.0
SET @dblCredit = 0.0
		
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
	   CompanyId = @intCOmpanyId )
Begin
	if @intdepartmentid=0
	begin
		
	    select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where
	    CompanyId = @intCompanyId
	    and FinancialId = (Select max(financialid) from aAccountfinyearopening where
	    CompanyId = @intCOmpanyId )
	    select @dblDebit = Sum(isnull(Amount,0))
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and
	    h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 0 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	     and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
	    select @dblCredit = Sum(isnull(Amount,0))
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and
	    h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 1 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	    and (accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
	    if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
		Begin
			Update #BalSheet set OBDr = isnull(OBDr,0) +
			(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
			where AccId = (Select RetainedEarningsAcc from aSettings where
			CompanyId = @intCompanyId)
		End		
	end
	else
	begin
	    select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId
	    and FinancialId = (Select max(financialid) from aAccountfinyearopening where
	    CompanyId = @intCOmpanyId )
	    select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 0 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	     and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
	    and d.departmentid IN (Select DeptId from #SubDepts1)
	    select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 1 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	    and (accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
	    and d.departmentid IN (Select DeptId from #SubDepts1)
	    if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
		Begin
			Update #BalSheet set OBDr = isnull(OBDr,0) +
			(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
			where AccId = (Select RetainedEarningsAcc from aSettings where
			CompanyId = @intCompanyId)
		End		
	end		
End	
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
--SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b
--where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
--order by b.parentgroupid
-- Planned Budget Starts Here
if @continueplan=1
begin
set @intfrommonth =month(@dtpackagedate)
set @intfromyear  =year(@dtpackagedate)
set @inttomonth  = month(@plantodate)
set @inttoyear    = year(@plantodate)
	if @dtfromdate >= @dtpackagedate
	begin
		set @strtext =''bpdamount from(select  bphdepartmentid,bphcompanyid,bpdbudgetheadid,sum(budgplan.bpdAmount)bpdamount from
		(select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
		from  budgetplanheader, budgetplandetail
		where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
		and bpdrevised=0 and bphcancelled=0
		and cast(cast(bphPlanYear as varchar)+
		cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
		+ cast(''''01'''' as varchar) as datetime)  between ''''''+
		convert(varchar ,dateadd(month,1, @dtpackagedate) ,112)+'''''' and ''''''+
		 convert(varchar,@dtfromdate,112)
		+  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,aGroupMaster b
		 where
		 a.companyid=b.companyid and a.groupid=b.groupid and
		 budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=accountid''
	
		-- Asset and amt >0 (ie debit)
		set @strcondition=''  and Accounttype=''''A'''' group by  bphcompanyid,bpdbudgetheadid,bphdepartmentid
		    having sum(budgplan.bpdAmount) >0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''	
		set @strquery =''update #BalSheet set OBDr=OBDr+''+ @strtext +@strcondition
		exec sp_executesql @strquery
	
	-- Asset and amt <0 (ie credit)
		set @strcondition= '' and Accounttype=''''A'''' group by bphcompanyid,bpdbudgetheadid ,bphdepartmentid
		    having sum(budgplan.bpdAmount) < 0 )main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''			
			set @strquery = ''update #BalSheet set OBCr=obcr+''+@strtext++@strcondition
		exec sp_executesql @strquery
			-- Liability and amt >0 (ie credit)
		set @strcondition='' and Accounttype=''''L'''' group by  bphcompanyid,bpdbudgetheadid ,bphdepartmentid
		having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''	 			
	
		set @strquery = ''update #BalSheet set obcr=obcr+''+ @strtext ++@strcondition
		exec sp_executesql @strquery
		-- Liability and amt <0 (ie Debit)
		set @strcondition= ''  and Accounttype=''''L'''' group by bphcompanyid, bpdbudgetheadid ,bphdepartmentid
		    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''			
	
		set @strquery = ''update #BalSheet set obDr=obdr+''+@strtext ++@strcondition
		exec sp_executesql @strquery
	end
		if @dtfromdate <=@dtpackagedate	
		begin
		set @dtfromdate =@dtpackagedate
		set @strtext =''bpdamount from(select  bphdepartmentid,bphcompanyid,bpdbudgetheadid,sum(budgplan.bpdAmount)bpdamount from
		(select bphcompanyid, bpdbudgetheadid,isnull(sum(bpdAmount),0) bpdAmount,bphdepartmentid
		from  budgetplanheader, budgetplandetail
		where bphcompanyid=bpdcompanyid and bphBudgetPlanID=bpdBudgetPlanID
		and bpdrevised=0 and bphcancelled=0
		and cast(cast(bphPlanYear as varchar)+
		cast(''''-'''' as varchar)+cast(bpdMonthNo as varchar)+cast(''''-'''' as varchar)
		+ cast(''''01'''' as varchar) as datetime)  between ''''''+ convert(varchar , @dtfromdate ,112)+'''''' and ''''''+  convert(varchar,@plantodate,112)
		+  '''''' group by bphdepartmentid, bpdbudgetheadid,bphcompanyid )Budgplan,aaccountmaster a,aGroupMaster b
		 where
		 a.companyid=b.companyid and a.groupid=b.groupid and
		 budgplan.bphcompanyid=a.companyid and budgplan.bpdBudgetHeadID=accountid''
	
		-- Asset and amt >0 (ie debit)
		set @strcondition=''  and Accounttype=''''A'''' group by  bphcompanyid,bpdbudgetheadid,bphdepartmentid
		    having sum(budgplan.bpdAmount) >0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''	
		set @strquery =''update #BalSheet set DebitAmt=debitamt+''+ @strtext +@strcondition --+ @strcondition
		exec sp_executesql @strquery
	
	-- Asset and amt <0 (ie credit)
		set @strcondition= '' and Accounttype=''''A'''' group by bphcompanyid,bpdbudgetheadid ,bphdepartmentid
		    having sum(budgplan.bpdAmount) < 0 )main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''			
			set @strquery = ''update #BalSheet set creditAmt=creditamt+''+@strtext++@strcondition
		exec sp_executesql @strquery
			-- Liability and amt >0 (ie credit)
		set @strcondition='' and Accounttype=''''L'''' group by  bphcompanyid,bpdbudgetheadid ,bphdepartmentid
		having sum(budgplan.bpdAmount)>0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''	 			
	
		set @strquery = ''update #BalSheet set creditAmt=creditamt+''+ @strtext ++@strcondition
		exec sp_executesql @strquery
		-- Liability and amt <0 (ie Debit)
		set @strcondition= ''  and Accounttype=''''L'''' group by bphcompanyid, bpdbudgetheadid ,bphdepartmentid
		    having sum(budgplan.bpdAmount)<0)main
	 	 	where 	 bpdbudgetheadid= #BalSheet.AccId and
		         bphcompanyid= #BalSheet.companyid and bphdepartmentid= #BalSheet.departmentid''			
	
		set @strquery = ''update #BalSheet set DebitAmt=debitamt+''+@strtext ++@strcondition
		exec sp_executesql @strquery
	
		end
end
--Insert  #LevelOrdering
--exec SpGroupLevelOrdering  @intcompanyid,@intDepartmentId
select @dblDebit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0 and d.departmentid in (select deptid from #subdepts1)
select @dblCredit = Sum(isnull(Amount,0))
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0 and d.departmentid in (select deptid from #subdepts1)
	
if @continueplan = 1
	begin
	
		select @dbldebit=@dbldebit+ (select isnull(sum(bpdamount),0) Debit
		from BudgetPlanHeader h, BudgetPlandetail d, aaccountmaster a,
		agroupmaster g 	where g.groupid = a.groupid and
		d.bpdBudgetHeadID = a.accountid and
		h.bphBudgetPlanID = d.bpdBudgetPlanID and
		 h.bphcompanyid = d.bpdcompanyid
	        and h.bphcancelled =0 and  ( cast(cast(bphPlanYear as varchar)+
		cast(''-'' as varchar)+cast(bpdMonthNo as varchar)+cast(''-'' as varchar)
		+ cast(''01'' as varchar) as datetime)  between  convert(varchar , @dtpackagedate ,112)
		 and  convert(varchar,@plantodate,112) and
	        AccountType =''E'' 	and  bpdamount >0 and
		bphDepartmentId in (select deptid from #subdepts1)))
	
	
		select @dbldebit=@dbldebit + (select isnull(sum(bpdamount),0) Debit
		from BudgetPlanHeader h, BudgetPlandetail d, aaccountmaster a,
		agroupmaster g 	where g.groupid = a.groupid and
		d.bpdBudgetHeadID = a.accountid and
		h.bphBudgetPlanID = d.bpdBudgetPlanID and
		 h.bphcompanyid = d.bpdcompanyid
	        and h.bphcancelled =0 and  ( cast(cast(bphPlanYear as varchar)+
		cast(''-'' as varchar)+cast(bpdMonthNo as varchar)+cast(''-'' as varchar)
		+ cast(''01'' as varchar) as datetime)  between  convert(varchar , @dtpackagedate ,112)
		  and  convert(varchar,@plantodate,112) and
	        (AccountType =''I'' )	and  bpdamount <0 and
		 bphDepartmentId in (select deptid from #subdepts1) ))	
		select @dblCredit = @dblcredit + (select  isnull(sum(bpdamount),0) ExpCredit
		from BudgetPlanHeader h, BudgetPlandetail d, aaccountmaster a,
		agroupmaster g 	where g.groupid = a.groupid and
		d.bpdBudgetHeadID = a.accountid and
		h.bphBudgetPlanID = d.bpdBudgetPlanID and
		h.bphcompanyid = d.bpdcompanyid
	        and h.bphcancelled =0 and  ( cast(cast(bphPlanYear as varchar)+
		cast(''-'' as varchar)+cast(bpdMonthNo as varchar)+cast(''-'' as varchar)
		+ cast(''01'' as varchar) as datetime)  between  convert(varchar , @dtpackagedate ,112)
		  and  convert(varchar,@plantodate,112) and
	        (AccountType =''E'' )	and   bpdamount <0 and
		 bphDepartmentId in (select deptid from #subdepts1) ) )
	
		select @dblCredit = @dblcredit + (select isnull(sum(bpdamount),0) IncomeCredit
		from BudgetPlanHeader h, BudgetPlandetail d, aaccountmaster a,
		agroupmaster g 	where g.groupid = a.groupid and
		d.bpdBudgetHeadID = a.accountid and
		h.bphBudgetPlanID = d.bpdBudgetPlanID and
		 h.bphcompanyid = d.bpdcompanyid
	        and h.bphcancelled =0 and  ( cast(cast(bphPlanYear as varchar)+
		cast(''-'' as varchar)+cast(bpdMonthNo as varchar)+cast(''-'' as varchar)
		+ cast(''01'' as varchar) as datetime)  between  convert(varchar , @dtpackagedate ,112)
		  and  convert(varchar,@plantodate,112) and
	        (AccountType =''I'' )	and bpdamount>0 and
		 bphDepartmentId in (select deptid from #subdepts1)))
		end	
Insert #FilteredResult(groupid , AccountCode ,
		AccountDesc , groupdesc , parentGroupid ,
			orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
	OBCr, DebitAmt, CreditAmt, AccId, DepartmentId, orderno, levelcode, Checked,
	ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
	b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.DepartmentId, r.OrderNo, r.LevelCode,
	0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r
left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))
where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0)) <> 0 and
isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) + isnull(creditamt,0)) -  isnull(debitamt,0)
<> 0 and isnull(AcType,'''') =''L'') and b.accCode is not null) or b.accCode is null)
and (r.AccType =''A'' or r.AccType =''L'' )
order by r.orderno
	set @GroupId = 0
--select * from #BalSheetFinal
-- TO avoid the groups which does not have any accounts information
	Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
	Order by OrderNo Desc
	While @GroupID <>0
	Begin
		set @intCount = 0
		Select @intCount = count(*) from #BalSheetFinal where
		((AcDesc is not Null and Groupid= @GroupID)
		 or ParentGroupid = @GroupID)
		if @intCount = 0
			Delete from #BalSheetFinal where GroupId = @GroupID
		else
			Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
		Set @GroupID  = 0
		Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
		Order by OrderNo Desc
	End
	Set @GroupID  = 0
--select * from #balsheetfinal 	
--if @intLevel>0
	--	Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
if @intdepartmentid>0
	Select * from #BalSheetFinal where departmentid=@intdepartmentid or companyid is null order by OrderNo
else
	Select * from #BalSheetFinal order by OrderNo
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPLAmtForBSdep]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPLAmtForBSdep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spPLAmtForBSdep    Script Date: 28/12/2002 4:26:50 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBSdep    Script Date: 14/09/2002 12:48:14 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBSdep    Script Date: 31/07/2002 2:00:36 PM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBSdep    Script Date: 20/11/2001 9:59:15 AM ******/
/****** Object:  Stored Procedure dbo.spPLAmtForBSdep    Script Date: 17/11/2001 9:22:27 PM ******/
CREATE proc [dbo].[spPLAmtForBSdep] (@strToDate as varchar(10), @intCompanyID as int,
@intdepartmentid as int,
@numDebitAmt as numeric(18,2) output, @numCreditAmt as numeric(18,2) output)
as
set nocount on
Declare @AcCode as varchar(100),
	@AcID as integer,
	@AccDesc as varchar(100),
	@strParentGroupName varchar(100),
	@intParentGroupID int,
	@AcType as varchar(1),
	@dblDebit as numeric(18,2),
	@dblCrEDit as numeric(18,2),
	@AccountOBCr as numeric(18,2),
	@AccountOBDr as numeric(18,2),
	@JournalOBDr as numeric(18,2),
	@JournalOBCr as numeric(18,2),
	@OBDr as numeric(18,2),
	@OBCr as numeric(18,2),
	@GroupDesc as varchar(100),
	@GroupID as int,
	@CompanyName as varchar(100),
	@dtFROMDate as datetime,
	@dtToDate as datetime
Create table #PL(
	CompanyID int,
	AcID int,
	AccCode varchar(100),
	AccDesc varchar(100),
	AcType varchar(1),
	GroupID integer,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CrEDitAmt numeric(18,2),
	ParentGroupID int,
	ParentGroupName varchar(100))
	SELECT  @dtFROMDate =  convert(datetime,convert(varchar(4),startyear) +
	''/''+convert(varchar(2),startmonth) +''/''+''01'') from afinancialyear where CurFinancialYear =1
	SELECT @dtToDate = convert(datetime, @strToDate)
Declare curPL Cursor For
SELECT AccountID, GM.GroupID, GM.GroupDesc, AccountCode, AccountDesc, AccountType,
openingamount, openingamount, ParentGroupID FROM aAccountMaster AM,aGroupMaster GM
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = "I" OR GM.AccountType = "E")
AND GM.CompanyID = @intCompanyID AND AM.CompanyID = @intCompanyID
ORDER BY AccountType, AccountID
Open curPL
Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,
@AccountOBCr, @AccountOBDr, @intParentGroupID
while @@fetch_status <> -1
begin
	set @strParentGroupName = ''''
	SELECT @strParentGroupName = GroupDesc FROM aGroupMaster WHERE groupID =
	@intparentgroupID
	if @AcType = ''E''
	begin
		SELECT @OBDr = 	isnull(@JournalOBDr,0)
		SELECT @OBCr = 0
	end
	else if @AcType = ''I''
	begin
		SET @OBDr = 0
		SET @OBCr = isnull(@JournalOBCr,0)
	end
	SELECT @dblDebit = Sum(isnull(Amount,0)) FROM vwjournaldetails JD, moajournalheader JH,
	acompanymaster c
	WHERE c.companyid = jh.companyid and c.financialid = jh.financialid and
	JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND jh.cancel =0 and
	JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
	@dtToDate) AND JD.JournalCrEDit = 0 AND JD.AccountID = @AcID
	and jd.departmentid = @intdepartmentid Group By JD.AccountID
	SELECT @dblCrEDit = Sum(isnull(Amount,0)) FROM vwjournaldetails JD, moajournalheader JH,
	acompanymaster c
	WHERE c.companyid = jh.companyid and c.financialid = jh.financialid and
	JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND jh.cancel =0 and
	JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
	@dtToDate) AND JD.JournalCrEDit = 1 AND JD.AccountID = @AcID
	and jd.departmentid = @intdepartmentid Group by JD.AccountID
	insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType, @GroupID,
		@GroupDesc, isnull(@OBDr,0), isnull(@OBCr,0), isnull(@dblDebit,0),
		isnull(@dblCrEDit,0), @intParentGroupID, @strParentGroupName)
	SELECT @OBDr = 0
	SELECT @OBCr = 0
	SELECT @dblDebit = 0
	SELECT @dblCrEDit = 0
	SELECT @JournalOBDr = 0
	SELECT @JournalOBCr = 0
	Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,
	@AccountOBCr, @AccountOBDr, @intParentGroupID
end
SELECT @numDebitAmt = (sum(OBDr) + sum(DebitAmt)),
@numCreditAmt  = (sum(OBCr) + sum(CreditAmt)) FROM #PL
close curPL
deallocate curPL
set nocount on' 
END
GO
/****** Object:  View [dbo].[vwJournalParticulars]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJournalParticulars]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwJournalParticulars    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwJournalParticulars    Script Date: 14/09/2002 12:48:06 AM ******/
/****** Object:  View dbo.vwJournalParticulars    Script Date: 31/07/2002 2:00:28 PM ******/
CREATE view [dbo].[vwJournalParticulars] as
select companyid, journalid, case when posting =''Dr'' then 0 when posting =''Cr'' then 1
end as journalcredit, min(particulars) particulars  from vwjournaldetailonename
group by companyid, journalid, posting'
GO
/****** Object:  View [dbo].[vwjournaldetailsmonthwise]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwjournaldetailsmonthwise]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwjournaldetailsmonthwise    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwjournaldetailsmonthwise    Script Date: 14/09/2002 12:48:05 AM ******/
/****** Object:  View dbo.vwjournaldetailsmonthwise    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwjournaldetailsmonthwise    Script Date: 20/11/2001 9:59:00 AM ******/
/****** Object:  View dbo.vwjournaldetailsmonthwise    Script Date: 17/11/2001 9:21:31 PM ******/
-- Last Modified on : 01/11/01
-- Modified by      : leo
CREATE view [dbo].[vwjournaldetailsmonthwise] as
SELECT jh.companyid, jh.journalid, month(jh.journaldate) tmonth,jd.departmentid,
case  when jd.journalcredit =1 then ''y'' else ''n'' end as journalcredit,
jd.accountid, jd.amount, jd.actualamount,jd.depamount FROM
vwjournaldetails JD,  moajournalheader JH, acompanymaster c
WHERE c.companyid = jh.companyid and jh.financialid > 0 and
JD.JournalID = JH.JournalID AND JH.CompanyID = jd.companyid AND JH.Cancel = 0'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockServiceInvoice]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateStockServiceInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By 	: Lawrence.J
--Created Date 	: Jan-09-2003
--Comments	: V3
--Purpose	:update stock table when transaction is saved in Service
		 -- Invoice sales transaction
	
CREATE proc [dbo].[spUpdateStockServiceInvoice](@InvoiceId int,
@intShopID int,@process char(1)) as
declare
@cur_InvoiceId int,
@cur_Shopid int,
@cur_itemid int,
@cur_itemQty numeric(18,3),
@intCount int
set nocount on
declare cursor_Detail  cursor for
	select repinvinvoiceid,repinvdshopid,repinvdpartsid,repinvdqty
	from losinvoicedpartsreplacedetails
	where repinvinvoiceid = @InvoiceId and repinvdshopid = @intShopID
open cursor_Detail
fetch next from cursor_Detail into
@cur_InvoiceId, @cur_Shopid, @cur_itemid,
@cur_itemQty
while @@fetch_status = 0
begin
	if @process =''R''
		update mosShopStock set stock = stock + @cur_itemQty
		where itemid = @cur_itemid and shopid = @cur_Shopid
	if @process =''F''
	begin
		select @intCount = count(*) from mosshopstock where
		itemid = @cur_Itemid and shopid = @intShopid
		if @intCount =0
		insert mosshopstock(ShopID,StockDate, ShipmentID, ItemID,
		OpeningStock, Stock, OpeningBadStock, BadStock)
		Select @intSHopid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
		update mosShopStock set stock = stock - @cur_itemQty
		where itemid = @cur_itemid and shopid = @cur_Shopid
	end
	fetch next from cursor_Detail into
	@cur_InvoiceId, @cur_Shopid, @cur_itemid,
	@cur_itemQty
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopPurchaseReturn]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopPurchaseReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[spUpdateShopPurchaseReturn] (@WriteOffId int,
@ShopId int, @Type char(1), @strTransType Char(1))  AS
Begin
declare
@cur_woffid int,
@cur_shopid int,
@cur_itemid int,
@cur_ItemGoodQty numeric(18,3),
@cur_cost numeric(18,2),
@cur_ShipmentID int,
@recCount as int,
@numBadQty as numeric(18, 3),
@intcount as int
set nocount on
set @intcount=0
declare cursor_Detail  cursor for
select wdid, wdshopid, wditemid, wdPurchaseReturnQty, wdcostprice, wdshipmentid
from losPurchaseReturnDetail where wdid = @WriteoffID and wdshopid = @Shopid
open cursor_Detail
fetch next from cursor_Detail into
@cur_woffid, @cur_shopid, @cur_itemid,
@cur_ItemGoodQty, @cur_cost,  @cur_ShipmentID
while @@fetch_status = 0
begin
--added by venki forinserting empty row if itemcount=0
select @intCount = count(*) from mosShopStock
where itemid = @cur_Itemid and Shopid= @shopid
if @intCount =0
Begin
insert mosshopStock (shopID,StockDate, ShipmentID, ItemID,
OpeningStock, Stock, OpeningBadStock, BadStock)
Select @shopid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
End
--
-- in write off, take bad qty as transaction qty
-- in other cases take it as 0
If @strTransType = ''W''
Set @numBadQty = @cur_ItemGoodQty
Else
Set @numBadQty = 0
if @TYpe=''f''
Begin
update mosshopstock
set stock = IsNull(stock, 0) - @cur_ItemGoodQty,
badStock = IsNull(badStock, 0) + @numBadQty
where itemid = @cur_itemid
and shopid = @cur_shopid
and shipmentid = @cur_ShipmentID
End
Else --@type=''r''
Begin
update mosshopstock
set stock = IsNull(stock, 0) + @cur_ItemGoodQty,
badStock = IsNull(badStock, 0) - @numBadQty
where itemid = @cur_itemid
and shopid = @cur_shopid
and shipmentid = @cur_ShipmentID
End
fetch next from cursor_Detail into
@cur_woffid, @cur_shopid, @cur_itemid,
@cur_ItemGoodQty, @cur_cost,  @cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0
End
---------------------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockRecvr]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockRecvr]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateShopStockRecvr    Script Date: 18/01/2003 9:45:45 PM ******/
--Created By		:Lawrence.J
--Created On		:30-Dec-2002
--Purpose		:(V3) Updating Stock in POS Recovery
--Verified by 		: Hariharan on 03/01/2003
CREATE Proc [dbo].[spUpdateShopStockRecvr] @RecoveryId int,
				   @Shopid int  as
begin
	declare
	@cur_RecoveryId int,
	@cur_ShopId int,
	@cur_ItemId int,
	@cur_AddQty numeric(18, 3),
	@cur_DedQty numeric(18, 3),
	@cur_cost numeric(18, 2),
	@cur_ShipmentID int,
	@recCount as int,
	@ItemQty as numeric(18, 3)
	set nocount on
	declare cursor_Detail  cursor for
		select srID srId, srShopID ShopId, srItemID ItemId,
		srAddStock AddQty, srDedStock DedQty,
		ItemRate, b.ShipmentID
		from (losstockrecovery Rec left outer join aItem
		on Rec.srItemId = aItem.ItemId),
		(select min(ShipmentID) ShipmentId from mosshopstock) b
		where srId = @RecoveryId
		and srShopID = @ShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_RecoveryId, @cur_ShopId, @cur_ItemId,
		@cur_AddQty, @cur_DedQty,
		@cur_cost, @cur_ShipmentId
	while @@fetch_status = 0
	begin
		-- if add qty is not zero, add stock
		-- other wise (if ded qty is not zero)
		-- then reduce stock
		if @cur_AddQty > 0
	   	begin
			set @ItemQty = @cur_AddQty
		end
		else
		begin		
			set @ItemQty = -1 * @cur_DedQty
		end
		-- check if the record exists in the stock table
		select @recCount = count(*) from mosshopstock
				where ItemID= @cur_ItemId
				and ShopID = @cur_ShopId
		
		-- if it does not exist
		if @recCount = 0
		begin
			-- insert to stock table
			insert mosshopstock(ShopID,ItemID,
				Stock, ShipmentID, ItemCostPrice,StockDate)
				select @cur_ShopId,@cur_ItemId,
				@ItemQty, @cur_shipmentId, @cur_cost, getdate()
		end
		else	-- if the record exists in the stock table
		begin
			-- update stock table
			update mosshopstock set Stock = Stock + @ItemQty
					where ItemID =@cur_ItemId
					and ShopID =@cur_ShopId
		End
		-- get next record from the cursor
		fetch next from cursor_Detail into
			@cur_RecoveryId, @cur_ShopId, @cur_ItemId,
			@cur_AddQty, @cur_DedQty,
			@cur_cost, @cur_ShipmentId
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockPos]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockPos]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified By  : Hariharan
-- MOdified Date : 29/12/2002
-- Comments : V3
-- TO update stock table when transaction is saved in pos
-- sales transaction
---------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on : 06/08/2003
-- Comments : Added the updation of free quantity
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
---------------------------------------------------------------------------
CREATE PROC [dbo].[SpUpdateShopStockPos](@intBillID int,
@intShopID int,
@process char(1)) AS
Begin
declare
@cur_BillID int,
@cur_Shopid int,
@cur_itemid int,
@cur_itemQty numeric(18, 3),
@intCount int,
@cur_FreeQuantity numeric(18, 3)
set nocount on
declare cursor_Detail  cursor for
select posdbillid, posdshopid, posdItemID, posdQuantity, isnull(posdFreeQuantity,0) posdFreeQuantity
from losPosDetail
where posdbillid = @intBillID and posdshopid = @intShopID
open cursor_Detail
fetch next from cursor_Detail into
@cur_BillID, @cur_Shopid, @cur_itemid,
@cur_itemQty, @cur_FreeQuantity
while @@fetch_status = 0
begin
if @process = ''R''
Begin
update mosShopStock set stock = stock + @cur_itemQty + @cur_FreeQuantity
where itemid = @cur_itemid and shopid = @cur_Shopid
End
if @process = ''F''
begin
select @intCount = count(*) from mosShopStock
where itemid = @cur_Itemid and shopid = @intShopid
if @intCount =0
Begin
insert mosShopStock (ShopID, StockDate, ShipmentID, ItemID,
OpeningStock, Stock, OpeningBadStock, BadStock)
Select @intSHopid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
End
update mosShopStock set stock = stock - (@cur_itemQty + @cur_FreeQuantity)
where itemid = @cur_itemid and shopid = @cur_Shopid
end
fetch next from cursor_Detail into
@cur_BillID, @cur_Shopid, @cur_itemid,
@cur_itemQty, @cur_FreeQuantity
end
close cursor_Detail
deallocate cursor_Detail
return 0
End' 
END
GO
/****** Object:  View [dbo].[shopstock1]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[shopstock1]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[shopstock1] as
select a.pbhbilldate,b.pbditemid from losppurchasebillheader a,losppurchasebilldetail b where
a.pbhbillid in(select pbdbillid from losppurchasebilldetail where pbditemid in(select itemid from vwinquiryshopstock))'
GO
/****** Object:  View [dbo].[vwPandCInquiryShopStock]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryShopStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created On : 09/07/2006
-- Created By : Aneesh
CREATE View [dbo].[vwPandCInquiryShopStock]  As
Select s.itemid,sum(s.stock) As Totalstock,s.shopid, shopname,  Max(sellingprice) sellingprice,
max(wholesaleprice) wholesaleprice,Max(discountprice) discountprice
From vwInquiryShopStock s, ashops a, vwshopitemshipmentdetail vd, vwitemretailpacking p,
aitem ai Where  s.shopid=a.shopid and vd.itemid = s.itemid and vd.shopid = s.shopid
and vd.itemid = p.itemid and vd.packingtypeid=p.packingtypeid and p.unitsid =ai.unitsid and ai.itemid=s.itemid
GROUP BY s.shopid, shopname, s.itemid'
GO
/****** Object:  View [dbo].[vwShopBincardBadQtySummary]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardBadQtySummary]'))
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwShopBincardBadQtySummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwShopBincardBadQty.
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- ===============================================
CREATE VIEW [dbo].[vwShopBincardBadQtySummary] AS
--stock verification add
select svdshopid shopid, svdItemid itemid, svhDate sdate, NULL transid, NULL transno,
svdVerifiedbadStock-svdAvailbadStock badtransqty,
''Bad Verification Plus'' [Type], 1 mode, NULL updatetime
from losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 and svhDate>''20100803''
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,
wd.wdWriteoffQty, ''Write off'', 1 mode, NULL
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and wh.whType=''W''
and wh.whdate>''20100803''
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, NULL, NULL,
Pd.wdPurchaseReturnQty, ''Purchase Return'', 1 mode, NULL
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whType=''P''
and Ph.whdate>''20100803''
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, NULL, NULL,
svdAvailbadStock-svdVerifiedbadStock,
''Bad Verification Minus'', -1 mode, NULL
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedbadStock < svdAvailbadStock
and svhCancelled=0 and svhDate>''20100803''
union all
--damage cleared
select dcdShopid, dcdItemID, dchClearingDate, NULL, NULL,
dcdWriteOffQty, ''Damage Cleared'', -1 mode, NULL
from LOsShopDamageClearingHeader, LOsShopDamageClearingdetails
where dchClearingID = dcdClearingID and dchShopid = dcdShopid
and dchcancelled = 0 and dchClearingDate>''20100803'''
GO
/****** Object:  View [dbo].[vwShopBincardAuditSummary]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAuditSummary]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- This view was automatically generated
-- by spMag_GenerateVwShopBincardAuditSummary.
-- Alter above proc to make any change in this view.
-- =============================================================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwShopBincardAudit.
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- =============================================================================
CREATE VIEW [dbo].[vwShopBincardAuditSummary] AS
SELECT h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,
NULL TransNo, NULL TransId,
d.gadItemGoodQuantityArrived TransQty,
''Arrival From Godown'' [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,
NULL DepCostPrice, NULL ConCostPrice
FROM losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d
WHERE h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1 and h.gaharrivaldate>''20100803''
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
UNION ALL
SELECT grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate,
NULL, NULL, GRNDQuantity, ''Goods Return'', 1 as mode,
NULL, NULL, NULL, NULL
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0 and GrnhGoodsreturnnoteDate>''20100803''
union all
--transfer in
select h.tihshopid,  d.tiditemid, h.tihdate, NULL, NULL,
d.TIDrecievedgoodqty, ''Transfer In'', 1 mode,
NULL, NULL, NULL, NULL
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
and h.tihdate>''20100803''
union all
--recovery add
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.sraddstock) as recAdd, ''Recovery Plus'', 1 Mode,
NULL, NULL, NULL, NULL
from
losstockrecovery sr
where sr.srdate>''20100803''
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock as svAddQty,
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''
and svhDate>''20100803''
union all
--TOTAL stock verification add
select svdshopid, svdItemid, svhDate, svhno, svhid,
svdVerifiedStock-svdAvailStock as svAddQty,
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''
and svhDate>''20100803''
union all
--exchange in
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,
sedExchangeQty, ''Exchanged In'',1 mode, NULL, NULL, NULL, NULL
FROM losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
and sehExchangeDate>''20100803''
union all
--local purchase
select lphShopid, lpditemid, lphbilldate, NULL, NULL,
lpdItemQuantity, ''Local Purchase'', 1 mode, NULL, NULL, NULL, NULL
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and
lphShopID= lpdShopid and lphCancelled=0
and lphbilldate>''20100803''
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,
wd.wdWriteoffQty, ''Write off'', -1 mode, NULL, NULL, NULL, NULL
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
and wh.whdate>''20100803''
union all
--Deapatch
select dd.dgdshopid, dd.dgditemid, dh.dghDate, NULL, NULL,
dd.dgddespatchedgoodqty, ''Despatch To Godown'' TYpe, -1 mode,
NULL, NULL, NULL, NULL
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
and dh.dghDate>''20100803''
union all
--Transferout
select todshopid, toditemid, tohDate, NULL, NULL,
todissuedgoodqty, ''Transfer Out'',-1 mode, NULL, NULL, NULL, NULL
from mestransferoutheader , mestransferoutdetail  where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
and tohDate>''20100803''
union all
--recovery minus
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.srdedstock) as recAdd, ''Recovery Minus'',-1 Mode,
NULL, NULL, NULL, NULL from
losstockrecovery sr
where sr.srdate>''20100803''
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid
having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,
NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''
and svhDate>''20100803''
union all
--Total stockverification minus
select svdshopid, svdItemid, svhDate, NULL, NULL,
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,
NULL, NULL, NULL, NULL
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''
and svhDate>''20100803''
union all
--pos sales
select poshShopID, posditemid, poshBilldate, NULL, NULL,
posdquantity, ''Cash Sales'', -1 mode, NULL, NULL, NULL, NULL
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
and poshBilldate>''20100803''
union all
--credit invoice
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,
idquantity, ''Credit Sales'', -1 mode, NULL, NULL, NULL, NULL
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''I''
and ihInvoicedate>''20100803''
union all
--exchange out
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,
sedquantity, ''Exchange Out'', -1 mode, NULL, NULL, NULL, NULL
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
and sehExchangeDate>''20100803''
union all
--special invoice return to shop
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,
-reqqty, ''Special Invoice Return'', 1 mode, NULL, NULL, NULL, NULL
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
and ihInvoicedate>''20100803''
union all
select serinvhShopid, repinvdpartsid, serinvhdate, NULL, NULL,
repinvdqty, ''Parts Replaced'', -1 as mode, NULL, NULL, NULL, NULL
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
and serinvhdate>''20100803''
union all
--Re-Exporting
select rehShopID, reditemid,  rehExportDate, NULL, NULL,
redquantity, ''Re-Export'', -1 mode, NULL, NULL, NULL, NULL
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''I''
and rehExportDate>''20100803''
union all
--MerGing minus
select lsdShopID, lsdItemID, lshDate, NULL, NULL,
sum(lsdqty), ''Merging Deduct'', -1 as mode, NULL, NULL, NULL, NULL
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopid = mh.lshShopId
and lshCancelled=0
and lshDate>''20100803''
group by lsdShopID, lsdItemID, lshDate, lshid
Having Sum(lsdQty) <> 0
union all
--MerGing Add
select lsdShopID, lshItemID, lshDate, NULL, NULL,
sum(lsdqty), ''Merging Add'', 1 as mode, NULL, NULL, NULL, NULL
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopID = mh.lshShopid
and lshCancelled = 0
and lshDate>''20100803''
group by lsdShopID, lshItemID, lshDate, lshid
Having Sum(lsdQty) <> 0
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate, NULL, NULL,
Pd.wdPurchaseReturnQty, ''Purchase Return'', -1 mode, NULL, NULL, NULL, NULL
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1
and Ph.whdate>''20100803''
union all
--Warrenty Claim/Business promotion
select wchShopID, wcditemid, wchdate, NULL, NULL,
wcdQty, ''WC/BP'', -1 mode, NULL, NULL, NULL, NULL
from losWarrentyClaimDetail,losWarrentyClaimHeader
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0
and wchdate>''20100803''
union all
-----Hire Purchase Invoice
select hpqhShopid,hpqdItemId,hpqhQuotationDate, NULL, NULL,
1 as Qty, ''Hire Purchase'', -1 mode, NULL, NULL, NULL, NULL
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I''
and hpqhQuotationDate>''20100803'''
GO
/****** Object:  View [dbo].[vwInquiryShopStockSummary]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockSummary]'))
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwInquiryShopStockSummary.
-- Alter spMag_GenerateVwInquiryShopStockSummary
-- to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 22-07-2010
-- Description :
--    To compute shop stock using transactions summary.
--    This view is created based on vwInquiryShopStock.
--    Shop Transactions Summary part is additionally added.
-- ===============================================
CREATE VIEW [dbo].[vwInquiryShopStockSummary] AS
SELECT
ShopId, ItemId, convert(numeric(18,3), sum(stock)) Stock
, sum(badstock) BadStock, sum(openingstock) OpeningStock
, sum(openingbadstock) OpeningBadStock, 1 ShipmentId
, max(itemcostprice) ItemCostPrice
FROM (
-- 1. Shop Transactions Summary
SELECT
ShopId, ItemId, Stock, BadStock, OpeningStock
, OpeningBadStock, ItemCostPrice
FROM losShopTransactionsSummary
UNION ALL
-- 2. Opening Stock
SELECT
shopid, itemid, openingstock stock, isnull(openingbadstock,0) badstock
, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
, itemcostprice
FROM mosshopstock
WHERE openingstock>''20100803''
UNION ALL
-- 3. Shop Bin Card For Good Stock
SELECT
shopid,itemid, transqty * mode stock, 0
, 0, 0, 0
FROM vwShopBincardAuditSummary
-- 4. Shop Bin Card For Bad Stock
UNION ALL
SELECT
shopid,itemid,  0,  badtransqty * mode badstock
, 0, 0, 0
FROM vwShopBincardBadQtySummary
) inqstock
GROUP BY shopid, itemid'
GO
/****** Object:  StoredProcedure [dbo].[spPandCInquiryShopStock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPandCInquiryShopStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- created on : 21/07/2002
-- Created by : leo
-- =============================================================================
-- Upgraded By : Regin T.
-- Upgraded On : 23-07-2010
-- Upgrade     :
--     Added parameter @intTransSummaryMode.
--     If @intTransSummaryMode = 1, vwInquiryShopStockSummary view will be used
--     to calculate stock. This view is fast, but may result in wrong stock
--     since it depends on trans summary (losShopTransactionsSummary) also.
--     If speed gets more importance, it is adviced to set @intTransSummaryMode to 1.
--     If accuracy is vital, @intTransSummaryMode should be 0.
-- Upgraded By : SHINE DAS.
-- Upgraded On : 23-07-2011
-- Upgrade     : Currency Symbol added into the select Qry. To show Currency symbol
--in Enquiries.
-- =============================================================================
CREATE PROC [dbo].[spPandCInquiryShopStock]
@intitemid as int
, @intTransSummaryMode as int = 0
AS
BEGIN
IF @intTransSummaryMode = 1  -- vwInquiryShopStockSummary is in use
select sum(s.stock) as Totalstock,s.shopid, shopname,  max(sellingprice) sellingprice, max(wholesaleprice) wholesaleprice,
max(discountprice) discountprice,cm.Symbol from vwInquiryShopStockSummary s, ashops a, vwshopitemshipmentdetail vd, vwitemretailpacking p,
aitem ai, aCurrencyMaster CM where s.itemid= @intitemid  and s.shopid=a.shopid and vd.itemid = s.itemid and vd.shopid = s.shopid
and vd.itemid = p.itemid and vd.packingtypeid=p.packingtypeid and p.unitsid =ai.unitsid and ai.itemid=s.itemid and
vd.currencyid =cm.CurrencyID
GROUP BY s.shopid, shopname, s.itemid,cm.Symbol
ELSE                         -- vwInquiryShopStock is in use
select sum(s.stock) as Totalstock,s.shopid, shopname,  max(sellingprice) sellingprice, max(wholesaleprice) wholesaleprice,
max(discountprice) discountprice,cm.Symbol from vwInquiryShopStock s, ashops a, vwshopitemshipmentdetail vd, vwitemretailpacking p,
aitem ai, aCurrencyMaster CM where s.itemid= @intitemid  and s.shopid=a.shopid and vd.itemid = s.itemid and vd.shopid = s.shopid
and vd.itemid = p.itemid and vd.packingtypeid=p.packingtypeid and p.unitsid =ai.unitsid and ai.itemid=s.itemid and
vd.currencyid =cm.CurrencyID
GROUP BY s.shopid, shopname, s.itemid,cm.Symbol
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BACKUP24022012]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments_BACKUP24022012]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Last Modified : 07/02/2004
Modified by   : Hariharan R
COMMENTS  : RESP AMOUNT posting done for` exchange diff acc
Verified by      : Hariharan
Verified Date     : 03/05/2004 (verified From Client DB)
Modified By   :Benzigar S D
Modified On   :20/03/2009
Comment       :Modified Company and Department amount calculation for adjustment
----------------------------------------------------------------------------------------------------
Ref No : 101
Modified By : SHINE DAS
Modified On : 05.05.2011
Comments : Calcuation of amount which has to be posted to "Exchange Gain/Loss" account was wrong.
*/
-----------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateLedgersAdjustments_BACKUP24022012]  @intCompanyID as int, @intAdjID as int as
begin
set nocount on
Declare
@intjournalId as int,
@intAdjustmentDetailId as int,
@intRowCount as int,
@intCompanycurID as int,
@dtAdjustmentDate as datetime,
@strAdjustmentNo as varchar(50),
@strRemarks as varchar(250),
@numAmount as numeric(18,2),
@numExAmount as numeric(18,2),
@bitJC as bit,
@intAccountID as int,
@intcustomerid as int,
@intvendorid as int,
@numdAmount as numeric(18,2),
@numcAmount as numeric(18,2),
@strextype as char(1),
@intexaccountid as int,
@intfinancialid as int,
@intdepartmentid as int,
@adjType as varchar(2),
@intDepCurrID as int,
@strexrates as varchar(250),
@numDepExRate as numeric(18,8),
@numConExRate as numeric(18,8),
@numexamountDep  as numeric(18,8),
@numexamountCom  as numeric(18,8),
@numexamountAccnt  as numeric(18,8),
@numExGainorLoss as numeric(18,2)  ---Ref No : 101 New Variable Declared
/* getting the maximum Journal ID FROM journal table */
SELECT @intjournalId = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
SELECT @intCompanycurID = CurrencyID FROM acompanymaster
WHERE CompanyID =@intCompanyID
Declare JTcur cursor for
SELECT AdjustmentID, AdjustmentNo, AdjustmentDate, remarks, amount, exchangegain,
accountid, financialid, departmentid, AdjustmentType, Exchangerates,
DepExchangerate, exchangeRate
FROM AdjustmentHeader WHERE cancellED =0 and postED =0 and
CompanyID = @intCompanyID and adjustmentid = @intAdjID
open JTCur
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,
@strexrates, @numDepExRate, @numConExRate
while @@Fetch_status = 0
begin
Select @intDepCurrID = depCurrencyId from aDepartmentMaster where
departmentid = @intdepartmentid
---------------Ref No : 101 Start
if right(@ADJType, 1) =''D''
begin
-- select @numExGainorLoss = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1) -
--(select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0)
select @numExGainorLoss =isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-
isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)
set @numexamountDep = @numexamount
set @numexamountCom = abs(@numExGainorLoss)
set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
else
begin
select @numExGainorLoss = isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-
isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)
set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountCom = abs(@numExGainorLoss)
set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
-----------Ref No : 101 End
/*
----------------------------------------   Ref No : 101 Commented Previous code - Start
if right(@ADJType, 1) =''D''
begin
set @numexamountDep = @numexamount
set @numexamountCom = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
else
begin
set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountCom = @numexamount
set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
------------------------------------------  Ref No : 101 Commented Previous code - End
*/
set @intjournalId = @intjournalId + 1
set @intAdjustmentDetailId = 1
insert into moaJournalHeader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate)
values (@intjournalid, @intCompanyID, @dtAdjustmentDate, @strAdjustmentNo,  @strRemarks,
@intFinancialID,''A'',@intCompanycurID,@dtAdjustmentDate)
set @bitjc =0
-- accounting hte net
if @strextype <> '''' and @numexamount <> 0.0
begin
if upper(@strextype) =''I''
set @bitjc = 1
else
set @bitjc = 0
if right(@ADJType, 1) =''D''
exec spConvertequiamount @intDepartmentid, ''d'',
@intexAccountID, ''a'', @strexrates,
@numexAmount, @numAmount output,''''
else
exec spConvertequiamount @intCompanycurID, ''m'',
@intexAccountID, ''a'', @strexrates,
@numexAmount, @numAmount output,''''
--insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
--JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
--( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
--@intexAccountID, @numAmount * @numConExRate, @numAmount,
--@intDepartmentID, @numAmount * @numDepExRate)
----@intexAccountID, @numexAmount * @numConExRate, @numAmount,
----@intDepartmentID, @numexAmount * @numDepExRate)
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intexAccountID, @numexamountCom, @numexamountAccnt,
@intDepartmentID, @numexamountDep)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
end
Declare DetailCur cursor for
SELECT journalcrEDit, AccountID,customerid,vendorid, Amount, consamount FROM
adjustmentdetails WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
open DetailCur
fetch next FROM DetailCur into @bitJC, @intAccountID,
@intcustomerid, @intvendorid, @numdAmount, @numcAmount
while @@Fetch_status =0
begin
if isnull(@intaccountid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intAccountID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intcustomerid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intcustomerID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intvendorid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intvendorID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
fetch next FROM DetailCur into @bitJC,
@intAccountID,  @intcustomerid, @intvendorid, @numdAmount, @numcAmount
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update Adjustmentheader set postED =1 WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid,
@adjType, @strexrates, @numDepExRate, @numConExRate
end
Close JTCur
Deallocate JTCur
set nocount off
end
---------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BackUp]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments_BackUp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--sp_helptext spUpdateLedgersAdjustments
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified : 07/02/2004
-- Modified by   : Hariharan R
--COMMENTS  : RESP AMOUNT posting done for exchange diff acc
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--Modified By   :Benzigar S D
--Modified On   :20/03/2009
--Comment       :Modified Company and Department amount calculation for adjustment
/*
This SP modified and send to SIMDI as emergency. So to keep a back up I changed name of SP and placed in same server.
*/
-------------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateLedgersAdjustments_BackUp] @intCompanyID as int, @intAdjID as int as
begin
set nocount on
Declare
@intjournalId as int,
@intAdjustmentDetailId as int,
@intRowCount as int,
@intCompanycurID as int,
@dtAdjustmentDate as datetime,
@strAdjustmentNo as varchar(50),
@strRemarks as varchar(250),
@numAmount as numeric(18,2),
@numExAmount as numeric(18,2),
@bitJC as bit,
@intAccountID as int,
@intcustomerid as int,
@intvendorid as int,
@numdAmount as numeric(18,2),
@numcAmount as numeric(18,2),
@strextype as char(1),
@intexaccountid as int,
@intfinancialid as int,
@intdepartmentid as int,
@adjType as varchar(2),
@intDepCurrID as int,
@strexrates as varchar(250),
@numDepExRate as numeric(18,8),
@numConExRate as numeric(18,8)
/* getting the maximum Journal ID FROM journal table */
SELECT @intjournalId = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
SELECT @intCompanycurID = CurrencyID FROM acompanymaster
WHERE CompanyID =@intCompanyID
Declare JTcur cursor for
SELECT AdjustmentID, AdjustmentNo, AdjustmentDate, remarks, amount, exchangegain,
accountid, financialid, departmentid, AdjustmentType, Exchangerates,
DepExchangerate, exchangeRate
FROM AdjustmentHeader WHERE cancellED =0 and postED =0 and
CompanyID = @intCompanyID and adjustmentid = @intAdjID
open JTCur
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,
@strexrates, @numDepExRate, @numConExRate
while @@Fetch_status = 0
begin
Select @intDepCurrID = depCurrencyId from aDepartmentMaster where
departmentid = @intdepartmentid
set @intjournalId = @intjournalId + 1
set @intAdjustmentDetailId = 1
insert into moaJournalHeader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate)
values (@intjournalid, @intCompanyID, @dtAdjustmentDate, @strAdjustmentNo,  @strRemarks,
@intFinancialID,''A'',@intCompanycurID,@dtAdjustmentDate)
set @bitjc =0
-- accounting hte net
if @strextype <> '''' and @numexamount <> 0.0
begin
if upper(@strextype) =''I''
set @bitjc = 1
else
set @bitjc = 0
if right(@ADJType, 1) =''D''
exec spConvertequiamount @intDepartmentid, ''d'',
@intexAccountID, ''a'', @strexrates,
@numexAmount, @numAmount output,''''
else
exec spConvertequiamount @intCompanycurID, ''m'',
@intexAccountID, ''a'', @strexrates,
@numexAmount, @numAmount output,''''
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intexAccountID, @numAmount * @numConExRate, @numAmount,
@intDepartmentID, @numAmount * @numDepExRate)
--@intexAccountID, @numexAmount * @numConExRate, @numAmount,
--@intDepartmentID, @numexAmount * @numDepExRate)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
end
Declare DetailCur cursor for
SELECT journalcrEDit, AccountID,customerid,vendorid, Amount, consamount FROM
adjustmentdetails WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
open DetailCur
fetch next FROM DetailCur into @bitJC, @intAccountID,
@intcustomerid, @intvendorid, @numdAmount, @numcAmount
while @@Fetch_status =0
begin
if isnull(@intaccountid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intAccountID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intcustomerid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intcustomerID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intvendorid,0) <> 0
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intvendorID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
fetch next FROM DetailCur into @bitJC,
@intAccountID,  @intcustomerid, @intvendorid, @numdAmount, @numcAmount
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update Adjustmentheader set postED =1 WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid,
@adjType, @strexrates, @numDepExRate, @numConExRate
end
Close JTCur
Deallocate JTCur
set nocount off
end
---------------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAdjustments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Last Modified : 07/02/2004
Modified by   : Hariharan R
COMMENTS  : RESP AMOUNT posting done for` exchange diff acc
Verified by      : Hariharan
Verified Date     : 03/05/2004 (verified From Client DB)
Modified By   :Benzigar S D
Modified On   :20/03/2009
Comment       :Modified Company and Department amount calculation for adjustment
----------------------------------------------------------------------------------------------------
Ref No : 101
Modified By : SHINE DAS
Modified On : 05.05.2011
Comments	: Calcuation of amount which has to be posted to "Exchange Gain/Loss" account was wrong.
-----------------------------------------------------------------
Ref No : 102
Modified By : SHINE DAS
Modified On : 24.02.2012
Comments	: To Correct Account wise Adjustment (client :SIMDI)
-----------------------------------------------------------------------------------------------------
Ref No : 103
Modified By : SHINE DAS
Modified On : 07.05.2012
Comments	: CALCULATION OF EXCHANGE GAIN OR LOSS WAS WRONG IN CONSOLIDATED WISE OPTION.
*/
-----------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateLedgersAdjustments] @intCompanyID as int, @intAdjID as int as
begin
set nocount on
Declare
@intjournalId as int,
@intAdjustmentDetailId as int,
@intRowCount as int,
@intCompanycurID as int,
@dtAdjustmentDate as datetime,
@strAdjustmentNo as varchar(50),
@strRemarks as varchar(250),
@numAmount as numeric(18,2),
@numExAmount as numeric(18,2),
@bitJC as bit,
@intAccountID as int,
@intcustomerid as int,
@intvendorid as int,
@numdAmount as numeric(18,2),
@numcAmount as numeric(18,2),
@strextype as char(1),
@intexaccountid as int,
@intfinancialid as int,
@intdepartmentid as int,
@adjType as varchar(2),
@intDepCurrID as int,
@strexrates as varchar(250),
@numDepExRate as numeric(18,8),
@numConExRate as numeric(18,8),
@numexamountDep  as numeric(18,8),
@numexamountCom  as numeric(18,8),
@numexamountAccnt  as numeric(18,8),
@numExGainorLoss as numeric(18,2),  ---Ref No : 101 New Variable Declared
@numAccAmount as numeric(18,2) ,
@intAccCurrID as int
/* getting the maximum Journal ID FROM journal table */
SELECT @intjournalId = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
SELECT @intCompanycurID = CurrencyID FROM acompanymaster
WHERE CompanyID =@intCompanyID
Declare JTcur cursor for
--SELECT AdjustmentID, AdjustmentNo, AdjustmentDate, remarks, amount, exchangegain,
--accountid, financialid, departmentid, AdjustmentType, Exchangerates,
--DepExchangerate, exchangeRate
--FROM AdjustmentHeader WHERE cancellED =0 and postED =0 and
--CompanyID = @intCompanyID and adjustmentid = @intAdjID
SELECT a.AdjustmentID, a.AdjustmentNo, a.AdjustmentDate, a.remarks, b.ConsAmount,b.ActualAmount,b.Amount , a.exchangegain,
a.accountid, a.financialid, a.departmentid, a.AdjustmentType, a.Exchangerates,
a.DepExchangerate, a.exchangeRate
FROM AdjustmentHeader a inner join AdjustmentDetails b on
a.AdjustmentID = b.AdjustmentID
WHERE a.cancellED =0 and a.postED =0 and
a.CompanyID = @intCompanyID and a.adjustmentid = @intAdjID
open JTCur
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numcAmount,@numAccAmount,@numdAmount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,
@strexrates, @numDepExRate, @numConExRate
while @@Fetch_status = 0
begin
Select @intDepCurrID = depCurrencyId from aDepartmentMaster where
departmentid = @intdepartmentid
Select @intAccCurrID = CurrencyID from aAccountMaster  where
AccountID = @intexaccountid
---------------Ref No : 101 Start
if right(@ADJType, 1) =''D''
begin
-- select @numExGainorLoss = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1) -
--(select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0)
select @numExGainorLoss =isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-
isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)
set @numexamountDep = @numexamount
set @numexamountCom = abs(@numExGainorLoss)
set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
else
begin
--- Ref No : 103  Added Below
select @numexamountDep = abs(isnull((select sum(Amount) from AdjustmentDetails
where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-
		isnull((select sum(Amount) from AdjustmentDetails
		where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0))
---Ref No : 103 Commented below
-- select @numExGainorLoss = isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-
-- isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)
--set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountCom = 0.0
--- Ref No : 103 Added Below
	exec spConvertequiamount @intDepCurrID, ''m'', @intAccCurrID,
	''m'', @strexrates ,@numexamountDep, @numexamountAccnt output,  ''r''
--set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
-----------Ref No : 101 End
/*
----------------------------------------   Ref No : 101 Commented Previous code - Start
if right(@ADJType, 1) =''D''
begin
set @numexamountDep = @numexamount
set @numexamountCom = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
else
begin
set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
set @numexamountCom = @numexamount
set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)
end
------------------------------------------  Ref No : 101 Commented Previous code - End
*/
set @intjournalId = @intjournalId + 1
set @intAdjustmentDetailId = 1
insert into moaJournalHeader (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate)
values (@intjournalid, @intCompanyID, @dtAdjustmentDate, @strAdjustmentNo,  @strRemarks,
@intFinancialID,''A'',@intCompanycurID,@dtAdjustmentDate)
set @bitjc =0
-- accounting hte net
--if @strextype <> '''' and @numexamount <> 0.0
if @strextype <> ''''
begin
if upper(@strextype) =''I''
set @bitjc = 1
else
set @bitjc = 0
if right(@ADJType, 1) =''D''
exec spConvertequiamount @intDepartmentid, ''d'',
@intexAccountID, ''a'', @strexrates,
@numexAmount, @numAmount output,''''
else
exec spConvertequiamount @intCompanycurID, ''m'',
@intexAccountID, ''a'', @strexrates,
@numexamountDep, @numAmount output,''''
--insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
--JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
--( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
--@intexAccountID, @numAmount * @numConExRate, @numAmount,
--@intDepartmentID, @numAmount * @numDepExRate)
----@intexAccountID, @numexAmount * @numConExRate, @numAmount,
----@intDepartmentID, @numexAmount * @numDepExRate)
----------   insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
----------JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
----------( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
----------@intexAccountID, @numexamountCom, @numexamountAccnt,
----------@intDepartmentID, @numexamountDep)
---- Ref No : 103 Added
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intexAccountID, @numexamountCom * @numConExRate, @numexamountAccnt,
@intDepartmentID, @numexamountDep * @numDepExRate)
--- Ref No : 103 Commented
--   insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
--JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
--( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
--@intexAccountID, @numcAmount * @numConExRate, @numAccAmount,
--@intDepartmentID, @numdAmount * @numDepExRate)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
end
Declare DetailCur cursor for
SELECT journalcrEDit, AccountID,customerid,vendorid, Amount, consamount,
	actualamount	------- Ref No : 01  added
	FROM
adjustmentdetails WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
open DetailCur
fetch next FROM DetailCur into @bitJC, @intAccountID,
@intcustomerid, @intvendorid, @numdAmount, @numcAmount,
@numAccAmount  ------- Ref No : 01  added
while @@Fetch_status =0
begin
if isnull(@intaccountid,0) <> 0
--insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
--JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values
--( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
--@intAccountID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
	   --- Ref No : 01 Added Below
		   insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intAccountID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID)
if isnull(@intcustomerid,0) <> 0
--- Ref No : 01 Commented Below
----insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
----JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values
----( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
----@intcustomerID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
		   insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intcustomerID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID)
if isnull(@intvendorid,0) <> 0
--- Ref No : 01 Commented Below
----insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
----JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values
----( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
----@intvendorID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
		 insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intvendorID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
fetch next FROM DetailCur into @bitJC,
@intAccountID,  @intcustomerid, @intvendorid, @numdAmount, @numcAmount
,@numAccAmount  ----shine  added
end
Close DetailCur
Deallocate DetailCur
/* mark the record as postED */
update Adjustmentheader set postED =1 WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numcAmount,@numAccAmount,@numdAmount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,
@strexrates, @numDepExRate, @numConExRate
end
Close JTCur
Deallocate JTCur
set nocount off
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReturnSellingPriceDetail]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReturnSellingPriceDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- created on : 14/07/02
-- Created by  : leo
-- comments : this sp is written so taht it can be called from other servers to fetch
-- the information and get back the result
----------------------------------------------------------------------------------------------
CREATE proc [dbo].[spReturnSellingPriceDetail] @intshopid as int, @intitemid as int as
begin
select isnull(s.sellingPrice,0) sellingprice ,
isnull(s.DiscountPrice,0) DiscountPrice, isnull(s.WholesalePrice,0)
WholesalePrice, isnull(i.dpqty,0) dpqty,
isnull(i.wpqty,0) wpqty,ipd.packingtypeid, a.PackingTypeName
from  aitem i , aitempackingdetail ipd left outer join losshopitemshipmentdetail  s
on ipd.itemid = s.itemid
and ipd.packingtypeid = s.packingtypeid
and (s.shopid is null or s.shopid = @intshopid) ,
apackingtype a
where ipd.packingtypeid = a.packingtypeid
and ipd.itemid = i.itemid
and i.itemid = @intitemid
--and ipd.PackingTypeID = a.packingtypeid
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersBills]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersBills]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last Modified  : 22/01/03
--Modified by  : leo
--Coments   : altered as per the new concept of ex rate
--last modified by Sreejith : 06/04/2010
--Coments   : increased the space between the seperator in remarks column
CREATE proc [dbo].[spUpdateLEDgersBills] @intCompanyID as int, @intbillsid as int as
begin
Declare @intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@strBillsNo as varchar(50),
@dtBillsDate as datetime,
@intDiscountAccID as int,
@intVendorID as int,
@strRemarks as varchar(250),
@intDepartmentID as int,
@numDiscount as numeric(18,2),
@numBillAmt as numeric(18,2),
@intDebitAccID as int,
@numDebitAmt as numeric(18,2),
@intCashBankID as int,
@numvendoramt as numeric(18,2),
@dtutime as datetime,
@numdepRate as numeric(18,9),
@numconsRate as numeric(18,9),
@strexrates as varchar(250),
@numaccamt as numeric(18,2),
@intcurrencyid as int
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
CompanyID = @intCompanyID
SELECT @intBillsID= BillsID, @strBillsno = Billsno, @dtBillsDate = BillDate,
@intVendorID = vendorID, @intDiscountAccID = discountAccountID, @numDiscount = discount,
@numBillAmt = billAmount, @strRemarks = case when (chequeno is null or chequeno ='''')
then remarks else chequeno + '';    '' + remarks end , @intFinancialID = FinancialID,
@intCashBankID = bankcashaccID, @dtutime = updatetime, @intdepartmentid = departmentid,
@strexrates = exchangerates, @numdepRate = depexrate, @numconsrate = exchangerate
FROM Bills WHERE postED =0 and CompanyID = @intCompanyID
and cancellED =0 and billsid = @intbillsid
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
-- get cash or crEDit
if (@intCashBankID is null) --crEDit trans
begin
SELECT @intcurrencyid = CurrencyID FROM avendormaster
WHERE CompanyID = @intCompanyID and vendorID = @intvendorID
insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsNo,
@strRemarks, @intFinancialID, ''B'', @intcurrencyid, @dtBillsDate, @dtutime)
set @numvendoramt =0
Declare DebitBillCur cursor for
SELECT AccountID, Amount FROM Billsdebitdetails
WHERE CompanyID = @intCompanyID and BillsID = @intBillsID
open debitbillcur
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intvendorid, ''v'', @intdebitaccid, ''a'', @strexrates,
@numdebitamt, @numaccamt output
insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, @numDebitAmt * @numconsrate, @numaccamt,
@intDepartmentID, @numDebitAmt * @numdeprate)
set @numvendoramt = @numvendoramt + @numDebitAmt
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
end
close DebitBillCur
deallocate debitbillcur
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intVendorID,
@numvendoramt * @numconsrate, @numvendoramt, @intDepartmentID,
@numvendoramt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
end --for crEDit trans
else
begin  -- cash trans
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID and AccountID = @intcashbankID
insert into moajournalheader (JournalID, CompanyID, JournalDate,
referenceno,  remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsNo,
@strRemarks, @intFinancialID,''B'', @intcurrencyid, @dtBillsDate, @dtutime)
set @numvendoramt =0.0
Declare DebitBillCur cursor for
SELECT AccountID, Amount FROM Billsdebitdetails WHERE
CompanyID = @intCompanyID and BillsID = @intBillsID
open debitbillcur
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
while @@Fetch_status =0
begin
/* inserting the Vendor account with the cost price */
set @numvendoramt = @numvendoramt + @numDebitAmt
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccid, ''a'',
@strexrates, @numdebitamt, @numaccamt output
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, @numDebitAmt * @numconsRate, @numaccamt,
@intdepartmentid, @numDebitAmt * @numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
end
close DebitBillCur
deallocate debitbillcur
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intcashbankID,
@numvendoramt * @numconsrate, @numvendoramt, @intDepartmentid,
@numvendoramt * @numconsrate)
set @intJournalDetailID = @intJournalDetailID +1
end --for cash trans
update Bills set postED =1 WHERE BillsID = @intBillsID and CompanyID = @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRptCustomBalanceSheet]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRptCustomBalanceSheet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By : Sreejith G A
--Created On : 20100806
--spRptCustomBalanceSheet ''20101212'',1
--select * from CustomBalanceSheet
create  proc [dbo].[spRptCustomBalanceSheet] (@strToDate as varchar(10), @intCompanyID as int) as
Begin
set nocount on
Declare @AcCode as varchar(100),
@AcID as int,
@dblDebit as numeric(18,2),
@dblCredit as numeric(18,2),
@GroupDesc as varchar(100),
@GroupID as int,
@dtToDate as datetime,
@dtFromDate as datetime,
@strFromdate as varchar(10),
@intCount as integer,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(1000),  --jyothish changed 250 to 1000
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #BalSheet(
CompanyID int,
AccCode varchar(100),
AcDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
OBDr numeric(18,2),
OBCr numeric(18,2),
DebitAmt numeric(18,2),
CreditAmt numeric(18,2),
ParentGroupID int,AccId int,departmentid int)
Create table #BalSheetFinal(
Departmentid int ,
AccId int,
AccCode varchar(30),
AcDesc varchar(250),
AcType varchar(5),
GroupID int,
GroupName varchar(50),
DepartmentName varchar(50),
Balance numeric(18,2) )
--delete from CustomBalanceSheet
--Create table CustomBalanceSheet (Departmentid int ,AccId int,AccCode varchar(30),AcDesc varchar(50),
--AcType varchar(5),GroupID int ,GroupName varchar(50),DepartmentName varchar(50),Balance numeric(18,2))
set @dtToDate = CONVERT(DATETIME,@strToDate)
select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(day, -1, @dtFromDate )
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId and FinancialId <= @intFinId
if @intLastFinId = 0
Select @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
insert #vwJournalDetails
Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
Journaldate>=@dtPrevFinUnclosedSDate and
JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, ------NEW MODIFIED
OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, departmentid)
select  vss.CompanyId, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,
vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.AccountID,vss.departmentid
from
(SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid
from aaccountfinyearopening ad
left outer join   aaccountmaster AM on AM.accountid=ad.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
union all
SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,
GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid
from  #vwJournalDetails v
left outer join   aaccountmaster AM on AM.accountid=v.accountid
left outer join agroupmaster gm on GM.GroupID = AM.GroupID
)vss
where
-- (VSS.AccountType = ''A'' OR VSS.AccountType = ''L'') AND
VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
GroupDesc,ParentGroupID
Update #BalSheet set  OBDr = opening.Openingamount from (Select AccountId,
CompanyId, Sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,
AccountId,departmentid) opening Where opening.Accountid = #BalSheet.AccId and
opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
and opening.departmentid= #BalSheet.departmentid
Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and #BalSheet.AcType =''A'' and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set  OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''A''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''L''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''E''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''E''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''I''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb
Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType =''I''
and trialDeb.departmentid=#BalSheet.departmentid
Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.Departmentid From #vwJournalDetails v,
#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and
h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId, v.Departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID
and trialDeb.CompanyId = @intCompanyId and trialDeb.Departmentid=#BalSheet.departmentid
Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From
#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
group by v.CompanyId, v.AccountId, v.departmentid) trialDeb Where
trialDeb.Accountid = #BalSheet.AccId and
trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
and trialDeb.departmentid = #BalSheet.departmentid
Insert #BalSheetFinal(Departmentid,AccId,AccCode,AcDesc,AcType,GroupID,GroupName,DepartmentName,Balance)
SELECT b.Departmentid,b.AccId,b.AccCode,b.AcDesc,b.AcType,b.GroupId,b.Groupname,ad.departmentname,
case when AcType=''A'' then (isnull(obdr,0) + isnull(debitamt,0) - isnull(creditamt,0))
when AcType=''L'' then (isnull(obdr,0) + isnull( creditamt,0) - isnull(debitamt,0))
when AcType=''E'' then (isnull(debitamt,0) + isnull(obdr,0) - isnull( creditamt,0) - isnull(obcr,0))
when AcType=''I'' then (isnull( creditamt,0) + isnull(obcr,0) -isnull(debitamt,0) - isnull(obdr,0)  )
end
from  #balsheet b
left outer join adepartmentmaster ad on ad.departmentid=b.departmentid
where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))
<> 0 and isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''L'')
or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''E'')
or ((isnull(obdr,0) + isnull(obcr,0) +
isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'''') =''I'')
and
b.accCode is not null) or b.accCode is null)
set @GroupId = 0
--insert into CustomBalanceSheet (Departmentid,AccId,AccCode,AcDesc,AcType,GroupID,GroupName,DepartmentName,Balance)
Select Departmentid,AccId,AccCode,AcDesc,AcType,GroupID,GroupName,DepartmentName,Balance from #BalSheetFinal   --where actype=''i''
drop table #BalSheet
drop table #Tempjournalheader
drop table #vwJournalDetails
Drop table #BalSheetFinal
set nocount off
End
--Create table CustomBalanceSheet (Departmentid int ,AccId int,AccCode varchar(30),AcDesc varchar(50),
--AcType varchar(5),GroupID int ,GroupName varchar(50),DepartmentName varchar(50),Balance numeric(18,2))
--
--
--select * from CustomBalanceSheet where AccId=887' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetServiceHistory]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetServiceHistory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
CREATED BY : SHINE DAS
CREATED ON : 24.08.2011
PURPOSE	   : TO SHOW SERVICE HISTORY OF GIVEN ITEM.
*/
create PROC [dbo].[spGetServiceHistory](@shopID AS INT,@itemId AS INT, @slNumber AS VARCHAR(100)) AS
BEGIN
SELECT
1 transtype, ''Parts Replaced'' ServiceType,InvH.serinvhid, InvH.serinvno InvoiceNo,serinvhprocno JobCardNo,
serinvhdate,vw.code,Invprlcd.repinvdpartsid ReplacedItemID,replVW.code ReplacedItemCode,replVW.itemdescription ReplacedItemDesc,
serCallBkhitemid ItemID, VW.itemdescription,Invprlcd.repinvdserialno NewSerialNo,
sbk.serCallBkhSerialNo SerialNo,InvH.serinvhpartsamt,SBK.serCallBkhcustomerid,sbk.serCallBkhcustomerName
FROM
losInvoicedPartsReplacedetails Invprlcd
LEFT JOIN losserviceinvheader InvH ON Invprlcd.repinvinvoiceid=InvH.serinvhid AND Invprlcd.repinvdshopid=InvH.serinvhshopid
LEFT JOIN losserviceheader lsh ON lsh.serinvhid=InvH.serinvhjobcardid AND InvH.serinvhshopid=lsh.serinvhshopid
LEFT JOIN loscallbookingheader sbk ON lsh.serinvhbookingid=sbk.serCallBkhid AND lsh.serinvhshopid=sbk.serCallBkhshopid	
LEFT JOIN vwItemDescription VW ON SBK.serCallBkhitemid=VW.ItemID
LEFT JOIN vwItemDescription replVW on Invprlcd.repinvdpartsid=replVW.ItemID
WHERE
sbk.serCallBkhCallShopID=@shopID AND sbk.serCallBkhSerialNo=@slNumber AND SBK.serCallBkhitemid=@itemId
UNION ALL
select 2 transtype,sername name,serCallBkhid,serCallBkhno InvoiceNo,'''' JobCardNo,serCallBkhdate,vw.code,
0 ReplacedItemID,'''' ReplacedItemCode,'''' ReplacedItemDesc,serCallBkhitemid ItemId,
vw.itemdescription  itemdescription, '''' NewSerialNo,serbookhSerialNumber SerialNo,
serbkdcharge charge,serCallBkhcustomerid, serCallBkhcustomerName
from losservicebookingheader lbh,losbookservicedetails lbs,
aservicemaster asm,loscallbookingheader cbh,vwItemDescription vw  where lbh.serbookhid = lbs.serbkdbookid and lbh.serbookhshopid =  lbs.serbkdshopid
and lbh.serbookhcompanyid =  lbs.serbkdcompanyid and  lbs.serbkdserviceid = asm.serid and serCallBkhitemid=vw.ItemID and
lbs.serbkdcompanyid = asm.sercompanyid  and cbh.serCallBkhid=lbh.serbookhRefId and cbh.serCallBkhShopID=lbh.serbookhshopid
and serbookhSerialNumber=@slNumber and serCallBkhitemid=@itemId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHandlingDebitNote]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHandlingDebitNote]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By 	: R Harikrishnan, Thomas Dheena
--Created on	: 09/07/2003, 09/12/2003
--Comments	: For Handling Debit note report
--modifed dheena add due period
-----------------------------------------------------------------------
CREATE proc [dbo].[spHandlingDebitNote]
	(	
		@intShopID 	as int,
		@intDCNID 	as int
	)
as
Select
	dh.losDCNNo,dh.losDCNDate,dh.losReferenceno,dh.losDCNDetails,cm.CustomerName,curr.Symbol,
	ld.ClearenceID,ld.POID,ld.BoatNoteID,ld.Amount,ld.ResAmount,ld.BoatNoteDetID,
	ld.ClearenceDetID,ocd.ClearenceNo,ocd.ocDescription,ocd.ClearenceReqNo,
	ocd.POno ClrReqPONO,ocd.VendorName ClrReqVendorName,lh.PONo LPPONo,
	lh.LPClrReqPONo,lh.VendorName LPClrReqVendorName,bnd.bnhBoateNoteNo,bnd.OCDesc,
	dateadd(d,dh.losDCNDueperiod,dh.losDCNDate) duedate
From
	losDebitCreditNote dh,aCustomerMaster cm,aCurrencyMaster curr,
	losDebitCreditNoteDetail ld
	left outer join (select
		oc.shopID,oc.ClearenceID,oc.DetailID,oc.ocDescription,ch.ClearenceNo,
		rh.ClearenceReqNo,rh.PONo,rh.VendorName
	From
		ShipmentClearenceOCDetails oc, ShipmentClearenceHeader ch,
		ClearenceRequestHeader rh
	Where
		oc.ShopID=ch.ShopID and oc.ClearenceID=ch.ClearenceID and
		oc.ShopID=rh.ShopID and oc.ClearenceReqID=rh.ClearenceReqID) ocd
	on ld.ShopID=ocd.ShopID and ld.ClearenceID=ocd.ClearenceID and
	ld.ClearenceDetID = ocd.DetailID
	left outer join (select
		lph.shopID,lph.POID,lph.PONo,crh.ClearenceReqNo,crh.PONo LPClrReqPONo,
		vm.VendorName
	From
		LosLPHeader lph, losLocalClearenceRequestHeader crh,aVendorMaster vm
	Where
		lph.ShopID=crh.ShopID and lph.ClearenceReqID=crh.ClearenceReqID and
		lph.VendorID=vm.vendorID)lh
	on ld.ShopID=lh.ShopID and ld.POID=lh.POID
	left outer join (select
		bd.shopID , bd.BoatNoteID, bd.DetailID, bd.OCDesc, bh.bnhBoateNoteNo
	From
		losShipmentBNOCDetail bd, losShipmentBNHeader bh
	Where
		bd.ShopID=bh.bnhShopID and bd.BoatNoteID=bh.bnhBoatNoteID) bnd
	on ld.ShopID=bnd.ShopID and ld.BoatNoteID=bnd.BoatNoteID and
	ld.BoatNoteDetID = bnd.DetailID
Where
	dh.losDCNShopID=ld.ShopID and dh.losDCNID=ld.DCNID and
	dh.losDCNCustomerID=cm.CustomerID and dh.losDCNShopID=@intShopID And
	cm.CompanyID=curr.CompanyID and cm.CurrencyID=curr.CurrencyID and
	dh.losDCNID=@intDCNID and dh.losDCNtype=''H''
order by ld.ShopID,ld.DCNID,ld.DetailID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGITDifference]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGITDifference]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--EXEC spGITDifference ''20090101'',''20091231''
create PROC [dbo].[spGITDifference](@strFromDate as varchar(10),@strtodate as varchar(10)) AS
BEGIN
DECLARE @COSTINGID AS INT
DECLARE @COSTINGNO AS VARCHAR(25)
DECLARE @COSTINGDATE AS datetime
DECLARE @BILLID AS INT
dECLARE @DEPARTMENTID AS INT
DECLARE @BILLAMOUNT as NUMERIC(18,2)
DECLARE @PAYMENTAMT AS NUMERIC(18,2)
DECLARE @LCAMOUNTAS NUMERIC(18,2)
DECLARE @Total NUMERIC(18,2)
DECLARE @GITACCOUNTID AS INT
DECLARE @BILLNUM  AS VARCHAR(25)
DECLARE @POID AS INT
CREATE table #Detail ( DepartmentID int, CostingID int, CostingNo nvarchar(25), CostingDate datetime, CostingAmt numeric(18,2), BillID int, BillNo varchar(25), Debitamt numeric(18,2),LCAmount numeric(18,2) )  DECLARE CURDETAIL CURSOR FOR
SELECT
chCostingID,chCOSTINGNO,chCostingDate,chBillID,chDepartmentID
FROM
LOaCostingHeader
WHERE
chCancelled=0 and
chCostingDate>= @strFromDate  and chCostingDate<=@strtodate
select @GITACCOUNTID=GoodsInTransitID  from apackagesettings
OPEN CURDETAIL
FETCH next FROM CURDETAIL into  @COSTINGID,@COSTINGNO,@COSTINGDATE,@BILLID, @DEPARTMENTID
WHILE @@Fetch_status = 0
BEGIN
INSERT INTO #Detail VALUES(@DEPARTMENTID,@COSTINGID,@COSTINGNO,@COSTINGDATE,NULL,@BILLID,NULL,NUll,null)
UPDATE #Detail SET CostingAmt= (
select  d.Amount  from moajournalheader h  inner join moajournaldetails d   on h.journalid=d.Journalid
where   h.Cancel=0 and  d.AccountID=@GITACCOUNTID and  ReferenceNo=@COSTINGNO)
WHERE CostingID=@COSTINGID
--UPDATE #Detail SET CostingAmt= (
--SELECT sum(cdCostingPrice*cdItemQuantity) FROM loacostingdetail WHERE cdcostingid=@COSTINGID )
--WHERE CostingID=@COSTINGID
select @BILLNUM=pbhBillNo ,@POID=pbhPOID from
LOspPurchaseBillHeader where pbhBillID=@BILLID and pbhCancelled=0
--UPDATE #Detail SET BillNo= (select pbhBillNo from LOspPurchaseBillHeader where pbhBillID=@BILLID and pbhCancelled=0 )
-- WHERE CostingID=@COSTINGID
UPDATE #Detail SET BillNo= @BILLNUM
WHERE CostingID=@COSTINGID
--set @BILLAMOUNT=(select sum(pbhBillAmount*pbhexchangerate) from LOspPurchaseBillHeader where pbhBillID=@BILLID and pbhCancelled=0)
set @BILLAMOUNT=(select  isnull(sum(d.Amount),0)  from moajournalheader h  inner join moajournaldetails d   on h.journalid=d.Journalid
where   h.Cancel=0 and  d.AccountID=@GITACCOUNTID and  ReferenceNo=@BILLNUM )
SET @PAYMENTAMT= (SELECT isnull(sum(pddAmount*phexchangerate),0) FROM   LOaCostingHeader left outer join LOspPurchaseBillHeader on chBillID=pbhBillID   left outer join ahqpaymentvoucherdebitdetails on pbhPOID=pddhqpoid  left outer join ahqpaymentvoucherheader
on pddPaymentID=phPaymentID  WHERE  phcancelled=0 and  chCostingID= @COSTINGID and  pbhBillID=@BILLID  and phlcpayment<>''LCO'' and phlcpayment<>''LCM'' )
set  @LCAMOUNTAS =(select  isnull(d.Amount,0)amount  from moajournalheader h  inner join moajournaldetails d   on h.journalid=d.Journalid
where   h.Cancel=0 and  d.AccountID=@GITACCOUNTID and  ReferenceNo in (
select phPaymentNo from aHQpaymentvoucherheader hq inner join aHqPaymentVoucherDebitDetails dt
on hq.phPaymentID=dt.pddPaymentID where  phCancelled=0 and pddhqpoid is not null
and phlcpayment=''LCM''and pddhqpoid=@POID))
-- set @Total=@PAYMENTAMT+@BILLAMOUNT
set @Total=@PAYMENTAMT+@BILLAMOUNT
UPDATE #Detail SET Debitamt=@Total,LCAmount=@LCAMOUNTAS WHERE CostingID=@COSTINGID
FETCH NEXT FROM  CURDETAIL INTO  @COSTINGID,@COSTINGNO,@COSTINGDATE,@BILLID, @DEPARTMENTID
END
CLOSE CURDETAIL
DEALLOCATE CURDETAIL
--SELECT dt2.DepartmentName ,dt.* FROM #Detail dt1, adepartmentmaster dt2 where dt2.DepartmentID=dt1.DepartmentID
SELECT DepartmentName,dt1.DepartmentID,CostingID,CostingNo,CostingDate,CostingAmt,BillID,BillNo,isnull(Debitamt,0) Debitamt,isnull(LCAmount ,0) lcAmount  FROM #Detail dt1,adepartmentmaster dt2 where  dt2.DepartmentID=dt1.DepartmentID order by dt1.DepartmentID
DROP TABLE #Detail
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReverseShopTotalStockVerification]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseShopTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------
-- Created By 		: Kishore
-- Created Date  	: 27/08/2003
-- Comments		: Reverses the stock updation of ''Total Stock Verification
--                        Taken from v2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spReverseShopTotalStockVerification] (@VerificationID int,
				@ShopId int) AS
Begin
	declare
	@cur_verid int,
	@cur_ShopId int,
	@cur_ItemId int,
	@cur_ItemGoodQty numeric(18,3),
	@cur_itemBadQty numeric(18,3),
	@cur_AvailGoodQty numeric(18,3),
	@cur_availBadQty numeric(18,3),
	@cur_packingtypeid int,
	@cur_cost numeric(18,2),
	@cur_ShipmentID int,
	@recCount as int
	set nocount on
	declare cursor_Detail  cursor for
	        select svdid, svdShopId, svdItemId, svdVerifiedStock, svdVerifiedBadStock,
		svdCostPrice, svdShipmentId, svdAvailStock, svdAvailBadStock
		from losStockVerificationDetail
		where svdid = @VerificationID and svdShopId = @ShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_verid, @cur_ShopId, @cur_ItemId,
		@cur_ItemGoodQty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
		@cur_AvailGoodQty, @cur_availBadQty
	While @@fetch_status = 0
	Begin
		-- reverse stock of items entered by user
		If @cur_AvailBadQty = 1
		Begin
			update mosShopStock
				set Stock = Stock + @cur_AvailGoodQty - @cur_ItemBadQty
				where ItemId = @cur_ItemId
				and ShopId = @cur_ShopId
		End		
		Else	-- Reverse stock of items entered by system
		
		Begin
			update mosShopStock
				set Stock = Stock + @cur_AvailGoodQty --  - @cur_ItemGoodQty
				where ItemId = @cur_ItemId
				and ShopId = @cur_ShopId
		End
		fetch next from cursor_Detail into
			@cur_verid, @cur_ShopId, @cur_ItemId,
			@cur_ItemGoodQty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
			@cur_AvailGoodQty, @cur_availBadqty
	End
	Close cursor_Detail
	Deallocate cursor_Detail
	Return 0
End
--------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetTransfer]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetTransfer]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- create date : 20/03/2004, 08/04/2004, 16/04/2004
--- create by  : Hariharan R, Hariharan R
--- pupose     : posting all transfer asset information
--	       : account transfer posted with dep value for acc dep accounts	
--	       : from dep Exchange Rate Correctly given for dep exchangerate
--******************************************************
CREATE PROC [dbo].[spUpdateLedgersAssetTransfer] @intassettransid as int ,
@intcompanyid as int as
begin
	Declare
	@strasttrransno as varchar(50),
	@dtasttransdate as datetime,
	@intasttransassetid as int,
	@intasttransfromdepid as int,
	@intasttranstodepid as int,
	@numasttransvalue as numeric(18,2),
	@intfixedassetaccid as int,
	@strexrates as varchar(50),
	@intFinancialID as int,
	@strasttransremarks as varchar(250),
	@numfromdepRate as numeric(18,8),
	@numtodepRate as numeric(18,8),
	@numconsRate as numeric(18,8),
	@intJournalID as int,
	@intJournalDetailID as int,
	@inttransferaccountid as int,
	@numaccamt  numeric(18,8),
	@intAstTransFromACCID as int,
	@intAstTransToACCID as int ,
	@OrgDepartmentId as int,
	@numAccDepValue as numeric(18,2),
	@intAccDepAccId as int,
	@intFromACCDeprAccId as int,
	@intToACCDeprAccId as int
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
	CompanyID = @intCompanyID
		
	set @intJournalDetailID = 1
	set @intJournalID = @intJournalID + 1	
	begin
		SELECT @strasttrransno=asttrransno ,
		@dtasttransdate=ast.asttransdate ,@intasttransassetid = ast.asttransassetid,
		@intasttransfromdepid = ast.asttransfromdepid,
		@intasttranstodepid = ast.asttranstodepid,
		@numasttransvalue =ast.asttransvalue, @intfixedassetaccid=fa.fixedassetaccid ,
		@numAccDepValue = AST.astDeprValue, @strexrates=ast.exchangerates ,
		@intFinancialID = ast.financialid, @strasttrransno = ast.asttrransno,
		@strasttransremarks = ast.asttransremarks, @numfromdepRate = fromdepexrate,
		@numtodepRate = todepexrate, @numconsRate = consexrate,
		@intAstTransFromACCID = FromAssetAccId,
		@intAstTransToACCID = ToAssetAccID, @OrgDepartmentId = DepartmentID,
		@intAccDepAccId = DepreciationAccId, @intFromACCDeprAccId = FromACCDeprAccId,
		@intToACCDeprAccId = ToACCDeprAccId
		FROM fixedasset fa, assettransfer  ast  WHERE fa.FixedAssetID = ast.asttransid
		and ast.asttranscompanyid = fa.CompanyID and ast.asttransposted =0 and
		ast.asttranscompanyid =  @intCompanyID and ast.asttransid=@intassettransid
		--check whether asset departmenttransfer or account transfer 	
		if @intasttranstodepid is not null
			begin 			
				select @inttransferaccountid = transferaccount from asettings
				insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,
				remarks, financialID,Type,chequedate)
				values (@intJournalID, @intCompanyID, @dtasttransdate,@strasttrransno,
			        @strasttransremarks, @intFinancialID, ''ASTR'', @dtasttransdate)			
				exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'',
				@strexrates, @numasttransvalue, @numaccamt output			
		
				insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,
				departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
				@intasttransfromdepid, @numasttransvalue * @numfromdepRate, 1)
		
				set @intJournalDetailID = @intJournalDetailID + 1			
	
				exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
				@strexrates, @numasttransvalue, @numaccamt output						    	
				insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@inttransferaccountid, @numasttransvalue * @numconsrate, @numaccamt,
				@intasttransfromdepid, @numasttransvalue * @numfromdepRate, 1)
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'',
				@strexrates, @numasttransvalue, @numaccamt output			
	
				insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
				 @intasttranstodepid, @numasttransvalue * @numtodepRate, 2)
			
	
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
				@strexrates, @numasttransvalue, @numaccamt output			
			    	
				insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@inttransferaccountid, @numasttransvalue * @numconsrate, @numaccamt,
				@intasttranstodepid, @numasttransvalue * @numtodepRate, 2)
				-- Depritiation 	
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @intFromACCDeprAccId, ''a'',
				@strexrates, @numAccDepValue, @numaccamt output			
	
				insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
				 @intasttransfromdepid, @numAccDepValue * @numfromdepRate, 3)
				
				if @numAccDepValue <> 0 			
				Begin
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
				@strexrates, @numAccDepValue, @numaccamt output			
			    	
				insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
				depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@inttransferaccountid, @numAccDepValue * @numconsrate,
				@numaccamt, @intasttransfromdepid,
				@numAccDepValue * @numfromdepRate, 3)
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @intFromACCDeprAccId, ''a'',
				@strexrates, @numAccDepValue, @numaccamt output			
	
				insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
				 @intasttranstodepid, @numAccDepValue * @numtodepRate, 4)
			
	
				set @intJournalDetailID = @intJournalDetailID + 1				
				exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
				@strexrates, @numAccDepValue, @numaccamt output			
			    	
				insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@inttransferaccountid, @numAccDepValue * @numconsrate, @numaccamt,
				@intasttranstodepid, @numAccDepValue * @numtodepRate, 4)
				End
		end
	else
		begin
			insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,
			remarks, financialID,Type,chequedate)
			values (@intJournalID, @intCompanyID, @dtasttransdate,@strasttrransno,
		        @strasttransremarks, @intFinancialID, ''ASTR'', @dtasttransdate)			
		
			exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'', @strexrates,
			@numasttransvalue, @numaccamt output			
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
			@intasttransfromdepid, @numasttransvalue * @numfromdepRate, 1)
		
			set @intJournalDetailID = @intJournalDetailID + 1				
			exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransToACCID, ''a'', @strexrates,
			@numasttransvalue, @numaccamt output			
			    	
			insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intAstTransToACCID, @numasttransvalue * @numconsrate, @numaccamt,
			@intasttransfromdepid, @numasttransvalue * @numfromdepRate, 1)
			IF @numAccDepValue <> 0
			Begin
			set @intJournalDetailID = @intJournalDetailID + 1	
			-- ACCUM DEP ACC TRANSFER DEBITED IN FROM ACCOUNT
			exec spConvertequiamount @intasttransfromdepid, ''d'',
			@intFromACCDeprAccId, ''a'', @strexrates,
			@numAccDepValue, @numaccamt output			
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
			@intasttransfromdepid, @numAccDepValue * @numfromdepRate, 2)
		
			set @intJournalDetailID = @intJournalDetailID + 1
				
			-- ACCUM DEP ACC TRANSFER CREDITED IN TO ACCOUNT
			exec spConvertequiamount @intasttransfromdepid, ''d'', @intToACCDeprAccId, ''a'', @strexrates,
			@numAccDepValue, @numaccamt output			
			    	
			insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intToACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
			@intasttransfromdepid, @numAccDepValue * @numfromdepRate, 2)
			End			
		end 	
	end
		update assettransfer set asttransposted =1 WHERE
			asttransid=@intassettransid and asttranscompanyid =  @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetRegister]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetRegister]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--MOdified By : Hariharan , Hariharan
--Modified on ; 04/03/2004, 16/04/2004
--Removed referno and add fixedassetno
--Corrected to give credit to the conversion acccountid and to debit the diffacc and asset register
-- Included PostGroup column in MoaJournalDetails insertion query
CREATE procedure [dbo].[spUpdateLedgersAssetRegister] @intassetregid as int ,
@intcompanyid as int as
	begin
	Declare @intbillrefid as int,
	@intfixedassetit as int,
	@FixedAssetID as int,
	@intfixedassetaccid as int,
	@intwriteoffrefid as int,
	@intconversiondiffaccid as int,
	@intJournalID as int,
	@intJournalDetailID as int,
	@intFinancialID as int,
	@strrefNo as varchar(50),
	@dtfixedassetDate as datetime,
	@strRemarks as varchar(250),
	@numrefamount as numeric(18,2),
	@numAssetValue as numeric(18,2),
	@numDiffValue as numeric(18,2),
	@numvendoramt as numeric(18,2),
	@dtutime as datetime,
	@numdepRate as numeric(18,9),
	@numconsRate as numeric(18,9),
	@strexrates as varchar(250),
	@numaccamt as numeric(18,2),
	@intcurrencyid as int,
	@intdepid as int,
	@intAssetConversionAccid as int
	
	
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
	CompanyID = @intCompanyID
		
	set @intJournalDetailID = 1
	set @intJournalID = @intJournalID + 1	
	begin
		SELECT @intbillrefid=fa.billsrefid,@intwriteoffrefid=fa.writeoffrefid ,
		@FixedAssetID=fa.FixedAssetID ,@strrefNo = FixedAssetNo,
		@intfixedassetaccid=fa.FixedAssetAccID, @dtfixedassetDate = FixedAssetDate,
		@strRemarks =fa.Remarks, @intFinancialID = fa.FinancialID,
		@intdepid = fa.departmentid, @numconsrate =fa.exrate, @numdepRate = fa.depexrate,
		@strexrates = fa.exchangerates , @numrefamount=fa.actrefamount,	
		@intconversiondiffaccid=fa.conversiondiffaccid, @numAssetValue = fa.costprice,
		@numDiffValue = fa.conversiondiff FROM fixedasset fa  WHERE postED =0 and
		fa.CompanyID =  @intCompanyID and FixedAssetID=@intassetregid
		--Get vendor currency id 	
		SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
		WHERE CompanyID = @intCompanyID and accountid = @intfixedassetaccid
		set @numvendoramt =0
		
		insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,
		remarks, financialID,Type,CurrencyID,chequedate, updatetime)
		values (@intJournalID, @intCompanyID, @dtfixedassetDate,@strrefNo,
	        @strRemarks, @intFinancialID, ''AST'', @intcurrencyid,@dtfixedassetDate, @dtutime)			
		
		if (@intbillrefid is not null)
		    begin
			if @numDiffValue>0
			begin
			exec spConvertequiamount @intfixedassetaccid, ''a'',
			@intconversiondiffaccid, ''a'', @strexrates,
			@numDiffValue, @numaccamt output, ''''			
	
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intconversiondiffaccid, @numDiffValue * @numconsrate, @numaccamt,
			@intDepID, @numDiffValue * @numdeprate)
	
			set @intJournalDetailID = @intJournalDetailID + 1				
			    	
			insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, vendorID, Amount, actualAmount,departmentid, depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intfixedassetaccid, @numDiffValue * @numconsrate, @numDiffValue,
			@intDepID, @numDiffValue * @numdeprate)
			end
		    end 	
		else
		  begin
			select @intAssetConversionAccid= AssetConversionAccid  from
			apackagesettings where companyid=@intCompanyID
			set @numvendoramt = (@numAssetValue+@numDiffValue)
			--add asset diff amount and asset amount
			exec spConvertequiamount @intfixedassetaccid, ''a'',
			@intAssetConversionAccid, ''a'', @strexrates,
			@numAssetValue, @numaccamt output, ''''								
			set @intJournalDetailID = @intJournalDetailID + 1	
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intAssetConversionAccid, @numAssetValue * @numconsrate,
			@numaccamt, @intDepID, @numAssetValue * @numdeprate,1 )
	
			if @numDiffValue>0			
			begin
			set @intJournalDetailID = @intJournalDetailID + 1	
			--add asset diff amount and asset amount
			exec spConvertequiamount @intfixedassetaccid, ''a'',
			@intAssetConversionAccid, ''a'', @strexrates,
			@numDiffValue, @numaccamt output, ''''								
			set @intJournalDetailID = @intJournalDetailID + 1	
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intAssetConversionAccid, @numDiffValue * @numconsrate,
			@numaccamt, @intDepID, @numDiffValue * @numdeprate, 2 )
			set @intJournalDetailID = @intJournalDetailID + 1	
			
			exec spConvertequiamount @intfixedassetaccid, ''a'',
			@intconversiondiffaccid,  ''a'', @strexrates,
			@numDiffValue, @numaccamt output,''''								
			    		
			insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit,AccountID, vendorID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intconversiondiffaccid, NULL,
			@numDiffValue * @numconsrate, @numaccamt, @intDepID,
			@numDiffValue * @numdeprate, 2)
			end
			set @intJournalDetailID = @intJournalDetailID + 1		
	    		--to debit asset account with the net value
			insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit,AccountID, vendorID, Amount, actualAmount,departmentid,
			depamount, PostGroup)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intfixedassetaccid, NULL,
			@numassetvalue  * @numconsrate, @numassetvalue, @intDepID,
			@numassetvalue * @numdeprate, 1)
		end
	end
		update fixedasset set postED =1 WHERE fixedassetid = @FixedAssetID
			and CompanyID = @intCompanyID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownStockSpecial]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownStockSpecial]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--MOdified by 	: Hariharan R
--Modified Date : 26/12/2002
--Comments 	: V3
--MOdified by 	:venkitesh.A.s
--Modified Date : 17/09/2003
--Comments 	: V3
--MOdified by removing the locationis
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE proc [dbo].[SpUpdateGodownStockSpecial](@despatchid int,@Godownid int,@process char(1)) as
declare
@cur_despatchid int,
@cur_godownid int,
@cur_shipmentid int,
@cur_itemid int,
@cur_itembadqty numeric(18,3),
@cur_itemgoodqty numeric(18,3),
@intcount as int
set nocount on
set @intcount=0
declare cursor_Detail  cursor for
	select dddespatchid, ddgodownid, ddshipmentid, dditemid, dditembadqty,
	dditemgoodqty from MeiSpecialDespatchtoshopdetail
	where dddespatchid = @despatchid and ddgodownid = @Godownid
open cursor_Detail
fetch next from cursor_Detail into
@cur_despatchid, @cur_godownid,@cur_shipmentid,@cur_itemid,
@cur_itembadqty,@cur_itemgoodqty
while @@fetch_status = 0
begin
	--added by venki forinserting empty row if itemcount=0
			select @intCount = count(*) from moigodownStock
			where gsitemid = @cur_Itemid and gsgodownid= @godownid
			if @intCount =0
			Begin
				insert moigodownStock (gsgodownID,gsStockDate, gsShipmentID, gsItemID,
				gsOpeningStock, gsStock, gsOpeningBadStock, gsBadStock)
				Select @godownid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
			End
			--
	if @process = ''R''
		update moigodownstock set gsstock = gsstock + @cur_itemgoodqty
		where gsitemid = @cur_itemid and gsshipmentid = @cur_shipmentid
		and gsgodownid = @cur_godownid
	if @process = ''F''
	begin
		update moigodownstock set gsstock = gsstock - @cur_itemgoodqty
		where gsitemid = @cur_itemid and gsshipmentid = @cur_shipmentid
		and gsgodownid = @cur_godownid
	end
	fetch next from cursor_Detail into
	@cur_despatchid, @cur_godownid,@cur_shipmentid,@cur_itemid,
	@cur_itembadqty,@cur_itemgoodqty
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGodownExpiryTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownExpiryTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by	: Kishore
-- Created on	: 25/08/2003
-- Comments     : This sp updates the Expiry wise stock in total stock verification
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spGodownExpiryTotalStockVerification](@intItemId as int,
							@intGodownId as int,
							@intSvdId as int,
							@dtUpdate as DateTime,
							@intArrivalDetailId as int OUTPUT,
							@intIssueDetailId as int OUTPUT) AS
Begin
	Declare @numSalesQty as Numeric(18, 8)
	Declare @numVerifiedQty as Numeric(18, 3)
	Declare @dtExpiryDate as DateTime
	Declare @numCurExpiryStock as Numeric(18, 3)
	print @intArrivalDetailId
	-- open the cursor to loop through the Expirys
	Declare curExpiry Cursor for
		SELECT eadExpiryDate, eadItemQty FROM loiExpiryArrivalDetails
		WHERE eadGodownId = @intGodownId
		AND eadTransactionId = @intSvdId
		AND eadInterfaceId = 8010
		AND eadCancel = 1
	Open curExpiry
	Fetch Next From curExpiry Into @dtExpiryDate, @numVerifiedQty
	While @@fetch_status = 0
	Begin
	
		-- get the sum qty involved in transactions
		-- in this case only special despatch to shop is transacted
		SELECT @numSalesQty = SUM(eidItemQty)
			FROM loiExpiryIssueDetails
			WHERE eidTransactionId IN
				(SELECT ddDespatchId
				FROM meiSpecialDespatchToShopDetail Detail,
				meiSpecialDespatchToShopHeader Header
				WHERE Detail.ddDespatchId = Header.dhDespatchId
				AND Detail.ddGodownId = Header.dhGodownId
				AND Detail.ddItemId = @intItemId
				AND Header.UpdateTime >= @dtUpdate	
				AND ddGodownId = @intGodownId)
				AND eidGodownId = @intGodownId
				AND eidInterfaceId = 5009 -- interfaceid of special despatch to shop
				AND eidItemId = @intItemId
				AND eidExpiryDate = @dtExpiryDate
		-- make the Expiry stock of specified item at
		-- specified Expiry to zero
		-- first get the currect Expiry stock
	SELECT @numCurExpiryStock = qty
	FROM
	(SELECT ExpiryDate, GodownId,
		ItemId, SUM(qty) qty
	        FROM
		(SELECT eadExpiryDate ExpiryDate,
		eadGodownId GodownId, eadItemId ItemId , SUM(eadItemQty) qty
	FROM loiExpiryArrivalDetails
		WHERE eadGodownId = @intGodownId
	AND eadItemId =  @intItemId
		AND eadCancel = 0
		AND eadExpiryDate = @dtExpiryDate
		GROUP BY eadExpiryDate, eadGodownId, eadItemId
	UNION ALL
		SELECT eidExpiryDate, eidGodownId, eidItemId, - SUM(eidItemQty)
	        FROM loiExpiryIssueDetails
	WHERE eidGodownId = @intGodownId
	        AND eidItemId = @intItemId
		AND eidCancel = 0
		AND eidExpiryDate = @dtExpiryDate
	        GROUP BY eidExpiryDate, eidGodownId, eidItemId) a
	        GROUP BY ExpiryDate, GodownId, ItemId
	        HAVING SUM(qty) <> 0 ) b
	WHERE b.ItemId = @intItemId  -- for extra safety
		
		-- if stock > 0, insert to issue details
		-- otherwise insert to arrival details
		-- to make the net stock zero
		If @numCurExpiryStock > 0
		Begin
			INSERT INTO loiExpiryIssueDetails
			(eidinterfaceid, eidgodownid, eidTransactionId, eiddetailId,
			eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
			eidpackingqty, eidcancel, eidadjustment)
			VALUES
			(8010, @intGodownId, @intSvdId, @intIssueDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numCurExpiryStock), 1, ABS(@numCurExpiryStock), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		Else
		Begin
			INSERT INTO loiExpiryArrivalDetails
			(eadinterfaceid, eadgodownid, eadtransactionid, eaddetailId,
			eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
			eadpackingqty, eadcancel, eadadjustment)
			VALUES
			(8010, @intGodownId, @intSvdId, @intArrivalDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numCurExpiryStock), 1, ABS(@numCurExpiryStock), 0, 1)
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		
		-- now insert to arrival/issue details
		If (@numVerifiedQty - @numSalesQty) > 0
		Begin
			INSERT INTO loiExpiryArrivalDetails
			(eadinterfaceid, eadgodownid, eadTransactionId, eaddetailId,
			eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
			eadpackingqty, eadcancel, eadadjustment)
			VALUES
			(8010, @intGodownId, @intSvdId, @intArrivalDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		Else
		Begin
			INSERT INTO loiExpiryIssueDetails
			(eidinterfaceid, eidgodownid, eidTransactionId, eiddetailId,
			eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
			eidpackingqty, eidcancel, eidadjustment)
			VALUES
			(8010, @intGodownId, @intSvdId, @intIssueDetailId,
			@dtExpiryDate, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		end
		Fetch Next From curExpiry Into @dtExpiryDate, @numVerifiedQty		
	End
	Close curExpiry
	Deallocate curExpiry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersDebitCredit]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersDebitCredit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified 	: 09/01/2003
-- modified by	: leo
-- Comments	: the concept of new exchange rate is included
---------------------------------------------------------------------------------------
-- Modified 	: 26/07/2003
-- modified by	: R Harikrishnan
-- Comments	: dcnFinancialid added in cursor to select
-- Modified 	: 26/08/2003, 25/01/2004
-- modified by	: Hariharan R, Hariharan R
-- Comments	: dcnFinancialid added in cursor to select
--		: debitacc1 and debitacc2 is posted with respect to the transaction.
--		: if transaction is debit these two opted as debit.
--		: if it is credit these two opted as Credit
---------------------------------------------------------------------------------------
CREATE proc [dbo].[spUpdateLedgersDebitCredit] @intCompanyid as int, @intdcnid as int as
begin	
	Declare @intAccountID as int
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dtdcnDate as datetime
	Declare @intCustomerID as int
	Declare @intVendorID as int
	Declare @strdcnNo as varchar(50)
	Declare @strdetails as varchar(1000)
	Declare @intDepartmentID as int
	Declare @bitDebit as bit
	Declare @numdcnAmount as numeric(18,2)
	Declare @numotherAmount as numeric(18,2)
	Declare @numdramt1 as numeric(18,2)
	Declare @numdramt2 as numeric(18,2)
	Declare @intdracc1 as int
	Declare @intdracc2 as int
	Declare @bitoppdebit as bit,
		@dtutime as datetime,
		@intcurrencyid as int,
		@numconsrate as numeric(18,9),
		@numdeprate as numeric(18,9),
		@strexrates as varchar(250),
		@numresamount as numeric(18,2)
	
	/* getting the maximum Journal ID FROM journal table */
	SELECT
		@intJournalID = isnull(max(JournalID),0)
	FROM
		moajournalheader
	WHERE 	
		CompanyID = @intCompanyID
	
	set @intJournalID = @intJournalID + 1
	SELECT
		@intdcniD = DCNID, @dtdcnDate = DCNDate , @intCustomerID = DCNCustomerId,
		@strdcnno = DCNNo, @strdetails = DCNDetails, @intAccountID = DCNotheraccid ,
		@intvendorid = DCNVendorId , @intDepartmentID = DCNDepartmentID,
		@bitdebit = DCNDebit, @numconsRate = DCNExchangerate, @numdcnamount = DCNAmount,
		@dtutime = updatetime, @numdeprate = dcndepexrate, @strexrates = dcnexchangerates,
		@intdracc1= debitaccount1, @intdracc2 = debitaccount2, @numdramt1 = debitamt1,
		@numdramt2 = debitamt2, @numotherAmount = otheraccamt, @intFinancialID = dcnFinancialid
	FROM
		debitcreditnote
	WHERE
		DCNCancelled =0 and DCNPosted =0 and DCNCompanyID = @intCompanyID
		and dcnid = @intdcnid
	-- customer
	if (@intcustomerid is not null)	
	begin		
		select
			@intcurrencyid = currencyid
		from
			acustomermaster
		where
			companyid = @intcompanyid and customerid = @intcustomerid
		insert into moajournalheader
			(JournalID, CompanyID, JournalDate, referenceno,
			remarks,financialID,Type, CurrencyID,chequedate,updatetime)
		values
			(@intJournalID, @intCompanyID, @dtdcnDate, @strdcnNo, @strdetails,
			@intFinancialID,''DCN'', @intcurrencyid, @dtdcndate, @dtutime)
		if (@bitdebit =0)
			set @bitoppdebit = 1
		else
			set @bitoppdebit = 0
		set @intJournalDetailID = 1
		if @numdcnamount >0
		Begin
			insert into moajournaldetails
			(JournalID, journaldetailID, CompanyID, JournalCrEDit, customerID,
			Amount, actualAmount,departmentID, depamount)
			values
			(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
			@intcustomerid, (@numdcnamount * @numconsRate), @numdcnamount,
			@intDepartmentID, @numdcnamount * @numdepRate)
			set @intJournalDetailID = @intJournalDetailID +1
		End			
		if (@intdracc1 is not null and @numdramt1 is not null)
		begin
			exec spConvertequiamount @intcustomerid, ''c'', @intdracc1,
			''a'', @strexrates, @numdramt1, @numresamount output
			
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
				Amount, actualAmount,departmentID, depamount)
			values
				(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
				@intdracc1, (@numdramt1 * @numconsRate), @numresamount,
				@intDepartmentID, @numdramt1 * @numdepRate)
			
			set @intJournalDetailID = @intJournalDetailID +1
		end
		if (@intdracc2 is not null and @numdramt2 is not null)
		begin
			exec spConvertequiamount @intcustomerid, ''c'', @intdracc2,
			''a'', @strexrates, @numdramt2, @numresamount output
			
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
				Amount, actualAmount,departmentID, depamount)
			values
				(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
				@intdracc2, (@numdramt2 * @numconsRate), @numresamount,
				@intDepartmentID, @numdramt2 * @numdepRate)
			
			set @intJournalDetailID = @intJournalDetailID +1
		end
		exec spConvertequiamount @intcustomerid, ''c'', @intaccountID,
		''a'', @strexrates, @numotherAmount, @numresamount output
		insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
				Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalID, @intjournalDetailID, @intCompanyID, @bitdebit,
			@intaccountid, (@numotherAmount * @numconsRate), @numresamount,
			@intDepartmentID, @numotherAmount * @numdepRate)
	end
	-- vendor
	if (@intvendorid is not null)
	begin
		select
			@intcurrencyid = currencyid
		from
			avendormaster
		where
			companyid = @intcompanyid and vendorid = @intvendorid
		insert into moajournalheader
			(JournalID, CompanyID, JournalDate, referenceno, remarks,financialID,
			Type, CurrencyID,chequedate, updatetime)
		values
			(@intJournalID, @intCompanyID, @dtdcnDate, @strdcnNo, @strdetails,
			@intFinancialID,''DCN'', @intcurrencyID,@dtdcndate, @dtutime)	
		set @intJournalDetailID = 1
		if (@bitdebit =0)
			set @bitoppdebit = 1
		else
			set @bitoppdebit = 0
		if @numdcnamount >0
		Begin
			insert into moajournaldetails
			(JournalID, journaldetailID, CompanyID, JournalCrEDit, vendorID, Amount,
			actualAmount,departmentID, depamount)
			values
			(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
			@intvendorid, (@numdcnamount * @numconsRate), @numdcnamount,
			@intDepartmentID, (@numdcnamount * @numdepRate))
			
			set @intJournalDetailID = @intJournalDetailID +1
		End
		if (@intdracc1 is not null and @numdramt1 is not null)
		begin
			exec spConvertequiamount @intvendorid, ''v'', @intdracc1,
			''a'', @strexrates, @numdramt1, @numresamount output
			
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
				Amount, actualAmount,departmentID, depamount)
			values
				(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
				@intdracc1, (@numdramt1 * @numconsRate), @numresamount,
				@intDepartmentID, @numdramt1 * @numdepRate)
			
			set @intJournalDetailID = @intJournalDetailID +1
		end
		if (@intdracc2 is not null and @numdramt2 is not null)
		begin
			exec spConvertequiamount @intvendorid, ''v'', @intdracc2,
			''a'', @strexrates, @numdramt2, @numresamount output
			
			insert into moajournaldetails
				(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
				 Amount, actualAmount,departmentID, depamount)
			values
				(@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
				@intdracc2, (@numdramt2 * @numconsRate), @numresamount,
				@intDepartmentID, @numdramt2 * @numdepRate)
			
			set @intJournalDetailID = @intJournalDetailID +1
		end
		exec spConvertequiamount @intvendorid, ''v'', @intaccountID,
		''a'', @strexrates, @numotherAmount, @numresamount output
		insert into moajournaldetails
			(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
			Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalID, @intjournalDetailID, @intCompanyID, @bitdebit,
			@intaccountid, 	(@numotherAmount * @numconsRate), @numresamount,
			@intDepartmentID, (@numotherAmount * @numdepRate) )
	end
	/* mark the record as postED */
	update debitcreditnote set
		dcnpostED = 1
	WHERE
		dcnCompanyID = @intCompanyID and dcnID = @intdcnID
end	-- end of procedure' 
END
GO
/****** Object:  View [dbo].[vwLcOutstandingPaid]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLcOutstandingPaid]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on		: 20/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAmount with pddAccountAmount
-------------------------------------------------------------------------------------------------
-- Modified on		: 25/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAccountAmount with pddAccountAmount - vendor exchange diff.
--		  	  This is an adjustment done for time being
-------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwLcOutstandingPaid] AS
select
	pohcompanyid,pohpoid,pohpono,pddpaymentid,phpaymentno,pddaccountid,accountdesc,
	pohlcamount as LCamount ,0 as LcMargin,
	pddAccountAmount - IsNull(pddVendorExchangeDifference, 0) as Outpaid,
	pddcustomeramount vendorpaideq, phlcpayment
from
	lopurchaseorderheader,ahqpaymentvoucherdebitdetails,
	ahqpaymentvoucherheader,aaccountmaster
where
	pohpoid = pddhqpoid
	and pohcompanyid = pddcompanyid
	and pddcompanyid = phcompanyid
	and pddpaymentid = phpaymentid
	and phlcpayment = ''LCO''
	and pohcancel = 0
	and phcancelled = 0
	and pddaccountid = accountid'
GO
/****** Object:  View [dbo].[vwLCOutstandingAge]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCOutstandingAge]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on		: 20/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAmount with pddAccountAmount
----------------------------------------------------------------------------
-- Modified on		: 25/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAccountAmount with pddAccountAmount - vendor exchange diff.
--			  This is an adjustment done for time being
----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwLCOutstandingAge] AS
select
	pohcompanyid, pohpoid, pohpono, pohpodate, max(phpaymentno) phpaymentno,
	max(b.accountdesc) lcaccountdesc, pohlcamount as amount,
	sum(pddAccountAmount) - IsNull(sum(pddVendorExchangeDifference), 0) as paid,
	sum(pddcustomeramount) vendorpaideq, '' 0 - 30'' due , lopurchaseorderheader.updatetime,
	v.vendorname, max(phpaymentdate) phpaymentdate, pohLCdueon, pohLCNumber, c.currencyname,
	c.symbol, pohlcaccountid, pohvendorid, c.currencyid, phdepartmentid, pohDueDate
from
	lopurchaseorderheader, ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader,
	aaccountmaster b, avendormaster v,acurrencymaster c
where
	pohpoid=pddhqpoid and pohcompanyid=pddcompanyid and pddcompanyid=phcompanyid and
	pddpaymentid=phpaymentid and (phlcpayment=''LCM'' OR phlcpayment=''LCO'') and
	pohcancel=0 and phcancelled=0 and c.companyid = b.companyid
	and b.currencyid = c.currencyid and pohlcaccountid= b.accountid and
	v.vendorid = pohvendorid and (datediff(dd,pohpodate,getdate())  between 0 and 30 )
group by
	pohcompanyid, pohpoid, pohpono, pohpodate, pohlcamount,
	lopurchaseorderheader.updatetime, v.vendorname, pohLCdueon,pohLCNumber,currencyname,
	c.symbol, pohlcaccountid, pohvendorid, c.currencyid, phdepartmentid, pohDueDate
union all
select
	pohcompanyid, pohpoid, pohpono, pohpodate, max(phpaymentno) phpaymentno,
	max(b.accountdesc) lcaccountdesc, pohlcamount as amount,
	sum(pddAccountAmount) - IsNull(sum(pddVendorExchangeDifference), 0) as paid,
	sum(pddcustomeramount) vendorpaideq, ''31 - 60'' due , lopurchaseorderheader.updatetime,
	v.vendorname, max(phpaymentdate) phpaymentdate, pohLCdueon,pohLCNumber,
	c.currencyname,c.symbol,pohlcaccountid, pohvendorid, c.currencyid, phdepartmentid, pohDueDate
from
	lopurchaseorderheader,ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader,
	aaccountmaster b, avendormaster v, acurrencymaster c
where
	pohpoid=pddhqpoid and pohcompanyid=pddcompanyid and pddcompanyid=phcompanyid and
	pddpaymentid=phpaymentid and (phlcpayment=''LCM'' OR phlcpayment=''LCO'') and
	pohcancel=0 and phcancelled=0 and c.companyid = b.companyid and
	b.currencyid = c.currencyid and pohlcaccountid= b.accountid and
	v.vendorid = pohvendorid and (datediff(dd,pohpodate,getdate())  between 31 and 60 )
group by
	pohcompanyid, pohpoid, pohpono, pohpodate, pohlcamount, lopurchaseorderheader.updatetime,
	v.vendorname, pohLCdueon,pohLCNumber,currencyname,c.symbol,pohlcaccountid, pohvendorid,
	c.currencyid, phdepartmentid, pohDueDate
union all
select
	pohcompanyid, pohpoid, pohpono, pohpodate, max(phpaymentno) phpaymentno,
	max(b.accountdesc) lcaccountdesc, pohlcamount as amount,
	sum(pddAccountAmount) - IsNull(sum(pddVendorExchangeDifference), 0) as paid,
	sum(pddcustomeramount) vendorpaideq, ''61 - 90'' due , lopurchaseorderheader.updatetime,
	v.vendorname, max(phpaymentdate) phpaymentdate, pohLCdueon,pohLCNumber,
	c.currencyname,c.symbol,pohlcaccountid, pohvendorid, c.currencyid, phdepartmentid ,
	pohDueDate
from
	lopurchaseorderheader,ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader,
	aaccountmaster b, avendormaster v,acurrencymaster c
where
	pohpoid=pddhqpoid and pohcompanyid=pddcompanyid and pddcompanyid=phcompanyid and
	pddpaymentid=phpaymentid and (phlcpayment=''LCM'' OR phlcpayment=''LCO'') and
	pohcancel=0 and phcancelled=0 and c.companyid = b.companyid and b.currencyid = c.currencyid and
	pohlcaccountid= b.accountid and v.vendorid = pohvendorid and
	(datediff(dd,pohpodate,getdate())  between 61 and 90 )
group by
	pohcompanyid, pohpoid, pohpono, pohpodate, pohlcamount, lopurchaseorderheader.updatetime,
	v.vendorname, pohLCdueon,pohLCNumber,currencyname,c.symbol,pohlcaccountid, pohvendorid,
	c.currencyid, phdepartmentid, pohDueDate
union all
select
	pohcompanyid, pohpoid, pohpono, pohpodate, max(phpaymentno) phpaymentno,
	max(b.accountdesc) lcaccountdesc, pohlcamount as amount,
	Sum(pddAccountAmount)  - IsNull(Sum(pddVendorExchangeDifference), 0) as paid,
	Sum(pddcustomeramount) vendorpaideq,'' > 90'' due , lopurchaseorderheader.updatetime,
	v.vendorname, max(phpaymentdate) phpaymentdate, pohLCdueon,pohLCNumber, c.currencyname,
	c.symbol,pohlcaccountid, pohvendorid, c.currencyid, phdepartmentid, pohDueDate
from
	lopurchaseorderheader,ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader,
	aaccountmaster b, avendormaster v, acurrencymaster c
where
	pohpoid=pddhqpoid and pohcompanyid=pddcompanyid and pddcompanyid=phcompanyid and
	pddpaymentid=phpaymentid and (phlcpayment=''LCM'' OR phlcpayment=''LCO'') and
	pohcancel=0 and phcancelled=0 and c.companyid = b.companyid and
	b.currencyid = c.currencyid and pohlcaccountid= b.accountid and
	v.vendorid = pohvendorid and (datediff(dd,pohpodate,getdate())  > 90 )
group by
	pohcompanyid, pohpoid, pohpono, pohpodate, pohlcamount,
	lopurchaseorderheader.updatetime,
	v.vendorname, pohLCdueon, pohLCNumber, currencyname, c.symbol, pohlcaccountid,
	pohvendorid, c.currencyid, phdepartmentid, pohDueDate'
GO
/****** Object:  View [dbo].[vwLCMarginPaid]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCMarginPaid]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on	: 20/09/2003
-- Modified by	: Kishore
-- Comments	: Replaced pddAmount with pddAccountAmount
-----------------------------------------------------------------------------------------------
-- Modified on	: 25/09/2003
-- Modified by	: Kishore
-- Comments	: Replaced pddAccountAmount with pddAccountAmount - vendor exchange diff.
--		  This is an adjustment done for time being
-----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwLCMarginPaid] AS
SELECT pohcompanyid, pohpoid, pohpono, pddpaymentid,
phpaymentno, pddaccountid, accountdesc,
pohlcamount as LCamount, 0 as LcMargin,
pddAccountAmount -  - IsNull(pddVendorExchangeDifference, 0)  as Outpaid,
phlcpayment, pddcustomeramount PaidVendorEq
FROM lopurchaseorderheader,
ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader,aaccountmaster
WHERE pohpoid = pddhqpoid
AND pohcompanyid = pddcompanyid
AND pddcompanyid = phcompanyid
AND pddpaymentid = phpaymentid
AND phlcpayment = ''LCM''
AND pohcancel = 0
AND phcancelled = 0
AND pddaccountid = accountid'
GO
/****** Object:  View [dbo].[vwLCMarginOutstanding]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLCMarginOutstanding]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on  : 06/09/2003
-- Modified by : Kishore
-- Comments : Added BillId column. For this linked with lospPurchaseBillHeader
-------------------------------------------------------------------------------------------
-- Modified on : 20/09/2003
-- Modified by : Kishore
-- Comments : Replaced pddAmount with pddAccountAmount
-------------------------------------------------------------------------------------------
-- Modified on : 25/09/2003
-- Modified by : Kishore
-- Comments : Replaced pddAccountAmount with pddAccountAmount - vendor exchange diff.
--    This is an adjustment done for time being
--------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwLCMarginOutstanding] AS
select pohcompanyid,pohpoid,pohpono,pddpaymentid,phpaymentno,pddaccountid,
pohlcaccountid, a.accountdesc, b.accountdesc lcaccountdesc, pohvendorid,
pohlcamount as amount,
pddAccountAmount - IsNull(pddVendorExchangeDifference, 0) as paid,
phlcpayment,pddcustomeramount PaidVendorEq,
bill.pbhBillId BillId
from lopurchaseorderheader h Left Outer Join lospPurchaseBillHeader bill
on h.pohPoId = bill.pbhPoId
and h.pohCompanyId = bill.pbhCompanyID and pbhCancelled=0 ,
ahqpaymentvoucherdebitdetails,
ahqpaymentvoucherheader, aaccountmaster a, aaccountmaster b
where pohpoid = pddhqpoid
and pohcompanyid = pddcompanyid
and pddcompanyid = phcompanyid
and pddpaymentid = phpaymentid
and (phlcpayment = ''LCM'' OR phlcpayment = ''LCO'')
and pohcancel = 0
and phcancelled = 0
and pddaccountid = a.accountid
and pohlcaccountid = b.accountid'
GO
/****** Object:  View [dbo].[vwKegItemsHistory]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwKegItemsHistory]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--MODIFIED  BY 	: - Santhosh M
--Modified Date : 23/08/2003
--MODIFIED  BY 	: venki , Hariharan R
--Modified Date : 25/09/2003, 30/09/2003
--given left outer joins
--Removed losKegReturnHeader and losKegReturnDetail from the equi join conditions
CREATE view [dbo].[vwKegItemsHistory] as
	select
		 ihinvoiceid,ihinvoiceno,ihinvoicedate,ihreferenceno,ihremarks,shopname,
		 customername,idquantity, a.krditemid,isnull(a.krdquantity,0)krdquantity,
		 ihcustomerid, idinvoiceid, idshopid, ItemDescription,iditemid,
		idPackingtypeid, idunitprice, idcostprice, idpQuantity
	from
	losinvoiceheader inh, acustomermaster acm,ashops ash, vwItemDescription vw,
	losinvoicedetail Ind
	LEFT OUTER JOIN
		(select krd.krdinvoiceid,krhshopid,krditemid,sum(krdquantity)krdquantity from
	 loskegreturnheader krh,loskegreturndetail krd where
	 krh.krhkegreturnid=krd.krdreturnnoteid and
	krh.krhshopid=krd.krdshopid and krh.krhCancel=0
	group by krd.krditemid,krd.krdinvoiceid,krhshopid) a on
	ind.idinvoiceid = a.krdinvoiceid and ind.idshopid = a.krhshopid  and
	ind.iditemid = a.krditemid
	where
	inh.ihinvoiceid=ind.idinvoiceid and inh.ihshopid=ind.idshopid
	 and inh.ihcustomerid=acm.customerid and inh.ihshopid=ash.shopid
	 and idtype = ''r'' and vw.itemid = iditemid and ihtype=''i'' and ihcancelled=0 	
	group by ihinvoiceno,ihinvoicedate,ihreferenceno,ihremarks,shopname,
	customername,idquantity, ihcustomerid, iditemid ,ihinvoiceid,
	idinvoiceid, idshopid, ItemDescription,a.krditemid, idPackingtypeid,
	a.krdquantity, idunitprice, idcostprice, idpQuantity'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockKegReturn]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockKegReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by   : santhosh
-- Created Date : 21/08/2003
-- Comments	: V3
-- TO update stock table when transaction is saved in kegreturn transaction
CREATE proc [dbo].[spUpdateShopStockKegReturn]  (@intReturnId int,
			@intShopId int, @process char(1)) as
begin
	declare
		@cur_ReturnId int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@intCount int,
		@cur_Damaged bit
	set nocount on
	declare cursor_Detail  cursor for
		select krdReturnNoteId, krdItemId, krdShopId, krdQuantity,
		krdDamaged
		from loskegReturnDetail
		where krdReturnNoteId = @intReturnId and krdShopId = @intShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_ReturnId, @cur_ItemId, @cur_ShopId,
		@cur_itemQty, @cur_damaged
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			-- if damaged, then update bad stock
			-- else update stock			
			if @cur_damaged = 1
			begin
				update mosShopStock set BadStock = BadStock - @cur_ItemQty
					where ItemId = @cur_ItemId and ShopId = @cur_ShopId				
			end
			else
			begin
				update mosShopStock set stock = stock - @cur_ItemQty
					where ItemId = @cur_ItemId and ShopId = @cur_ShopId
			end
		end
		if @process = ''F''
		begin
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock (ShopId, StockDate, ShipmentId, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			
			-- if damaged, then update bad stock
			-- else update stock			
			if @cur_damaged = 1
			begin
				update mosShopStock set BadStock = BadStock + @cur_ItemQty
					where ItemId = @cur_ItemId and ShopId = @cur_ShopId				
			end
			else
			begin
				update mosShopStock set stock = stock + @cur_ItemQty
					where ItemId = @cur_ItemId and ShopId = @cur_ShopId
			end
		end
		fetch next from cursor_Detail into
		@cur_ReturnId, @cur_ItemId, @cur_ShopId,
		@cur_itemQty, @cur_damaged
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockInv]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created  by   	: Kishore
-- Created  Date 	: 30/12/2002
-- Comments		: V3
-- TO update stock table when transaction is saved in invoice
-- sales transaction
-- Verified by 		:	Hariharan
---------------------------------------------------------------------
-- Modified on 		: 07/08/2003
-- Modified by		: R Harikrishnan
-- Comments		: Other charges changes
---------------------------------------------------------------------
-- Modified on          : 07/08/2003
-- Modified by          : Comments
-- Comments             : Added the free items concept
----------------------------------------------------------------------
-- Modified on          : 16/09/2003 venki ''
-- Modified by          : Comments
-- Comments             : replaced idpquantity to idquantiy
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
---------------------------------------------------------------------
CREATE PROC [dbo].[SpUpdateShopStockInv]
(
	@intInvoiceId 	int,
	@intShopId 	int,
	@process 	char(1)
)
as
begin
	declare
		@cur_InvoiceId int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@cur_FreeQty numeric(18, 3),
		@intCount int
		
	set nocount on
	declare cursor_Detail  cursor for
		select
			idInvoiceId, idShopId, idItemId, idQuantity, ISNULL(idFreeQuantity,0) idFreeQuantity
		from 	
			losInvoiceDetail
		where
			idInvoiceId = @intInvoiceId and idShopId = @intShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_InvoiceId, @cur_ShopId, @cur_ItemId, @cur_itemQty, @cur_FreeQty
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			update mosShopStock set
				stock = stock + @cur_itemQty + @cur_FreeQty
			where
				ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		if @process = ''F''
		begin
			select
				@intCount = count(*)
			from
				mosShopStock
			where
				ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock
					(ShopId, StockDate, ShipmentID, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
				Select
					@intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update mosShopStock set
				stock = stock - (@cur_itemQty + @cur_FreeQty)
			where
				ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		fetch next from cursor_Detail into
			@cur_InvoiceId, @cur_ShopId, @cur_ItemId,@cur_itemQty, @cur_FreeQty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateshopDamageClearing]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateshopDamageClearing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  By 	: Lawrence.J
--Created  Date  : 27-Dec-02
--Verified By 	: Hariharan on 03/01/2003
--Comments	: (V3)
--Created  By 	: venki
--Created  Date  : 17-09-03
--Comments	: insertion to mosshopstock done if found no entry for item
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE  proc [dbo].[spUpdateshopDamageClearing] @ClearID int,
@shopid int, @Type char(1)  as
declare
@cur_ClearID int,
@cur_shopid int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_ShipmentID int,
@intcount int
set @intcount=0
set nocount on
	declare cursor_Detail  cursor for
	select dcdClearingID, dcdShopid, dcdItemID, dcdWriteOffQty, dcdShipmentID
	from LOsShopDamageClearingDetails where dcdClearingID = @ClearID and dcdShopid = @shopid
open cursor_Detail
fetch next from cursor_Detail into
@cur_ClearID, @cur_shopid, @cur_itemid,
@cur_itemgoodqty, @cur_ShipmentID
while @@fetch_status = 0
begin
		
		if @TYpe=''f''
		Begin
			select
				@intCount = count(*)
			from
				mosShopStock
			where
				ItemId = @cur_ItemId and ShopId = @ShopId
			if @intCount = 0
			begin
				insert mosShopStock
					(ShopId, StockDate, ShipmentID, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
				Select
					@ShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update MOsShopStock set BadStock = BadStock - @cur_itemgoodqty
			where ItemID = @cur_itemid and ShopID = @cur_shopid  and
			ShipmentID = @cur_ShipmentID
		End
		Else	--@type=''r''
		Begin
			update MOsShopStock set BadStock = BadStock + @cur_itemgoodqty
			where ItemID = @cur_itemid and ShopID = @cur_shopid  and
			ShipmentID = @cur_ShipmentID
		End
	fetch next from cursor_Detail into
	@cur_ClearID, @cur_shopid, @cur_itemid,
	@cur_itemgoodqty, @cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockExport]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateStockExport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateStockExport    Script Date: 18/01/2003 9:45:46 PM ******/
-- Created by   : Kishore
-- Created Date : 31/12/2002
-- Comments	: V3
-- TO update stock table when transaction is done in reexport
-- sales transaction
--Verified By	: Hariharan R  on 04/01/2003
CREATE proc [dbo].[spUpdateStockExport] (@intExportId int,
			@intShopId int, @process char(1)) as
begin
	declare
		@cur_ExportId int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@intCount int
	set nocount on
	declare cursor_Detail  cursor for
		select redExportId, redShopId, redItemId, redQuantity
		from losExportDetail
		where redExportId = @intExportId and redShopId = @intShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_ExportId, @cur_ShopId, @cur_ItemId,
		@cur_itemQty
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			update mosShopStock set Stock = Stock + @cur_ItemQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId				
		end
		if @process = ''F''
		begin
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock (ShopId, StockDate, ShipmentId, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update mosShopStock set stock = stock - @cur_ItemQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		fetch next from cursor_Detail into
			@cur_ExportId, @cur_ShopId, @cur_ItemId,
			@cur_itemQty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopWriteOff]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopWriteOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on   : 04-Jun-2003
-- Modified by   : Kishore
-- Comments      : ALTERd on 27-Dec-2002 by Lawrence.
--                 Added the isNull condition while updation of
--                 			stock and bad stock (16-Jan-2003).
--                 The bad stock updation changed in case of in-house consumption (04-Jun-2003)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE PROCEDURE [dbo].[spUpdateShopWriteOff] (@WriteoffId int,
		@ShopId int, @Type char(1), @strTransType Char(1)) AS
Begin
	declare
	@cur_woffid int,
	@cur_shopid int,
	@cur_itemid int,
	@cur_ItemGoodQty numeric(18,3),
	@cur_cost numeric(18,2),
	@cur_ShipmentID int,
	@recCount as int,
	@numBadQty as Numeric(18, 3),
	@intcount int
	
	set nocount on
	set @intcount=0	
	declare cursor_Detail  cursor for
	select WdID,wdShopID,WdItemID,WdWriteoffQty,wdcostprice,WdShipmentID
	from LOswriteoffDetail where WdID= @WriteoffID and wdShopID = @shopid
	open cursor_Detail
	fetch next from cursor_Detail into
	@cur_woffid, @cur_shopid, @cur_itemid,
	@cur_ItemGoodQty, @cur_cost,  @cur_ShipmentID
	while @@fetch_status = 0
	begin
		-- is transaction is in-house consumption
		If @strTransType = ''I''
			Set @numBadQty = 0
		Else	-- if transaction is write-off
			Set @numBadQty = @cur_ItemGoodQty
		if @TYpe=''f''
		Begin
			select
				@intCount = count(*)
			from
				mosShopStock
			where
				ItemId = @cur_ItemId and ShopId = @ShopId
			if @intCount = 0
			begin
				insert mosShopStock
					(ShopId, StockDate, ShipmentID, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
				Select
					@ShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update MOsShopstock set Stock =  isNull(Stock, 0) - @cur_ItemGoodQty,
			BadStock = isNull(BadStock, 0) + @numBadQty
			where ItemID = @cur_itemid
			and ShopID = @cur_shopid  and ShipmentID = @cur_ShipmentID
		End
		Else	--@type=''r''
		Begin
			update MOsShopstock set Stock =  isNull(Stock, 0) + @cur_ItemGoodQty,
			BadStock = isNull(BadStock, 0) - @numBadQty
			where ItemID = @cur_itemid
			and ShopID = @cur_shopid  and ShipmentID = @cur_ShipmentID
		End
		
		fetch next from cursor_Detail into
		@cur_woffid, @cur_shopid, @cur_itemid,
		@cur_ItemGoodQty, @cur_cost, @cur_ShipmentID
	end
	
	close cursor_Detail
	
	deallocate cursor_Detail
	
	return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopVerification]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By 	    : Lawrence.J
-- Created Date     : 27-Dec-2002
-- Last Modified on : 06/06/2003
-- Modified by      : Kishore
-- Comments         : Changed the differences found on comparison with v2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateShopVerification] @VerificationID int,
@shopid int, @Type char(1)  as
declare
@cur_verid int,
@cur_shopid int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_itemBadQty numeric(18,3),
@cur_availgoodqty numeric(18,3),
@cur_availBadQty numeric(18,3),
@cur_packingtypeid int,
@cur_cost numeric(18,2),
@cur_ShipmentID int,
@recCount as int
set nocount on
	declare cursor_Detail  cursor for
select svdid,svdShopid,svditemid,svdVerifiedStock,svdVerifiedBadStock,
	svdcostprice,svdShipmentID,svdAvailStock,svdAvailBadStock from
	losStockVerificationDetail where svdid=@VerificationID and svdShopid=@shopid
open cursor_Detail
fetch next from cursor_Detail into
@cur_verid,@cur_shopid, @cur_itemid,
@cur_itemgoodqty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
@cur_availgoodqty, @cur_availBadqty
while @@fetch_status = 0
begin
		if @TYpe=''f''
		Begin
			select @recCount = count(*) from mosShopstock where
			ItemID=@cur_itemid
			and ShopID= @cur_shopid
			if @recCount =0
				insert mosShopstock(ShopID,ShipmentID,ItemID,
				Stock,BadStock,ItemCostPrice,StockDate)
				select @cur_shopid,@cur_Shipmentid, @cur_ItemID,
				@cur_itemgoodqty, @cur_itemBadQty, @cur_Cost, getdate()
			else
				update mosShopstock set Stock = @cur_itemgoodqty,
				BadStock = @cur_itemBadQty where ItemID = @cur_itemid and
				ShopID= @cur_shopid
		End
		Else	--@type=''r''
		Begin
			update mosShopstock
			set Stock = Stock + @cur_availgoodqty - @cur_itemgoodqty,
			BadStock = BadStock + @cur_availBadQty - @cur_itemBadQty
			where ItemID = @cur_itemid
			and ShopID = @cur_shopid
		End
	fetch next from cursor_Detail into
	@cur_verid,@cur_shopid, @cur_itemid,
	@cur_itemgoodqty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
	@cur_availgoodqty, @cur_availBadqty
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockStg]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockStg]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  By		:Lawrence.J
--Created  On		:30-Dec-2002
--Purpose		:(V3) Updating Stock from Shop to Godown
--verified by hariharan on	: 03/01/2003
--ALTERd By		:venki 170903
--modi On		:17-09-2003
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE proc [dbo].[spUpdateShopStockStg](@despatchid int,@Shopid int,@process char(1)) as
declare
@cur_despatchid int,
@cur_shopid int,
@cur_itemid int,
@cur_shipmentid int,
@cur_itembadqty numeric(18,3),
@cur_itemgoodqty numeric(18,3),
@intcount int
set @intcount=0
set nocount on
declare cursor_Detail  cursor for
	select dgdID,dgdShopID,dgdItemID,dgdDespatchedBadQty,
	dgdDespatchedGoodQty,dgdShipmentID from MEsDespatchtoGodownDetail
	where dgdID=@despatchid and dgdShopID= @shopid
open cursor_Detail
fetch next from cursor_Detail into
@cur_despatchid, @cur_shopid, @cur_itemid,
@cur_itembadqty, @cur_itemgoodqty,@cur_shipmentid
while @@fetch_status = 0
begin
	if @process = ''R''
		update mosshopstock set Stock = Stock + @cur_itemgoodqty
		where ItemID = @cur_itemid and ShopID = @cur_shopid
		and ShipmentID=@cur_shipmentid
	if @process = ''F''
	begin
		select
				@intCount = count(*)
			from
				mosShopStock
			where
				ItemId = @cur_ItemId and ShopId = @ShopId
			if @intCount = 0
			begin
				insert mosShopStock
					(ShopId, StockDate, ShipmentID, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
				Select
					@ShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
		update mosshopstock set Stock = Stock - @cur_itemgoodqty
		where ItemID = @cur_itemid and ShopID = @cur_shopid
		and ShipmentID=@cur_shipmentid
	end
	fetch next from cursor_Detail into
	@cur_despatchid, @cur_shopid, @cur_itemid,
	@cur_itembadqty, @cur_itemgoodqty,@cur_shipmentid
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInventoryAgeAnalysis]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryAgeAnalysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spInventoryAgeAnalysis 1,47
--CREATED BY : SREEJITH G A
--CREATED ON : 20101005
--PURPOSE	 : SHOWS CURRENT STOCK OF THE ITEM AND ALSO THE
--			   PURCHASE QTY DISTRIBUTION ON AGE WISE.
CREATE PROC [dbo].[spInventoryAgeAnalysis] (@intCompanyId as int,@intdepId as int) as
begin
if @intdepId<>0
	begin
		select BILLDETAILS.pbhCompanyID,pbdBillID,pbhBillNo,
		BILLDETAILS.pbhDepartmentID,case when pbhBillDate is null then StockDate else pbhBillDate end pbhBillDate,
		BILLDETAILS.Due,pbhVendorID,ai.ItemID[pbdItemID],ItemCode,
		ItemDescription,UnitsID,Brand,modelno,isnull(part_code,'''')part_code,
		ItemCategoryID,PackingTypeID[pbdPackingtypeID],isnull(pbdItemQuantity,0)pbdItemQuantity,pbdItemUnitPrice ,isnull(Stock,0 ) Stock,OpeningStock OpeningStock FROM
		   ((
		 select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,pbhVendorID,pbdItemID,pbdPackingtypeID,
		 pbdItemQuantity,pbdItemUnitPrice,
		 case when getdate() -pbhBillDate between 0 and 30 then ''0 - 30''
		 when getdate() -pbhBillDate between 30 and 180 then ''30 - 180''
		 when getdate() -pbhBillDate between 180 and 365 then ''180 - 365''
		 when getdate() -pbhBillDate between 365 and 700 then ''365 - 700''
		 when getdate() -pbhBillDate >700 then ''>700'' end Due
		 from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
		 pbhCancelled=0 AND pbhDespatched=1
		 UNION ALL
		--Local purchase
		 select lphCompanyID,lphBillID,lphBillNo,lphDepartmentID,lphBillDate,lphVendorID,lpdItemID,null,
		 lpdItemQuantity,lpdPOUnitPrice,
		 case when getdate() -lphBillDate between 0 and 30 then ''0 - 30''
		 when getdate() -lphBillDate between 30 and 180 then ''30 - 180''
		 when getdate() -lphBillDate between 180 and 365 then ''180 - 365''
		 when getdate() -lphBillDate between 365 and 700 then ''365 - 700''
		 when getdate() -lphBillDate >700 then ''>700'' end Due
		 from losLocalPurchaseDetail inner join LosLocalPurchaseHeader
		 on lpdBillID=lphBillID and lphCancelled=0
		) BILLDETAILS
		left outer join
		(
		select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,DepartmentID[pbhDepartmentID],sum(v.Stock)Stock,sum(v.OpeningStock)OpeningStock,op.StockDate[StockDate],
		case when getdate() -op.StockDate between 0 and 30 then ''0 - 30''
		when getdate() -op.StockDate between 30 and 180 then ''30 - 180''
		when getdate() -op.StockDate between 180 and 365 then ''180 - 365''
		when getdate() -op.StockDate between 365 and 700 then ''365 - 700''
		when getdate() -op.StockDate >700 then ''>700'' end Due
		from vwCompanyTotalStock v
		inner join ashops on shopid=LocationID INNER JOIN mosshopstock op on LocationID=op.shopid and v.ItemID=op.ItemID
		inner join aitempackingdetail p on p.itemid=v.ItemID
		group by v.ItemID,v.companyId,LocationID,DepartmentID,StockDate,PackingTypeID
		UNION ALL
		select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,DepartmentId[pbhDepartmentID],sum(Stock)Stock,sum(OpeningStock)OpeningStock,gsStockDate[StockDate],
		case when getdate() -gsStockDate between 0 and 30 then ''0 - 30''
		when getdate() -gsStockDate between 30 and 180 then ''30 - 180''
		when getdate() -gsStockDate between 180 and 365 then ''180 - 365''
		when getdate() -gsStockDate between 365 and 700 then ''365 - 700''
		when getdate() -gsStockDate >700 then ''>700'' end Due
		from vwCompanyTotalStock v
		inner join agodown on GodownID=LocationID inner join moigodownstock op on LocationID=op.gsGodownID and v.ItemID=op.gsItemID
		inner join aitempackingdetail p on p.itemid=v.ItemID
		group by v.ItemID,v.companyId,LocationID,DepartmentId,gsStockDate,PackingTypeID
		)CompanyTotalStock
		ON BILLDETAILS.pbdItemID=CompanyTotalStock.ItemID and CompanyTotalStock.pbhDepartmentID=BILLDETAILS.pbhDepartmentID
		)
		left outer JOIN aItem ai ON ai.ItemID=pbdItemID
		where BILLDETAILS.pbhDepartmentID=@intDepId and BILLDETAILS.pbhCompanyID=@intCompanyId --and  BILLDETAILS.[pbdItemID]=6443
	end
	
else
	begin
		select BILLDETAILS.pbhCompanyID,pbdBillID,pbhBillNo,
		BILLDETAILS.pbhDepartmentID,pbhBillDate,
		BILLDETAILS.Due,pbhVendorID,ai.ItemID[pbdItemID],ItemCode,
		ItemDescription,UnitsID,Brand,modelno,isnull(part_code,'''')part_code,
		ItemCategoryID,PackingTypeID[pbdPackingtypeID],isnull(pbdItemQuantity,0)pbdItemQuantity,pbdItemUnitPrice ,SUM(Stock ) Stock,SUM(OpeningStock ) OpeningStock FROM
		   (
		 select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,pbhVendorID,pbdItemID,pbdPackingtypeID,
		 pbdItemQuantity,pbdItemUnitPrice,
		 case when getdate() -pbhBillDate between 0 and 30 then ''0 - 30''
		 when getdate() -pbhBillDate between 30 and 180 then ''30 - 180''
		 when getdate() -pbhBillDate between 180 and 365 then ''180 - 365''
		 when getdate() -pbhBillDate between 365 and 700 then ''365 - 700''
		 when getdate() -pbhBillDate >700 then ''>700'' end Due
		 from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
		 pbhCancelled=0 AND pbhDespatched=1
		 UNION ALL
		--Local purchase
		 select lphCompanyID,lphBillID,lphBillNo,lphDepartmentID,lphBillDate,lphVendorID,lpdItemID,null,
		 lpdItemQuantity,lpdPOUnitPrice,
		 case when getdate() -lphBillDate between 0 and 30 then ''0 - 30''
		 when getdate() -lphBillDate between 30 and 180 then ''30 - 180''
		 when getdate() -lphBillDate between 180 and 365 then ''180 - 365''
		 when getdate() -lphBillDate between 365 and 700 then ''365 - 700''
		 when getdate() -lphBillDate >700 then ''>700'' end Due
		 from losLocalPurchaseDetail inner join LosLocalPurchaseHeader
		 on lpdBillID=lphBillID and lphCancelled=0
		) BILLDETAILS
		left outer join
		(
		select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,sum(v.Stock)Stock,sum(v.OpeningStock)OpeningStock,op.StockDate[StockDate],
		case when getdate() -op.StockDate between 0 and 30 then ''0 - 30''
		when getdate() -op.StockDate between 30 and 180 then ''30 - 180''
		when getdate() -op.StockDate between 180 and 365 then ''180 - 365''
		when getdate() -op.StockDate between 365 and 700 then ''365 - 700''
		when getdate() -op.StockDate >700 then ''>700'' end Due
		from vwCompanyTotalStock v
		inner join ashops on shopid=LocationID INNER JOIN mosshopstock op on LocationID=op.shopid and v.ItemID=op.ItemID
		inner join aitempackingdetail p on p.itemid=v.ItemID
		group by v.ItemID,v.companyId,LocationID,StockDate,PackingTypeID
		UNION ALL
		select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,sum(Stock)Stock,sum(OpeningStock)OpeningStock,gsStockDate[StockDate],
		case when getdate() -gsStockDate between 0 and 30 then ''0 - 30''
		when getdate() -gsStockDate between 30 and 180 then ''30 - 180''
		when getdate() -gsStockDate between 180 and 365 then ''180 - 365''
		when getdate() -gsStockDate between 365 and 700 then ''365 - 700''
		when getdate() -gsStockDate >700 then ''>700'' end Due
		from vwCompanyTotalStock v
		inner join agodown on GodownID=LocationID inner join moigodownstock op on LocationID=op.gsGodownID and v.ItemID=op.gsItemID
		inner join aitempackingdetail p on p.itemid=v.ItemID
		group by v.ItemID,v.companyId,LocationID,gsStockDate,PackingTypeID
		)CompanyTotalStock
		ON BILLDETAILS.pbdItemID=CompanyTotalStock.ItemID--- and CompanyTotalStock.pbhDepartmentID=BILLDETAILS.pbhDepartmentID
		left outer JOIN aItem ai ON ai.ItemID=pbdItemID
		where BILLDETAILS.pbhCompanyID=@intCompanyId
		GROUP BY BILLDETAILS.pbhCompanyID,pbdBillID,pbhBillNo,
		BILLDETAILS.pbhDepartmentID,pbhBillDate,--StockDate ,
		BILLDETAILS.Due,pbhVendorID,ai.ItemID,ItemCode,
		ItemDescription,UnitsID,Brand,modelno,part_code,
		ItemCategoryID,PackingTypeID,pbdItemQuantity,pbdItemUnitPrice
	end
end' 
END
GO
/****** Object:  View [dbo].[vwInquiryShopStockDirect]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockDirect]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Regin T.
-- Create date: 23-07-2010
--    The name of the view is changed from vwInquiryShopStock
--    to vwInquiryShopStockDirect.
-- Description:	
--    To compute the shop stock in direct method.
--	  Shop transactions summary is not used here.
--    This view can be used to verify if the stock computed
--    using stock summary is correct.
-- =============================================
CREATE VIEW [dbo].[vwInquiryShopStockDirect] AS
SELECT
	shopid, itemid, convert(numeric(18,3), sum(stock)) stock
	, sum(badstock) badstock, sum(openingstock) openingstock
	, sum(openingbadstock) openingbadstock
	, 1 shipmentid, max(itemcostprice) itemcostprice
FROM (
	-- 1. Opening Stock
	SELECT
		shopid, itemid, openingstock stock, isnull(openingbadstock,0) badstock
		, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
		, itemcostprice
	FROM mosshopstock
	
	UNION ALL
	-- 2. Shop Bin Card For Good Stock
	SELECT
		shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock
		, 0, 0, 0, 0
	FROM vwshopbincardaudit
	GROUP BY shopid,itemid
	UNION ALL
	-- 3. Shop Bin Card For Bad Stock
	SELECT shopid,itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) stock
	, 0, 0, 0
	FROM vwshopbincardbadqty
	GROUP BY shopid,itemid
) inqstock
GROUP BY shopid, itemid'
GO
/****** Object:  View [dbo].[vwInquiryShopStockDatewise]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStockDatewise]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwInquiryShopStockDatewise] AS
SELECT
ShopId, ItemId, convert(numeric(18,3), sum(stock)) Stock
, sum(badstock) BadStock, sum(openingstock) OpeningStock
, sum(openingbadstock) OpeningBadStock
, 1 ShipmentId, max(itemcostprice) ItemCostPrice, StockDate,type
FROM (
-- 1. Opening Stock
SELECT
shopid, itemid, openingstock stock, isnull(openingbadstock,0) badstock
, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
, itemcostprice,StockDate,'''' type
FROM mosshopstock
UNION ALL
-- 2. Shop Bin Card For Good Stock
SELECT
shopid,itemid, transqty * mode stock
, 0, 0, 0, 0, sDate,type
FROM vwshopbincardaudit
UNION ALL
-- 3. Shop Bin Card For Bad Stock
SELECT shopid,itemid,  0,  badtransqty * mode stock
, 0, 0, 0, sdate,''''
FROM vwshopbincardbadqty
) inqstock
GROUP BY shopid, itemid, StockDate,type
----------------------------------------------------'
GO
/****** Object:  View [dbo].[vwShopBinCardAudit_Pos]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAudit_Pos]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Benzigar S D
--Created On : 20/01/2009
--Comment    : To Speed up POS
-----------------------------------------
--MODIFIED BY : NIDHEESH PV
--MODIFIED ON :09/02/2011
--cOMMENTS : ADDED INHOUSE RETURN
--------------------------------------------------------------------------------
--Modified by          : Nidheesh P V
--Modified on          : 6/07/2011
--Comments             : Added In-House Consumption part seperately.
--Modified Area        : All Interfaces where stock effects
--Referenc No          : Ref-No1
--------------------------------------------------------------------------------
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U
-- Modified on	: 26/03/2012
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
--------------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwShopBinCardAudit_Pos] AS
select shopid, itemid
from
--arrival from godown
(select h.gahshopid shopid, d.gaditemid itemid from
losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d where
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1 group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,
gaharrivalno, d.gaditemid,updatetime, gadCostprice, gahdepexrate, gahconexrate
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select grn.grnhShopid, grd.GRNDItemID from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0
union all
--transfer in
select h.tihshopid shopid,  d.tiditemid itemid
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,
tihdepexrate, tihconexrate
union all
--recovery add
select sr.srshopid, sr.sritemid from
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 group by   svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate, svhconexrate
union all
--exchange in
select sehShopID, seditemid from
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPrice, sehDepExrate, sehExchangerate
union all
--local purchase
select lphShopid, lpditemid
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1--<<Ref-No2>>
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,
	lphdepexrate,lphExchangerate
union all
--write off
select wh.whshopid, wd.wditemid
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype<>''I'' --Ref-No1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--InHouse Consumption   --Ref-No1
select wh.whshopid, wd.wditemid
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype=''I'' and whVerified=1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Deapatch
select dd.dgdshopid, dd.dgditemid
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,
dgdCostPrice, dghdepexrate, dghconexrate
union all
--Transferout
select todshopid, toditemid
from mestransferoutheader , mestransferoutdetail  where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,
tohdepexrate, tohConExrate
union all
--recovery minus
select sr.srshopid, sr.sritemid from
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--pos sales
select poshShopID, posditemid from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0 group by
poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate
union all
--credit invoice
select IhShopid, iditemid  from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''I'' group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,
updatetime, idCostPrice, ihdepexrate, ihExchangeRate
union all
--exchange out
select sehShopID, seditemid
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPRice, sehdepexrate, sehExchangerate
union all
--special invoice return to shop
select IhShopid, iditemid
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1 group by ihshopid, ihinvoicedate, ihInvoiceid,
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate
-- transfinished added as stock is updated only after confirming
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select serinvhShopid, repinvdpartsid
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,
serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate
union all
--Re-Exporting
select rehShopID, reditemid
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''I'' group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate
UNION ALL
--InHouse Return
SELECT IHRHShopID,IHRDItemID
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1
group by IHRHShopID,IHRHID,IHRDItemID
)
shopbin
-------------------------------------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwInquiryShopStock_Pos]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryShopStock_Pos]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Benzigar S D
--Created On : 29/01/2009
--Comment    : To Speed Up POS
CREATE view [dbo].[vwInquiryShopStock_Pos] as
select shopid, itemid
from
(select  shopid, itemid from
mosshopstock
union all
select shopid,itemid from
vwshopbincardaudit_Pos group by shopid,itemid
union all --for taking bad qty
select shopid,itemid  from
vwshopbincardbadqty group by shopid,itemid) inqstock group by shopid, itemid
--------------------------------------------------------------------------------------------------------------------------'
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeShopTransactions]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeShopTransactions]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Regin T.
-- Create date: 21-07-2010
-- =============================================
-- Description:	
--	This proc summarizes shop transactions based on input criteria
--	to speed up calculating shop item stock.
--		If summary date is not specified,
--		this proc summarizes all transactions in closed financial year.
--		If summary date is given,
--		summarizes all trans done on or before given date.
-- =============================================
-- spSummarizeShopTransactions ''20080531''
CREATE PROCEDURE [dbo].[spSummarizeShopTransactions]
	@SummaryDate varchar(10) = ''''
AS
BEGIN
	SET NOCOUNT ON;
	-- If summary date is not specified, summarize all transactions in closed financial year.
	IF @SummaryDate = ''''
	BEGIN
		SELECT @SummaryDate=edate FROM vwFinYearPeriod
		WHERE FinancialId=(SELECT max(FinancialId)-1 finid FROM aAccountFinYearOpening)
	END -- End of if
	-- Clear the summary table
	DELETE FROM losShopTransactionsSummary
	-- Compute and insert trans summary into losShopTransactionsSummary.
	INSERT INTO
		losShopTransactionsSummary
		(SummaryDate, ShopId, ItemId, Stock, BadStock,
		OpeningStock, OpeningBadStock, ShipmentId, ItemCostPrice)
	-- Below part was copied from vwInquiryShopStock
	-- Date filtering was added to get only transaction done on or before summary date.
	SELECT
		@SummaryDate, shopid, itemid, convert(numeric(18,3), sum(stock)) stock,
		sum(badstock) badstock, sum(openingstock) openingstock,
		sum(openingbadstock) openingbadstock,
		1 shipmentid, max(itemcostprice) itemcostprice
	FROM (
		-- 1. Opening Stock
		SELECT
			shopid, itemid, openingstock stock, isnull(openingbadstock,0) badstock
			, isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock
			, itemcostprice
		FROM mosshopstock
		WHERE StockDate<=@SummaryDate
		
		UNION ALL
		-- 2. Shop Bin Card For Good Stock
		SELECT
			shopid,itemid, transqty * mode stock, 0
			, 0, 0, 0
		FROM vwshopbincardaudit
		WHERE sDate<=@SummaryDate
		
		-- 3. Shop Bin Card For Bad Stock
		UNION ALL
		SELECT
			shopid,itemid,  0,  badtransqty * mode badstock
			, 0, 0, 0
		FROM vwshopbincardbadqty
		WHERE sDate<=@SummaryDate
	) inqstock
	GROUP BY shopid, itemid
	-- Save Summary Date in aPackageSettings table
	UPDATE aPackageSettings SET TransactionsSummaryDate=@SummaryDate
END -- End of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopLocationTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by	: Kishore
-- Created on	: 25/08/2003
-- Comments     : This sp updates the location wise stock in total stock verification
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spShopLocationTotalStockVerification] (@intItemId as int,
							@intShopId as int,
							@intSvdId as int,
							@dtUpdate as DateTime,
							@intArrivalDetailId as int OUTPUT,
							@intIssueDetailId as int OUTPUT) AS
Begin
	Declare @numSalesQty as Numeric(18, 8)
	Declare @numVerifiedQty as Numeric(18, 3)
	Declare @intLocationId as int
	Declare @numCurLocationStock as Numeric(18, 3)
	Declare @numSumOut as Numeric(18, 3)
	Declare @numSumIn as Numeric(18, 3)
	-- open the cursor to loop through the locations
	Declare curLocations Cursor for
		SELECT ladLocationId, ladItemQty
		FROM losLocationArrivalDetails
		WHERE ladShopId = @intShopId
		AND ladTransId = @intSvdId
		AND ladInterfaceId = 1900
		AND ladCancel = 1
	Open curLocations
	Fetch Next From curLocations Into @intLocationId, @numVerifiedQty
	While @@fetch_status = 0
	Begin
		
	       /* Interface ids of transaction
		* 1502        Point of Sales
		* 1504        Invoice for credit sales
		* 1518        Goods Exchange
		* 1516        Service Invoice
		* 1518        Goods Exchange
		* 5008        Special Invoice
		* 1512        Goods Return Note	
		*/
		-- get sum of location wise qty transacted in
		-- after starting the ''total stock verification''
		SELECT @numSumOut = SUM(lidItemQty)
			FROM losLocationIssueDetails
			WHERE lidTransId IN
				(SELECT TransID
				FROM vwShopBinCardAudit
				WHERE ItemId = @intItemId
				AND UpdateTime >= @dtUpdate
				AND Type IN (''Cash Sales'', ''Credit Sales'',
				''Exchange Out'', ''Parts Replaced'')
				AND ShopId = @intShopId)
			AND lidShopId = @intShopId
			AND lidInterfaceId IN (1502, 1504, 1518, 1516)
			AND lidItemId = @intItemId
			AND lidLocationId = @intLocationId
		-- get sum qty transacted in
		-- after starting the ''total stock verification''
		SELECT @numSumOut = SUM(ladItemQty)
			FROM losLocationArrivalDetails
			WHERE ladTransId IN
				(SELECT TransId
				FROM vwShopBinCardAudit
				WHERE ItemId = @intItemId
				AND UpdateTime >= @dtUpdate
				AND Type IN (''Exchanged In'', ''Special Invoice Return'',
				''Goods Return'')
				AND ShopId = @intShopId)
			AND ladShopId = @intShopId
			AND ladInterfaceId IN (1518, 5008, 1512)
			AND ladItemId = @intItemId
			AND ladLocationId = @intLocationId
		Set @numSalesQty = @numSumIn - @numSumOut
		-- make the location stock of specified item at
		-- specified location to zero
		-- get current location stock
		-- first get the currect location stock
	SELECT @numCurLocationStock = qty
	FROM
	(SELECT LocationId, ShopId,
		ItemId, SUM(qty) qty
	        FROM
		(SELECT ladLocationId LocationId,
		ladShopId ShopId, ladItemId ItemId , SUM(ladItemQty) qty
	FROM losLocationArrivalDetails
		WHERE ladShopId = @intShopId
	AND ladItemId =  @intItemId
		AND ladCancel = 0
		AND ladLocationId = @intLocationId
		GROUP BY ladLocationId, ladShopId, ladItemId
	UNION ALL
		SELECT lidLocationId, lidShopId, lidItemId, - SUM(lidItemQty)
	        FROM losLocationIssueDetails
	WHERE lidShopId = @intShopId
	        AND lidItemId = @intItemId
		AND lidCancel = 0
		AND lidLocationId = @intLocationId
	        GROUP BY lidLocationId, lidShopId, lidItemId) a
	        GROUP BY LocationId, ShopId, ItemId
	        HAVING SUM(qty) <> 0 ) b,
	        losLocation
	WHERE b.LocationId = losLocation.lLocationId
	        AND b.ShopId = losLocation.lShopId		
		AND b.ItemId = @intItemId  -- for extra safety
		
		-- if stock > 0, insert to issue details
		-- otherwise insert to arrival details
		-- to make the net stock zero
		If @numCurLocationStock > 0
		Begin
			INSERT INTO losLocationIssueDetails
			(lidinterfaceid, lidShopid, lidTransId, liddetailid,
			lidlocationid, liditemid, liditemqty, lidpackingtypeid,
			lidpakingqty, lidcancel, lidadjustment)
			VALUES
			(1900, @intShopId, @intSvdId, @intIssueDetailId,
			@intLocationId, @intItemId,
			ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		Else
		Begin
			INSERT INTO losLocationArrivalDetails
			(ladinterfaceid, ladShopid, ladtransid, laddetailid,
			ladlocationid, laditemid, laditemqty, ladpackingtypeid,
			ladpakingqty, ladcancel, ladadjustment)
			VALUES
			(1900, @intShopId, @intSvdId, @intArrivalDetailId,
			@intLocationId, @intItemId,
			ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		End
		
		-- now insert to arrival/issue details
		If (@numVerifiedQty - @numSalesQty) > 0
		Begin
			INSERT INTO losLocationArrivalDetails
			(ladinterfaceid, ladShopid, ladTransId, laddetailid,
			ladlocationid, laditemid, laditemqty, ladpackingtypeid,
			ladpakingqty, ladcancel, ladadjustment)
			VALUES
			(1900, @intShopId, @intSvdId, @intArrivalDetailId,
			@intLocationId, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intArrivalDetailId = @intArrivalDetailId + 1
		End
		Else
		Begin
			INSERT INTO losLocationIssueDetails
			(lidinterfaceid, lidShopid, lidTransId, liddetailid,
			lidlocationid, liditemid, liditemqty, lidpackingtypeid,
			lidpakingqty, lidcancel, lidadjustment)
			VALUES
			(1900, @intShopId, @intSvdId, @intArrivalDetailId,
			@intLocationId, @intItemId,
			ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 1)
			Set @intIssueDetailId = @intIssueDetailId + 1
		end
		Fetch Next From curLocations Into @intLocationId, @numVerifiedQty		
	End
	Close curLocations
	Deallocate curLocations
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankMonthWise]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsBankMonthWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- created/Modified by    :    Kamesh , Hariharan R, Kishore
-- created/Modified date  :    18/01/2004, 20/02/2004, 23/06/2004
-- purpose            :    Date wise populating Cash flow statement
-- comments            :    accounttype selection added as last column
--                        :    Removed vwJournalParticulars from the link as no fields
--                             of this view are used (23/06/2004)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create PROC [dbo].[spPostingsBankMonthWise] (@intCompanyID as int,
@intAccID as int,
@strType as char(1),
@strFROMDate as varchar(10),
@intdeptid as int,
@strTODate as varchar(10)) as
begin
declare @intnoofrec as int
declare @dtstartdate as datetime
declare @dtenddate as datetime
declare @numopeningamt as numeric(18,2)
Declare @AccType as char(1)
set @numopeningamt = 0.0
set @dtstartdate = convert(datetime,@strfromdate,101)
set @dtenddate=convert(datetime,@strTODate,101)
select @AccType  = AccountType  from aAccountMaster a, aGroupMaster g where a.Groupid = g.GroupId and
a.CompanyId = g.CompanyId and AccountId = @intAccID
exec spopeningbalance @strfromdate, @intaccid,@intcompanyid,@strtype,
@numopeningamt output,@intdeptid
if @intdeptid > 0
select  CompanyID,month(JournalDate)as JournalMonth,year(JournalDate) as JournalYear,departmentID,financialID,
sum(Payment) Payment,sum(Receipt) Receipt,opbal, @AccType AccType from (
SELECT  h.CompanyID,h.JournalDate,d.departmentID,h.financialID,0 Payment,
case when @strtype = ''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
when @strtype =''d'' then sum(d.depamount) end Receipt,  @numopeningamt opbal
FROM moaJournalHeader h, vwJournalDetails d,--vwjournalparticulars  one,
acompanymaster c
WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 0
and d.departmentid = @intdeptid
Group by h.CompanyID,h.JournalDate,  d.departmentID,h.financialID
union all
SELECT  h.CompanyID,h.JournalDate,  d.departmentID,h.financialID,
case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
when @strtype =''d'' then sum(d.depamount) end Payment,0 Receipt,  @numopeningamt opbal
FROM moaJournalHeader h, vwJournalDetails d, -- vwjournalparticulars  one,
acompanymaster c
WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 1
and d.departmentid = @intdeptid
Group by h.CompanyID, h.JournalDate, d.departmentID, h.financialID ) a
group by CompanyID, year(JournalDate), month(JournalDate),
departmentID, financialID, opbal
else
select  CompanyID, month(JournalDate)as JournalMonth,year(JournalDate) as JournalYear, departmentID,financialID,
sum(Payment) Payment,sum(Receipt) Receipt,opbal, @AccType AccType from (
SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
0 Payment,case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
when @strtype =''d'' then sum(d.depamount) end Receipt,  @numopeningamt opbal
FROM moaJournalHeader h, vwJournalDetails d, -- vwjournalparticulars  one,
acompanymaster c
WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit=0
Group by h.CompanyID, h.JournalDate,  d.departmentID,h.financialID
union all
SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
when @strtype =''d'' then sum(d.depamount) end Payment,0 Receipt,  @numopeningamt opbal
FROM moaJournalHeader h, vwJournalDetails d, --vwjournalparticulars  one,
acompanymaster c
WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 1
Group by h.CompanyID, h.JournalDate,d.departmentID,h.financialID ) a
group by CompanyID, Year(JournalDate), month(JournalDate),
departmentID,financialID,opbal
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankDateWise]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsBankDateWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ALTER by dheena, Hariharan, Kishore
-- Created  date 14/11/2003, 20/02/2004, 21/06/2004
-- purpose          : Date wise populating Cash flow statement
-- Verified by 	    : Hariharan
-- Verified Date    : 03/05/2004 (verified From Client DB)
-- Comments         : Removed vwJournalParticulars from view as
--                    no fields from this view was used
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spPostingsBankDateWise] (@intCompanyID as int,
@intAccID as int,
@strType as char(1),
@strFROMDate as varchar(10),
@intdeptid as int,
@strTODate as varchar(10)) as
begin
declare @intnoofrec as int
declare @dtstartdate as datetime
declare @dtenddate as datetime
declare @numopeningamt as numeric(18,2)
Declare @AccType as char(1)
	
	set @numopeningamt = 0.0
	set @dtstartdate = convert(datetime,@strfromdate,101)
	set @dtenddate = convert(datetime,@strTODate,101)
	select @AccType  = AccountType  from aAccountMaster a, aGroupMaster g where a.Groupid = g.GroupId and
	a.CompanyId = g.CompanyId and AccountId = @intAccID
	exec spopeningbalance @strfromdate, @intaccid,@intcompanyid,@strtype,
	@numopeningamt output,@intdeptid
	
	if @intdeptid > 0
begin
		select  CompanyID, JournalDate,  departmentID,financialID,
		sum(Payment) Payment,sum(Receipt) Receipt,opbal, Acctype from (
		SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
		0 Payment,case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
		when @strtype =''d'' then sum(d.depamount) end Receipt,  @numopeningamt opbal, @AccType Acctype
		FROM moaJournalHeader h, vwJournalDetails d, acompanymaster c
		WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
		and h.CompanyID = d.CompanyID
and h.cancel = 0
		and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 0
		and d.departmentid = @intdeptid
		Group by h.CompanyID, h.JournalDate,  d.departmentID,h.financialID
		union all
		SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
		case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
		when @strtype =''d'' then sum(d.depamount) end Payment,0 Receipt,  @numopeningamt opbal, @AccType  Acctype
		FROM moaJournalHeader h, vwJournalDetails d, acompanymaster c
		WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
		and h.CompanyID = d.CompanyID
and h.cancel = 0
		and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit=1
and d.departmentid=@intdeptid		
		Group by h.CompanyID, h.JournalDate,d.departmentID,h.financialID ) a group by
CompanyID, JournalDate,  departmentID,financialID,opbal,Acctype
end
	else
begin
		select  CompanyID, JournalDate,  departmentID,financialID,
		sum(Payment) Payment,sum(Receipt) Receipt,opbal, Acctype from (
		SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
		0 Payment,case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
		when @strtype =''d'' then sum(d.depamount) end Receipt,  @numopeningamt opbal, @AccType Acctype
		FROM moaJournalHeader h, vwJournalDetails d, acompanymaster c
		WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
		and h.CompanyID = d.CompanyID
and h.cancel = 0
		and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 0		
		Group by h.CompanyID, h.JournalDate,  d.departmentID,h.financialID
		union all
		SELECT  h.CompanyID, h.JournalDate,  d.departmentID,h.financialID,
		case when @strtype =''C'' then sum(d.Amount) when @strtype =''a'' then sum(d.actualamount)
		when @strtype =''d'' then sum(d.depamount) end Payment,0 Receipt,  @numopeningamt opbal, @AccType Acctype
		FROM moaJournalHeader h, vwJournalDetails d, acompanymaster c
		WHERE c.companyid = h.companyid
and h.JournalID = d.JournalID
		and h.CompanyID = d.CompanyID
and h.cancel = 0
		and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.journaldate >= @dtstartdate
and h.journaldate <= @dtenddate
and h.financialid > 0
and d.journalcredit = 1
		Group by h.CompanyID, h.JournalDate,d.departmentID,h.financialID ) a
group by CompanyID, JournalDate, departmentID, financialID, opbal, Acctype
end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostingsbank]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsbank]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spPostingsbank 1,12,''c'',''20070101'',0
-- Last Modified on : 05/12/2002
-- Modified by      : leo
-- Comments     : v3
-- Last Modified on : 05/07/2003
-- Modified by      : venki, Hariharan
--description     : added department fileration for   spopeningbalance
--Comments     : Given departmentId filteration
CREATE proc [dbo].[spPostingsbank] @intCompanyID as int, @intAccID as int, @strType as char(1),
@strFROMDate as varchar(10),@intdeptid as int as
begin
declare @intnoofrec as int
declare @dtstartdate as datetime
declare @numopeningamt as numeric(18,2)
set @numopeningamt = 0.0
set @dtstartdate = convert(datetime,@strfromdate,101)
exec spopeningbalance @strfromdate, @intaccid,@intcompanyid,@strtype,
@numopeningamt output,@intdeptid
if isnull(@numopeningamt,0) =0
set @numopeningamt = 0.0
if @intDeptId = 0
Begin
select @intnoofrec = count(*) from
(SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID,
h.type, case when @strtype =''C'' then d.Amount when @strtype =''a'' then d.actualamount
when @strtype =''d'' then d.depamount end as amount,
one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix, updatetime
FROM moaJournalHeader h, vwJournalDetails d, vwjournalparticulars  one, acompanymaster c
WHERE c.companyid = h.companyid and h.JournalID = d.JournalID and h.financialid > 0
and h.CompanyID = d.CompanyID and h.companyid = one.companyid and h.cancel = 0
and h.journalid = one.journalid and one.journalcredit = abs(1-d.journalcredit)
and h.CompanyID = @intcompanyid and d.accountid = @intaccid and h.journaldate >=
@dtstartdate) one
End
Else
Begin
select @intnoofrec = count(*) from
(SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID,
h.type, case when @strtype =''C'' then d.Amount when @strtype =''a'' then d.actualamount
when @strtype =''d'' then d.depamount end as amount,
one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix, updatetime
FROM moaJournalHeader h, vwJournalDetails d, vwjournalparticulars  one, acompanymaster c
WHERE c.companyid = h.companyid and h.JournalID = d.JournalID and h.financialid > 0
and h.CompanyID = d.CompanyID and h.companyid = one.companyid and h.cancel = 0
and h.journalid = one.journalid and one.journalcredit = abs(1-d.journalcredit)
and h.CompanyID = @intcompanyid and d.accountid = @intaccid and h.journaldate >=
@dtstartdate and d.DepartmentID = @intDeptId) one
End
if @intnoofrec > 0
Begin
if @intDeptId =0
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID,
h.type, case when @strtype =''C'' then d.Amount when @strtype =''a'' then d.actualamount
when @strtype =''d'' then d.depamount end amount, one.particulars as particulars,
d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
updatetime, @numopeningamt opbal,BankDate
FROM moaJournalHeader h, vwJournalDetails d,vwjournalparticulars  one, acompanymaster c
WHERE c.companyid = h.companyid and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and h.companyid = one.companyid and h.cancel = 0
and h.journalid = one.journalid and one.journalcredit = abs(1- d.journalcredit)
and h.CompanyID = @intcompanyid and d.accountid = @intaccid and
h.journaldate >= @dtstartdate and h.financialid > 0
else
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID,
h.type, case when @strtype =''C'' then d.Amount when @strtype =''a'' then d.actualamount
when @strtype =''d'' then d.depamount end amount, one.particulars as particulars,
d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
updatetime, @numopeningamt opbal ,BankDate
FROM moaJournalHeader h, vwJournalDetails d,vwjournalparticulars one, acompanymaster c
WHERE c.companyid = h.companyid and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and h.companyid = one.companyid and h.cancel = 0
and h.journalid = one.journalid and one.journalcredit = abs(1- d.journalcredit)
and h.CompanyID = @intcompanyid and d.accountid = @intaccid and
h.journaldate >= @dtstartdate and h.financialid > 0 and d.DepartmentID = @intDeptId
End
else
Begin
if @intDeptId = 0
SELECT  0 JournalID, @intcompanyid companyid, @dtstartdate journaldate,
''no rem'' remarks, NULL departmentid, ''ref no'' referenceno,
c.financialid financialid, ''j'' type, 0.0 amount, ''part'' particulars,
0 journalcredit,''pre'' prefix, @dtstartdate updatetime,
@numopeningamt opbal from acompanymaster c where companyid = @intcompanyid
--Union all
-- select 0, @intcompanyid,@dtstartdate,'''',null,'''',0,'''',0,'''',0,'''',@dtstartdate,@numopeningamt
else
SELECT  0 JournalID, @intcompanyid companyid, @dtstartdate journaldate,
''no rem'' remarks, @intdeptid departmentid, ''ref no'' referenceno,
c.financialid financialid, ''j'' type, 0.0 amount, ''part'' particulars,
0 journalcredit,''pre'' prefix, @dtstartdate updatetime,
@numopeningamt opbal from acompanymaster c where companyid = @intcompanyid
End
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostingsAll]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostingsAll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on : 12/12/2003
-- Modified by      : Kishore
-- Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-- Comments	    : Added separate queries for new method posting and old method posting
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spPostingsAll] (@intCompanyID as int,
@strFromdate as varchar(10),
@strToDate as varchar(10),
@bitcons as bit) AS
begin
set nocount on
CREATE table #temp(
		companyid  int,
		accountid  int,
		opdebitamt  numeric(18,2),
		opcreditamt  numeric(18,2)
		)
declare @dtFromdate as datetime,
	@dtTodate as datetime,
	@intaccid as int,
	@numopeningcredit as numeric(18,2),
	@numopeningdebit as numeric(18,2),
	@numopening as numeric(18,2),
	@straccountype as varchar(5),
	@dtfinstartdate as datetime
	
	set @dtfromdate = convert(datetime,@strfromdate)
	set @dttodate = convert(datetime,@strtodate)
	select @dtfinstartdate = sdate from vwfinyearperiod where CurFinancialYear =1
	declare opcur cursor for
	SELECT distinct(d.accountid) , Accounttype FROM moaJournalHeader h, vwjournaldetails d,
	aaccountmaster am, agroupmaster g WHERE am.groupid = g.groupid and h.JournalID =
	d.JournalID and h.CompanyID = d.CompanyID and am.companyid =
	d.companyid and am.accountid = d.accountid  and h.CompanyID = @intcompanyid and
	h.cancel=0 and h.journaldate >= @dtfromdate and h.financialid > 0 and
	h.journaldate <= @dttodate and d.accountid is not null
	open opcur
	fetch next from opcur into @intaccid, @straccountype
	while @@fetch_status =0
	begin
		set @numopening =0.0
		if @bitcons = 1
			exec spopeningbalance @strFromDate, @intaccid, @intcompanyid, ''c'',
			@numOpening  output
		else
			exec spopeningbalance @strFromDate, @intaccid, @intcompanyid, ''d'',
			@numOpening  output
		set @numopeningdebit = 0.0
		set @numopeningcredit = 0.0
		if @straccountype = ''A'' or @straccountype = ''E''
			if @numopening >=0
			    set @numopeningdebit = @numopening
			else
			    set @numopeningcredit = @numopening
		else
			if @numopening >=0
			    set @numopeningcredit = @numopening
			else
			    set @numopeningdebit = @numopening
		insert into #temp values (@intcompanyid, @intaccid, @numopeningdebit,
		@numopeningcredit)
		fetch next from opcur into @intaccid, @straccountype
	end	-- end for while
	close opcur
	deallocate opcur
	SELECT h.JournalID, h.CompanyID, gm.accounttype, am.accountdesc, h.JournalDate,
	h.remarks, d.departmentID, h.referenceno,h.financialID, h.type, case when @bitcons = 0
	then d.depAmount else d.amount end amount, one.particulars as particulars,
	d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
	#temp.opcreditamt, #temp.opdebitamt, h.updatetime
	FROM moaJournalHeader h, moaJournalDetails d left outer join #temp
on d.companyid = #temp.companyid
and d.accountid = #temp.accountid, vwjournalparticulars one,
aaccountmaster am, agroupmaster gm
	WHERE am.groupid = gm.groupid
and am.companyid = gm.companyid
and am.companyid = d.companyid
	and am.accountid = d.accountid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
	and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
	and h.CompanyID = @intcompanyid
and h.financialid > 0
and h.cancel = 0
and h.journaldate >= @dtfromdate
and h.journaldate <= @dttodate
and d.accountid is not null
and d.PostGroup IS NULL
Union All
	SELECT h.JournalID, h.CompanyID, gm.accounttype, am.accountdesc, h.JournalDate,
	h.remarks, d.departmentID, h.referenceno,h.financialID, h.type, case when @bitcons = 0
	then d.depAmount else d.amount end amount, one.particulars as particulars,
	d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
	#temp.opcreditamt, #temp.opdebitamt, h.updatetime
	FROM moaJournalHeader h, moaJournalDetails d left outer join #temp
on d.companyid = #temp.companyid
and d.accountid = #temp.accountid, vwNewJournalDetails one,
aaccountmaster am, agroupmaster gm
	WHERE am.groupid = gm.groupid
and am.companyid = gm.companyid
and am.companyid = d.companyid
	and am.accountid = d.accountid
and h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
	and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
	and h.CompanyID = @intcompanyid
and h.financialid > 0
and h.cancel = 0
and h.journaldate >= @dtfromdate
and h.journaldate <= @dttodate
and d.accountid is not null
and d.PostGroup IS NOT NULL
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostings_Detail]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostings_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by : Sreejith G A
--Created on : 20100810
--To show department wise General Ledger
--spPostings 1,918,0,''20100909''
--go
--spPostings_Detail 1,324,0,''20100101'',''20100909''
------------------------------------------------
--RefNo:1
--Modified By : VinothMurugan V
--Date    : 26/08/2010
---Purpose    : Increase The Length
CREATE PROC [dbo].[spPostings_Detail] (@intCompanyID as int,
@intAccID as int,
@intdepid as int,
@dtFromdate as varchar(10) ,   --Use only to find the Balance Till this Date
@dttodate as varchar(10)) AS
begin
declare @FinalBalance numeric(18,2)
declare @Acctype as varchar(20)   --RefNo:1
select @Acctype=  GM.AccountType from  aaccountmaster AM  left outer join agroupmaster gm on GM.GroupID = AM.GroupID
where AM.accountid=@intAccID
create table #temp(Companyid int,Departmentid  int,
Accountid int,
AccCode varchar(25),
AccDesc varchar(100),  --RefNo:1
AccType varchar(20),   --RefNo:1
GroupId int,
GroupName varchar(200),
DepName varchar(150),
OpeningBalance numeric(18,2))
insert into #temp
exec spOpeningBalance_Detail @dtFromdate,@intCompanyID
--Finds the final balance after the from date.
create table #tempFinalBalance(Companyid int,Departmentid  int,
Accountid int,
AccCode varchar(25),
AccDesc varchar(100),
AccType varchar(20),   --RefNo:1
GroupId int,
GroupName varchar(100), --RefNo:1
DepName varchar(150),   --RefNo:1
OpeningBalance numeric(18,2))
insert into #tempFinalBalance
exec spOpeningBalance_Detail @dttodate,@intCompanyID
select @FinalBalance= sum(OpeningBalance) from #tempFinalBalance where Accountid=@intAccID
-- select @FinalBalance
-- for new breed of postings
SELECT v.accountid,JournalID,  v.CompanyID, JournalDate, remarks, v.departmentID,
referenceno, financialID, type, Amount ,particulars,
journalcredit,prefix,updatetime,depamount,actualamount,departmentname ,isnull(#temp.OpeningBalance,0) Balance,isnull(#temp.AccType,@Acctype) Acctype,isnull(@FinalBalance,0) FinalBalance from
(SELECT d.accountid,h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount ,ad.departmentname
FROM moaJournalHeader h, vwJournalDetails d, vwNewJournalDetails one   ,adepartmentmaster ad
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and one.postgroup =  d.postgroup
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NOT NULL
and ad.departmentid= d.departmentID
Union All
-- for old breed of postings
SELECT d.accountid,h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount ,ad.departmentname
FROM moaJournalHeader h, vwJournalDetails d, vwjournalparticulars one ,adepartmentmaster ad
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid                             and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0                          and d.PostGroup IS NULL
and ad.departmentid= d.departmentID )v
left outer join  #temp on #temp.departmentid=v.departmentid  and #temp.Accountid=v.accountid
union all
select #temp.accountid,0,#temp.Companyid,@dttodate,'''',#temp.departmentid,'''',0,'''',0,'''',
0,'''','''',0,0,#temp.depname,#temp.OpeningBalance,isnull(#temp.AccType,@Acctype) Acctype ,isnull(@FinalBalance,0) FinalBalance from #temp
where #temp.Accountid=@intAccID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPostings]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPostings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on  : 12/12/2003,22-11-2011,24-11-2011
-- Modified by       : Kishore jyothish
-- Comments  : given a blank record for showing opening balance on report (26/08/2003)
--                      : Added separate queires for new method posting and old method posting (12/12/2003)
--   GST posting is added
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spPostings] (@intCompanyID as int,
@intAccID as int,
@intdepid as int,
@dttodate as varchar(10)) AS
begin
declare @openbal as numeric(18,2)
if @intdepid = 0
Begin
exec spopeningbalance @dttodate, @intaccid, @intcompanyid, ''c'', @openbal output, @intdepid
End
else
Begin
exec spopeningbalance @dttodate, @intaccid, @intcompanyid, ''d'', @openbal output, @intdepid
End
if @openbal = 0.00
Begin
-- for new breed of postings
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwNewJournalDetails one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid
and one.postgroup =  d.postgroup
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NOT NULL    and d.accountid not in (select TaxAccountId from aTaxCategoryMaster )
Union All
---------------------GST posting------------------------
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwNewJournalDetails_GST one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid
and one.postgroup =  d.postgroup
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NOT NULL
and d.accountid in(select TaxAccountId from aTaxCategoryMaster ) and TYPE in (''SCI'' ,''POSGRN'')
-----------------------------------------------------------------------------------
union  All
-- for old breed of postings
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwjournalparticulars one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NULL
End
else
Begin
-- for new breed of postings
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwNewJournalDetails one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and one.postgroup =  d.postgroup
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NOT NULL  and d.accountid not in (select TaxAccountId from aTaxCategoryMaster )
Union All
---------------------GST posting------------------------
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwNewJournalDetails_GST one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid
and one.postgroup =  d.postgroup
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NOT NULL
and d.accountid in(select TaxAccountId from aTaxCategoryMaster )  and TYPE in (''SCI'' ,''POSGRN'')
-----------------------------------------------------------------------------------
Union all
-- for old breed of postings
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno, h.financialID, h.type, d.Amount ,one.particulars as particulars,
d.journalcredit,
case d.JournalCredit when 1 then ''By'' when 0 then ''To'' end as prefix,
h.updatetime, d.depamount, d.actualamount
FROM moaJournalHeader h, vwJournalDetails d, vwjournalparticulars one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.cancel = 0
and financialid > 0
and d.PostGroup IS NULL
union all
SELECT 0, 1, @dttodate, '''', @intdepid, '''', 0, '''',  0 , '''', 0, '''', @dttodate, 0, 0
End
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPLuserformat]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

GO
/****** Object:  View [dbo].[vwdeliverynotenew]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdeliverynotenew]'))
EXEC dbo.sp_executesql @statement = N'
----------
-----------------------------------------------------------------------------------------------------------------
--Created By : Yogesh Joe
--Created On : 09-06-2010
--Purpose :
-- To use in the reports - Customer-wise Delivery Notes,Item-wise Delivery Notes
-----------------------------------------------------------------------------------------------------------------
--Ref:01
--Modified on : 16/02/2011
--Modified By : Nidheesh P V
--Comments : Added the option for cash customer in pos part
----------------------------------------------------------------------------------------------
CREATE view [dbo].[vwdeliverynotenew] as
select itemdescription,dndnid, dndnno,
dnshopid, dndndate, iditemid, idquantity, idpquantity, UnitCode, packingtypecode,
customername, Address1, Address2, Address3, Symbol, idpackingtypeid,unitid,
itemcode, unitname, packingtypename, PONO,podate,
ihReferenceNo, Part_code, volume,dncancelled,DNDeliveryType ,
Case isnull(dndQty,0)  when 0 then idquantity else dndQty End as dndQty,idUnitPrice,
DnCustomerID,DnDeliveredBy,DnReceivedBY,DnRemarks,DnDeliveryTime,dnContactNumber,dnDeliveryAddress1,
dnDeliveryAddress2,dnDeliveryAddress3,dnStatus,dnConfirmed,Detail.DnDinvoiceId,PhoneNo,DeliveryTime,CompanyID
From
(
Select Distinct case when (iddescription is null or iddescription ='''')
then vw.itemdescription else iddescription end  itemdescription, dndnid, dndnno,
dnshopid, dndndate, iditemid, idquantity, idpquantity, UnitCode, packingtypecode,
ISNULL(customername,dnCustomerName) customername, ISNULL(Address1,dnCustomerAddress1) Address1, ISNULL(Address2,dnCustomerAddress2) Address2,
ISNULL(Address3,dnCustomerAddress3) Address3, Symbol, idpackingtypeid, u.unitid,
a.itemcode, unitname, packingtypename, ih.ihinvoiceno PONO, ih.ihinvoicedate podate,
ih.ihReferenceNo, Part_code, isnull(Volume,0) volume,dncancelled,DNDeliveryType,idUnitPrice,
DnCustomerID,DnDeliveredBy,DnReceivedBY,DnRemarks,DnDeliveryTime,ISNULL(dnContactNumber,ac.PhoneNo) dnContactNumber,dnDeliveryAddress1,
dnDeliveryAddress2,dnDeliveryAddress3,dnStatus,dnConfirmed,dd.DnDinvoiceId,ac.PhoneNo,DeliveryTime= LTRIM(SUBSTRING(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 10, 5) + RIGHT(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 3)),c.CompanyID
from
losdeliverynoteheader dh, losdeliverynotedetail dd,losinvoiceheader ih,losinvoicedetail d
, aitem a, apackingtype p,
vwitemdescription vw, aunit u, acustomermaster ac, acurrencymaster c
where
ih.ihinvoiceid = d.idinvoiceid and ih.ihshopid = d.idshopid and
dh.dndnid = dd.dnddnid and dh.dnshopid = dd.dnDshopid and d.idshopid = dd.dndshopid and
dd.dndinvoiceid = d.idinvoiceid and idpackingtypeid=p.packingtypeid and
iditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid  and
ac.customerid = dncustomerid and ac.currencyid=c.currencyid
AND dd.DnDinvoiceId=d.idInvoiceID ) Detail
INNER Join
(SELECT did.*,dd.DnDinvoiceId FROM losdeliverynoteItemDetails did INNER JOIN losdeliverynotedetail dd
ON did.dndShopID=dd.DnDShopid AND did.dndId=dd.DnDdnId AND did.dndDetailID=dd.DnDetailId)delivery
ON detail.dndnid=delivery.dndID  And detail.dnshopid=delivery.dndShopID And delivery.dndItemID=Detail.idItemID
AND  Detail.DnDinvoiceId=delivery.DnDinvoiceId
Union All
select itemdescription, dndnid, dndnno, dnshopid, dndndate, posditemid, posdquantity, posdpquantity,
UnitCode, packingtypecode,customername, Address1, Address2, Address3, Symbol, posdpackingtypeid, unitid,
itemcode, unitname, packingtypename,PONO,podate,null, Part_code, volume,dncancelled,DNDeliveryType,
Case isnull(dndQty,0)  when 0 then posdquantity else dndQty End as dndQty,posdUnitPrice,
DnCustomerID,DnDeliveredBy,DnReceivedBY,DnRemarks,DnDeliveryTime,dnContactNumber,dnDeliveryAddress1,
dnDeliveryAddress2,dnDeliveryAddress3,dnStatus,dnConfirmed,Detail.dndBillID,PhoneNo,DeliveryTime,CompanyID
From
(
select
distinct case when (posddescription is null or posddescription ='''')
then vw.itemdescription else posddescription end  itemdescription, dndnid, dndnno,
dnshopid, dndndate, posditemid, posdquantity, posdpquantity, UnitCode, packingtypecode,
--ISNULL(dnCustomerName,customername) customername, ISNULL(dnCustomerAddress1,Address1) Address1, ---Ref:01
--ISNULL(dnCustomerAddress2,Address2) Address2, ISNULL(dnCustomerAddress3,Address3) Address3,     ---Ref:01
case when DnCustomerID is Not null then ISNULL(dnCustomerName,customername) else ''Cash Customer'' end customername, --Ref:01
case when DnCustomerID is Not null then ISNULL(dnCustomerAddress1,Address1) else '''' end Address1,
case when DnCustomerID is Not null then ISNULL(dnCustomerAddress2,Address2) else '''' end Address2,
case when DnCustomerID is Not null then ISNULL(dnCustomerAddress3,Address3) else '''' end Address3,
Symbol, posdpackingtypeid, u.unitid,
a.itemcode, unitname, packingtypename, ih.poshbillno PONO, ih.poshbilldate podate,
Part_code, isnull(Volume,0) volume,dncancelled,DNDeliveryType,posdUnitPrice,
DnCustomerID,DnDeliveredBy,DnReceivedBY,DnRemarks,DnDeliveryTime,
--ISNULL(dnContactNumber,ac.PhoneNo)dnContactNumber,        ---Ref:01
case when DnCustomerID is Not null then ISNULL(dnContactNumber,ac.PhoneNo) else dnContactNumber end dnContactNumber, ---Ref:01
dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,dnStatus,dnConfirmed,dd.dndBillID,
--ac.PhoneNo,                      ---Ref:01
case when DnCustomerID is Not null then ac.PhoneNo else dnContactNumber end PhoneNo, ---Ref:01
DeliveryTime= LTRIM(SUBSTRING(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 10, 5) + RIGHT(CONVERT(VARCHAR(20),
CONVERT(DATETIME, DnDeliveryTime), 22), 3)),c.CompanyID
from
losdeliverynoteheader dh, losdeliverynotedetail dd, losposheader ih,
losposdetail d, aitem a, apackingtype p,
vwitemdescription vw, aunit u, acustomermaster ac,acurrencymaster c,aAccountMaster acc
where
ih.poshbillid = d.posdbillid and ih.poshshopid = d.posdshopid and
dh.dndnid = dd.dnddnid and dh.dnshopid = dd.dnDshopid and d.posdshopid = dd.dndshopid and
dd.dndbillid = d.posdbillid and posdpackingtypeid=p.packingtypeid and
posditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid and dd.dndBillID=d.posdBillID and
((ac.customerid = dncustomerid and DnCustomerID is Not null) or (DnCustomerID is null)) and ---Ref:01
((ac.currencyid=c.currencyid and DnCustomerID is Not null)or(acc.AccountID=poshCashAccID and acc.CurrencyID=c.currencyid and DnCustomerID is null))--Ref:01
)Detail
INNER Join
(SELECT did.*,dd.dndBillID FROM losdeliverynoteItemDetails did INNER JOIN losdeliverynotedetail dd
ON did.dndShopID=dd.DnDShopid AND did.dndId=dd.DnDdnId AND did.dndDetailID=dd.DnDetailId
) delivery
ON detail.dndnid=delivery.dndID  And detail.dnshopid=delivery.dndShopID And delivery.dndItemID=posdItemID
and detail.posdQuantity=delivery.dndqty and Detail.dndBillID=delivery.dndBillID'
GO
/****** Object:  View [dbo].[vwdeliverynote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdeliverynote]'))
EXEC dbo.sp_executesql @statement = N'
----------
--Last Modified on  : 21/04/2003
--Last modified by  : Rajesh
--Modified by  : Lawrence.J ,Shinu
--Modified On  : 06/04/2003
--Comments  :Shopid join condition is given
--Modified by  :Santhosh m
--Comments  :added dncancelled on 30/09/2003
--Modified ON : 20/11/2007,28/06/2008
--Modified by :Shinu ,Shinu
--Comments : Added Delivery note for POS
--    : Added losdeliverynoteItemDetails
--Modified by :Benzigar
--Modified On :05/09/2009
--Comment     :Added unit price
--Modified by :Abhishek
--Modified On:21/10/09
--for avoiding duplication of same item with different packingtype
--added is:  detail.posdQuantity=did.dndqty
--Modified by : Sreejith G A
--Modified on : 26/10/2010
--Purpose : To show some more fields in the report rptDeliveryNote
--Comment : Added the fields - DnDeliveryTime,dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,dndItemRemarks,dnContactNumber
--   to the view
----------------------------------------------------------------------------------------------
--Ref:01
--Modified on : 16/02/2011
--Modified By : Nidheesh P V
--Comments : Added the option for cash customer in pos part
----------------------------------------------------------------------------------------------
--Ref:02
--Modified on : 27/05/2011
--Modified By : Aadyakumar.D.V
--Comments    : Joins(left outer join) details of losDeliveryDetails  to existing view
----------------------------------------------------------------------------------------------
--Ref:03
--Modified on : 22/02/2012
--Modified By : Aadyakumar.D.V
--Comments    : Added idBillDetailID,posdbilldetailid for ordering the report
----------------------------------------------------------------------------------------------
--select * from vwdeliverynote where dnshopid=2 and dndnid=73
CREATE view [dbo].[vwdeliverynote] as
select case when CustomerName='''' then ''Cash Customer'' else CustomerName end Customer,
case when DeliveryRemarks='''' then DnRemarks else DeliveryRemarks end Remark,* from --Ref:02
(select itemdescription,dndnid, dndnno,
dnshopid, dndndate, iditemid, idquantity, idpquantity, UnitCode, packingtypecode,customername as name,
Address1, Address2, Address3, Symbol, idpackingtypeid,unitid,
itemcode, unitname, packingtypename, PONO,podate,
ihReferenceNo, Part_code, volume,dncancelled,DNDeliveryType ,
Case isnull(dndQty,0)  when 0 then idquantity else dndQty End as dndQty,idUnitPrice,DnDeliveryTime,
dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,did.dndItemRemarks,dnContactNumber,dndbillid,DnRemarks,
idBillDetailID --Ref:03
From
(Select Distinct case when (iddescription is null or iddescription ='''')
then vw.itemdescription else iddescription end  itemdescription, dndnid, dndnno,
dnshopid, dndndate, iditemid, idquantity, idpquantity, UnitCode, packingtypecode,
Address1, Address2, Address3, Symbol, idpackingtypeid, u.unitid,customername,
a.itemcode, unitname, packingtypename, ih.ihinvoiceno PONO, ih.ihinvoicedate podate,
ih.ihReferenceNo, Part_code, isnull(Volume,0) volume,dncancelled,DNDeliveryType,idUnitPrice,DnDeliveryTime,
dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,dnContactNumber
,case when dndbillid IS null then DnDinvoiceId else dndbillid end dndbillid,
DnRemarks,
idBillDetailID --Ref:03
from
losdeliverynoteheader dh, losdeliverynotedetail dd,losinvoiceheader ih,losinvoicedetail d
, aitem a, apackingtype p,
vwitemdescription vw, aunit u, acustomermaster ac, acurrencymaster c
where
ih.ihinvoiceid = d.idinvoiceid and ih.ihshopid = d.idshopid and
dh.dndnid = dd.dnddnid and dh.dnshopid = dd.dnDshopid and d.idshopid = dd.dndshopid and
dd.dndinvoiceid = d.idinvoiceid and idpackingtypeid=p.packingtypeid and
iditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid  and
ac.customerid = dncustomerid and ac.currencyid=c.currencyid
) Detail
Left Outer Join losdeliverynoteItemDetails did
ON detail.dndnid=did.dndID  And detail.dnshopid=did.dndShopID And dndItemID=idItemID)
Delivery --Ref:02
left outer join losDeliveryDetails lod on Delivery.dnshopid=lod.ShopId --Ref:02
and Delivery.dndbillid=case when lod.CashInvoiceId is null then lod.CreditInvoiceId else lod.CashInvoiceId end --Ref:02
Union All
select case when CustomerName='''' then ''Cash Customer'' else CustomerName end Customer,
case when DeliveryRemarks='''' then DnRemarks else DeliveryRemarks end Remark,* from  --Ref:02
(select itemdescription, dndnid, dndnno, dnshopid, dndndate, posditemid, posdquantity, posdpquantity,
UnitCode, packingtypecode,customername as name, Address1, Address2, Address3, Symbol, posdpackingtypeid, unitid,
itemcode, unitname, packingtypename,PONO,podate,'''' ihReferenceNo, Part_code, volume,dncancelled,DNDeliveryType,
Case isnull(dndQty,0)  when 0 then posdquantity else dndQty End as dndQty,posdUnitPrice,DnDeliveryTime,
dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,did.dndItemRemarks,dnContactNumber,dndbillid,DnRemarks,
posdbilldetailid --Ref:03
From
(
select
distinct case when (posddescription is null or posddescription ='''')
then vw.itemdescription else posddescription end  itemdescription, dndnid, dndnno,
dnshopid, dndndate, posditemid, posdquantity, posdpquantity, UnitCode, packingtypecode,
--customername,Address1,Address2,Address3                     --Ref:01
case when DnCustomerID is Not null then customername else ''Cash Customer'' end customername, --Ref:01
case when DnCustomerID is Not null then Address1 else '''' end Address1,
case when DnCustomerID is Not null then Address2 else '''' end Address2,
case when DnCustomerID is Not null then Address3 else '''' end Address3,
Symbol,posdpackingtypeid, u.unitid,
a.itemcode, unitname, packingtypename, ih.poshbillno PONO, ih.poshbilldate podate,
Part_code, isnull(Volume,0) volume,dncancelled,DNDeliveryType,posdUnitPrice,DnDeliveryTime,
dnDeliveryAddress1,dnDeliveryAddress2,dnDeliveryAddress3,dnContactNumber
,case when dndbillid IS null then DnDinvoiceId else dndbillid end dndbillid,DnRemarks,
posdbilldetailid --Ref:03
from
losdeliverynoteheader dh, losdeliverynotedetail dd, losposheader ih,
losposdetail d, aitem a, apackingtype p,
vwitemdescription vw, aunit u, acustomermaster ac, acurrencymaster c,aAccountMaster acc
where
ih.poshbillid = d.posdbillid and ih.poshshopid = d.posdshopid and
dh.dndnid = dd.dnddnid and dh.dnshopid = dd.dnDshopid and d.posdshopid = dd.dndshopid and
dd.dndbillid = d.posdbillid and posdpackingtypeid=p.packingtypeid and
posditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid and
((ac.customerid = dncustomerid and DnCustomerID is Not null) or (DnCustomerID is null)) and ---Ref:01
((ac.currencyid=c.currencyid and DnCustomerID is Not null)or(acc.AccountID=poshCashAccID and acc.CurrencyID=c.currencyid and DnCustomerID is null))--Ref:01
)Detail
Left Outer Join losdeliverynoteItemDetails did
ON detail.dndnid=did.dndID  And detail.dnshopid=did.dndShopID And dndItemID=posdItemID
and detail.posdQuantity=did.dndqty
) Delivery --Ref:02
left outer join losDeliveryDetails lod on Delivery.dnshopid=lod.ShopId --Ref:02
and Delivery.dndbillid=case when lod.CashInvoiceId is null then lod.CreditInvoiceId else lod.CashInvoiceId end --Ref:02'
GO
/****** Object:  View [dbo].[vwDummyUniPriceVariancePerBill]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDummyUniPriceVariancePerBill]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on 	        : 02/09/03
-- Modified by		: venki
-- Comments		: added dept
---------------------------------------------------
-- Modifed on           : 30/12/2003
-- Modified by          : Kishore
-- Comments             : Added currency symbol field
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDummyUniPriceVariancePerBill] AS
select pbhBillNo, pbhBillDate, pd1.pbdItemId,
(pd1.pbddummyunitprice/pd1.pbdItemQuantity) pbdDummyUnitPrice,
vi.ItemDescription, pbhDepartmentId, c.Symbol CurrencySymbol
from losppurchasebillheader ph, losppurchasebilldetail pd1,
losppurchasebilldetail pd2, vwitemdescription vi, aVendorMaster v, aCurrencyMaster c
where vi.itemid = pd1.pbditemid
and ph.pbhbillid = pd1.pbdbillid
and pd1.pbditemid = pd2.pbditemid
and ph.pbhVendorId = v.VendorId
and v.CurrencyId = c.CurrencyId
and pd1.pbdbillid <> pd2.pbdbillid
and pd1.pbddummyunitprice <> pd2.pbddummyunitprice'
GO
/****** Object:  View [dbo].[vwendoritemdescription]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwendoritemdescription]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwendoritemdescription] as
select * from vwitemdesc where poditemid not in (select poditemid from vwitemdesc where type=0)
union
select * from vwitemdesc where type=0'
GO
/****** Object:  View [dbo].[vwDiscountFromSupplierPerShipment]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountFromSupplierPerShipment]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on 	: 31/12/2003
-- Modified by		: Kishore
-- Comments		: Added currencySymbol field
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDiscountFromSupplierPerShipment] AS
select vendorname, pbhbillno,pbhbilldate,pbhbillid, pbditemid, vw.itemdescription,
pbdItemQuantity, pbditemunitprice, pbddiscount, pbhvendorid,
itemcode,pbhdepartmentid, c.Symbol CurrencySymbol
from losppurchasebillheader h, losppurchasebilldetail d,
avendormaster v,vwitemdescription vw, aitem ai, aCurrencyMaster c
where h.pbhbillid = d.pbdbillid
and pbhvendorid = v.vendorid
and vw.itemid = pbditemid
and vw.itemid = ai.itemid
and v.CompanyId = c.CompanyId
and v.CurrencyId = c.CurrencyId
and pbhdiscount > 0
and pbddiscount > 0'
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchVehicleList]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpMag_FetchVehicleList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Create By   : VinothMurugan
--Create Date : 08/09/2010
--Purpose     : Fetch the vehicle
-------------------------------------
--exec SpMag_FetchVehicleList ''RWREQ'',1,1
CREATE PROCEDURE [dbo].[SpMag_FetchVehicleList](@strModule as varchar(50),@intShopid as int,@Companyid AS int)
as
IF @strModule=''RWREQ''
BEGIN
--select *,poshBillID PosId from losHpItemRegistrationDetails IRD  inner join losposheader on IRTransactionID = poshBillID where poshCancelled = 0 and
--IRD.IRRegistrationID not in (select RegistrationID from LosVrRoadWorthnessReqDetails) and IRD.ircompanyid = @Companyid
--select *,poshBillID PosId from losHpItemRegistrationDetails IRD  inner join losposheader on IRTransactionID = poshBillID where poshCancelled = 0 and
--IRD.IRRegistrationID not in (select RegistrationID from LosVrRoadWorthnessReqDetails d  left outer join  LosVrRoadWorthnessReq h
--on h.RoadWorthnessRequestId = d.RoadWorthnessRequestId where h.Deleted = 0 ) and IRD.ircompanyid = @Companyid
	select *,IRTypeOfVehicle TypeOfVehicle from
	(
		select poshBillNo,poshBillDate,posdShopID,posdBillID PosId,0 InvoiceId,posdItemID itemid,''POS'' TType
		from losposdetail A left outer join losposheader B on B.poshShopID=A.posdShopID
			and B.poshBillID=A.posdBillID and  B.poshCompanyID=@companyid
		where posdShopID=@intshopid and posdBillID not in
		(
			select isnull(posid,0) from LosVrRoadWorthnessReqDetails A left outer join
				LosVrRoadWorthnessReq B on A.RoadWorthnessRequestId=B.RoadWorthnessRequestId
			where deleted=0
		)
		
		UNION ALL
		
		select ihInvoiceNo,ihInvoiceDate,idShopID,0 PosId,idInvoiceID InvoiceId,idItemID itemid ,''INV'' TType
		from losinvoicedetail A left outer join losinvoiceheader B on B.ihShopID=A.idShopID
			and B.ihInvoiceID=A.idInvoiceID
		where idShopID=@intshopid  and   idInvoiceID not in
		(
			select isnull(InvoiceId,0) from LosVrRoadWorthnessReqDetails A left outer join LosVrRoadWorthnessReq B
				on A.RoadWorthnessRequestId=B.RoadWorthnessRequestId
			where deleted=0
		)
	)v
left outer join losHpItemRegistrationDetails C on C.IRItemID=v.itemid and
		(IrInterfaceID=1502 and IRTransactionID=PosId) or (IrInterfaceID=1504 and IRTransactionID=InvoiceId)
	left outer join acolor ac on IRColorID=colorid
	inner join aitem D on D.itemid=C.irItemID and D.HirePurchase=1
end
if @strModule=''RWRCPT''
begin
select *,isnull(CustomerName,'''')CustomerName,NICNO
from LosVrRoadWorthnessReqDetails A
		left outer join LosVrRoadWorthnessReq B on A.RoadWorthnessRequestId=B.RoadWorthnessRequestId
		left outer join losHpItemRegistrationDetails on A.RegistrationID=IRRegistrationID
		left outer join losposheader  on A.posid=poshBillID and B.Shopid= poshShopID   --
		left outer join losinvoiceheader Inv on A.invoiceid=ihInvoiceID and B.Shopid=  ihShopID
		left outer join losspecialinvoiceheader sInv on A.spinvoice=sInv.IhInvoiceID and B.Shopid= sInv.IhShopID
		left outer join acustomermaster AC on AC.CustomerId=Coalesce(poshcustomerid,Inv.ihCustomerID,sInv.IhCustomerID)
where A.RegistrationID not in
(	
		select isnull(RegistrationID,0) from LosVrRoadWorthnessReceiptDetail  A
			left outer join LosVrRoadWorthnessReceipt B on A.RoadWorthnessRecptId=B.RoadWorthnessRecptId
		where deleted=0
)   AND B.SHOPID= @intShopid and B.Deleted=0
end
if @strModule=''RWSUB''						
begin
	select * from LosVrRoadWorthnessReceiptDetail wrd
		left outer join LosVrRoadWorthnessReceipt wrh on wrh.RoadWorthnessRecptId=wrd.RoadWorthnessRecptId
		left outer join  losHpItemRegistrationDetails on wrd.RegistrationID=IRRegistrationID
		--select * from LosVrRoadWorthnessReceiptDetail wrd  left outer join LosVrRoadWorthnessReceipt wrh
		-- on wrh.RoadWorthnessRecptId=wrd.RoadWorthnessRecptId
		--left outer join  losHpItemRegistrationDetails  on wrd.RegistrationID=IRRegistrationID   --where   wrh.Deleted = 0
		left outer join losposheader on poshBillID = wrd.posid--IRTransactionID
		left outer join losinvoiceheader Inv  on wrd.invoiceid=ihInvoiceID
		left outer join losspecialinvoiceheader sInv on wrd.spinvoice=sInv.IhInvoiceID
		--inner join acustomermaster c on customerid = poshcustomerid
	where wrd.CompanyId = @companyid and wrh.Deleted = 0
	and wrd.RegistrationID not in (select isnull(RegistrationID,0) from LosVrRegistartionSubmissionDetail d
	left outer join LosVrRegistartionSubmission h on d.RegistartionSubId = h.RegistartionSubId
	where Deleted = 0 )
END
if @strModule=''RWSCON''
begin
	select RoadWorthnessNo IRRoadWorthiness,IRModelNo,rsd.RegistartionSubId,IRRegistrationID,
		IRTransactionID PosId,CustomerName --  RoadWorthnessNo
	from LosVrRegistartionSubmissionDetail rsd
		left outer join LosVrRegistartionSubmission rs on rsd.RegistartionSubId=rs.RegistartionSubId
		left outer join losHpItemRegistrationDetails on rsd.RegistrationID=IRRegistrationID and rsd.CompanyId=IRCompanyID
		--left outer join LosVrRoadWorthnessReceiptDetail rrd on rrd.RoadWorthnessRecptId = rsd.RoadWorthnessRecptId
		LEFT OUTER join losposheader on poshBillID = rsd.posid and poshShopID = rs.shopid
		left outer join losinvoiceheader Inv on rsd.invoiceid=ihInvoiceID and rs.Shopid= ihShopID
		left outer join losspecialinvoiceheader sInv on rsd.spinvoice=sInv.IhInvoiceID and rs.Shopid=sInv.IhShopID
		left outer join acustomermaster c on customerid = poshcustomerid
		left outer join LosVrRoadWorthnessReceiptDetail rrd on rrd.RoadWorthnessRecptId = rsd.RoadWorthnessRecptId
		left outer join LosVrRoadWorthnessReceipt rwr on  rwr.RoadWorthnessRecptId = rrd.RoadWorthnessRecptId
	where rsd.CompanyId = @companyid and rs.Deleted = 0 and rwr.deleted = 0 and rrd.PosId = rsd.PosId
		and rsd.RegistrationID not in (select isnull(RegistrationID,0) from LosVrRegistartionSubmissionConfDetail d
		left outer join LosVrRegistartionSubmissionConf h on d.RegistartionSubConfId = h.RegistartionSubConfId
		where Deleted = 0 )
	-- select * from   LosVrRegistartionSubmissionDetail rsd
	-- left outer join LosVrRegistartionSubmission rs on rsd.RegistartionSubId=rs.RegistartionSubId and rsd.regsubShopid=rs.regsubShopid
	-- left outer join losHpItemRegistrationDetails on rsd.CompanyId=IRRegistrationID and rsd.CompanyId=IRCompanyID
	-- inner join losHPCustomerDetails c on IRCustomerID = c.hpCustID where rsd.CompanyId = @companyid
END
if @strModule=''DELRQ''
begin
	select * from
	(
		select poshBillNo, poshBillDate,posdShopID,posdBillID  PosId, 0 InvoiceId,posdItemID itemid ,''POS'' TType
		from losposdetail A
			left outer join losposheader B  on B.poshShopID=A.posdShopID and B.poshBillID=A.posdBillID and  B.poshCompanyID=@companyid
		where posdShopID=@intshopid  and  posdBillID not in
		(
			select ISNULL(posid,0) from LosVrRegistartionDeliveryReqdetail  A
			left outer join LosVrRegistartionDeliveryReq B on A.RegistartionDeliveryReqId=B.RegistartionDeliveryReqId
			where deleted=0
		)
		
		union all
		
		select ihInvoiceNo,ihInvoiceDate,idShopID,0 PosId,idInvoiceID InvoiceId,idItemID itemid ,''INV'' TType
		from losinvoicedetail A
			left outer join losinvoiceheader B on B.ihShopID=A.idShopID and B.ihInvoiceID=A.idInvoiceID and  B.ihCompanyID=@companyid
		where idShopID=@intshopid and idInvoiceID not in
		(
			select ISNULL(InvoiceId,0) from LosVrRegistartionDeliveryReqdetail A
				left outer join LosVrRegistartionDeliveryReq B on A.RegistartionDeliveryReqId=B.RegistartionDeliveryReqId
			where deleted=0
		)
	)v
	left outer join losHpItemRegistrationDetails C on  C.IRItemID=v.itemid and
		(IrInterfaceID=1502 and IRTransactionID=PosId) or (IrInterfaceID=1504 and IRTransactionID=InvoiceId)
	left outer join [LosVrRegistartionReceiveDetail] lr on lr.[RegistrationID]=IRRegistrationId
	left outer join [LosVrRegistartionReceive] lh on shopid= @intshopid and lr.RegistartionReceiveId=lh.RegistartionReceiveId
	left outer join acolor ac on IRColorID=colorid
	inner join aitem  D on D.itemid=C.irItemID and D.HirePurchase=1 and lh.deleted = 0
END
if @strModule=''DELCON''
begin
--select IRRegistrationID,rdr.RegistartionDeliveryReqId,rdr.PosId,IREngineNo,RegistryNoLong IRRegistrationNo,IRFrameNo,
--case when rwrd.RoadWorthnessNo is not null then rwrd.RoadWorthnessNo else ''''end
--IRRoadWorthiness,IRModelNo ,ColorName
--from  LosVrRegistartionDeliveryReqDetail rdr
--left outer join LosVrRegistartionDeliveryReq rdh
--on rdh.RegistartionDeliveryReqId = rdr.RegistartionDeliveryReqId
--left outer join  losHpItemRegistrationDetails
--on IRRegistrationID = registrationid
--inner join aColor on IRColorID = ColorID
--left outer join LosVrRegistartionReceiveDetail rrd
--on rrd.RegistartionReceiveId = rdr.RegistartionReceiveId
--left outer join LosVrRoadWorthnessReceiptDetail rwrd on rwrd.RegistrationID = rdr.RegistrationID
--and  rwrd.PosId = rdr.PosId left outer join LosVrRoadWorthnessReceipt rwr
--on  rwr.RoadWorthnessRecptId =rwrd.RoadWorthnessRecptId
--where  IRRegistrationID not in (select registrationid
--from losvrdeliveryconfdetail d left outer join losvrdeliveryconf h on
--d.DeliveryConfId = h.DeliveryConfId where h.Deleted =0 ) and rdr.companyid =  @companyid
--and  rdh.deleted = 0 and rwr.deleted = 0
	select IRRegistrationID,rdr.RegistartionDeliveryReqId,rdr.PosId,IREngineNo,RegistryNoLong IRRegistrationNo,
		IRFrameNo,case when rwrd.RoadWorthnessNo is not null then rwrd.RoadWorthnessNo else ''''end IRRoadWorthiness,
		IRModelNo ,ColorName
	from LosVrRegistartionDeliveryReqDetail rdr
		left outer join LosVrRegistartionDeliveryReq rdh on rdh.RegistartionDeliveryReqId = rdr.RegistartionDeliveryReqId
		left outer join  losHpItemRegistrationDetails on IRRegistrationID = registrationid
		LEFT OUTER join losposheader on poshBillID = rdr.posid and poshShopID = rdh.shopid
		left outer join losinvoiceheader Inv on rdr.invoiceid=ihInvoiceID and rdh.Shopid= ihShopID
		left outer join losspecialinvoiceheader sInv on rdr.spinvoice=sInv.IhInvoiceID and rdh.Shopid=sInv.IhShopID
		left outer join aColor on IRColorID = ColorID
		left outer join LosVrRegistartionReceiveDetail rrd on rrd.RegistartionReceiveId = rdr.RegistartionReceiveId  and rdr.PosId =rrd.PosId
		--left outer join LosVrRegistartionReceive lrr on lrr.RegistartionReceiveId = rrd.RegistartionReceiveId and rdr.PosId =rrd.
		left outer join LosVrRoadWorthnessReceiptDetail rwrd on rwrd.RegistrationID = rdr.RegistrationID and  rwrd.PosId = rdr.PosId
		left outer join LosVrRoadWorthnessReceipt rwr on  rwr.RoadWorthnessRecptId =rwrd.RoadWorthnessRecptId
	where  IRRegistrationID not in
	(
		select isnull(registrationid,0) from losvrdeliveryconfdetail d
			left outer join losvrdeliveryconf h on d.DeliveryConfId = h.DeliveryConfId where h.Deleted =0
	) and rdr.companyid =  @Companyid and  rdh.deleted = 0 and rwr.deleted = 0 --and lrr.deleted = 0
END
if @strModule=''RegistrationSubmition''
begin
	select Roadworthnessno IRRoadWorthiness,A.*,ird.*,c.CustomerName CustomerName,NICNO
	from LosVrRoadWorthnessReceiptDetail A
		--left outer join LosVrRoadWorthnessReceiptDetail B on A.RegistrationID=B.RegistrationID
		left outer join LosVrRoadWorthnessReceipt rrh on rrh.RoadWorthnessRecptId=A.RoadWorthnessRecptId
		left outer join losHpItemRegistrationDetails ird on ird.IRRegistrationID=A.RegistrationID
		inner join losposheader ph on ph.poshBillID = ird.IRTransactionID and ph.poshShopID=rrh.ShopId
		left outer join losinvoiceheader Inv on A.invoiceid=ihInvoiceID and rrh.Shopid= ihShopID
		left outer join losspecialinvoiceheader sInv on A.spinvoice=sInv.IhInvoiceID and rrh.Shopid=sInv.IhShopID
		inner join   acustomermaster c on customerid = ph.poshcustomerid
	where rrh.ShopId = @intShopid and rrh.CompanyId=@Companyid and rrh.deleted = 0 and
		ird.IRRegistrationID not in
		(
			select isnull(RegistrationID,0) from LosVrRegistartionSubmissionDetail rsd
				left outer join LosVrRegistartionSubmission rs on rs.RegistartionSubId = rsd.RegistartionSubId
			where rs.Deleted = 0
		)
end
else
if @strModule=''RegistrationReceived''
begin
	select A.*,IRD.*,c.CustomerName CustomerName,c.Address1 CustomerAddress
	from LosVrRegistartionSubmissionConfDetail A
		--left outer join LosVrRegistartionSubmissionConfDetail B on B.RegistartionSubConfId=A.RegistartionSubConfId
		left outer join LosVrRegistartionSubmissionConf rsc on rsc.RegistartionSubConfId=A.RegistartionSubConfId
		left outer join losHpItemRegistrationDetails IRD on ird.IRRegistrationID=A.RegistrationID
		left outer join losposheader ph on ph.poshBillID = ird.IRTransactionID and ph.poshShopID=rsc.ShopId
		left outer join losinvoiceheader Inv on A.invoiceid=ihInvoiceID and rsc.Shopid= ihShopID
		left outer join losspecialinvoiceheader sInv on A.spinvoice=sInv.IhInvoiceID and rsc.Shopid=sInv.IhShopID
		left outer join   acustomermaster c on c.customerid = ph.poshcustomerid
	where rsc.CompanyId = @Companyid  and rsc.shopid=@intShopid and rsc.deleted = 0 and
	ird.IRRegistrationID not in
	(
		select isnull(RegistrationID,0) from LosVrRegistartionReceiveDetail rrd
			left outer join LosVrRegistartionReceive rr on rrd.RegistartionReceiveId = rr.RegistartionReceiveId
		where rr.Deleted = 0
	)
end' 
END
GO
/****** Object:  View [dbo].[VwCashDrawer]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwCashDrawer]'))
EXEC dbo.sp_executesql @statement = N'
Create view [dbo].[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
/****** Object:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_SaveDeliveryVerificationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:  Regin T.
-- Create date: 15-07-2010
-- Description:
--   To save Delivery Verification Details
-- =============================================================================
CREATE PROC [dbo].[spMag_SaveDeliveryVerificationDetails]
-- Add the parameters of the stored procedure here
@CompanyId int,
@ShopId int,
@DeliveryVerificationId int,
@Slno  int,
@BillId int = null,
@InvoiceId int = null,
@ItemId int,
@PackId int,
@PackQty numeric(18,3),
@FinancialYearId int
AS
BEGIN
DECLARE @Qty AS NUMERIC(18,3)
-- Calculate Qty from PackQty
SELECT @Qty = @PackQty * pc.Quantity
FROM aPackingTypeCapacityDetail pc
INNER JOIN aItem i ON pc.UnitsID=i.UnitsID
WHERE ItemId=@ItemId and PackingTypeID=@PackId
INSERT INTO [dbo].[losDeliveryVerificationDetails]
([CompanyId]
,[ShopId]
,[DeliveryVerificationId]
,[SlNo]
,[BillId]
,[InvoiceId]
,[ItemId]
,[PackId]
,[PackQty]
,[Qty]
,[FinancialYearId]
)
VALUES
(@CompanyId
,@ShopId
,@DeliveryVerificationId
,@Slno
,@BillId
,@InvoiceId
,@ItemId
,@PackId
,@PackQty
,@Qty
,@FinancialYearId
)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLCRegisterAllDetailsOld]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLCRegisterAllDetailsOld]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY: NIDHEESH PV
--CREATED ON: 19/10/2010
--COMMENTS: TO GET ALL DETAILS OF LC REGISTER
--spLCRegisterAllDetails 1,0,0,0,''20070101'',''20101001'',''N''
CREATE proc [dbo].[spLCRegisterAllDetailsOld]
@intCompanyID as int,
@intDepartmentID as int,
@intVendorID as int,
@intAccountID as int,
@strFromDate as varchar(12),
@strToDate as varchar(12),
@strType as char(1)=''D''--If passing ''N'' date Range will not be considered
as
begin
set nocount on
select PO.*,LCPay.phpaymentid,LCPay.pddhqpoid,LCPay.phPaymentDate,
isnull(LCPay.Margin,0)Margin,isnull(LCPay.LCSettled,0)LCSettled,isnull(LCPay.LCSettledvendoreqi,0)LCSettledvendoreqi
from
(
select
pohPoid,pohDepartmentid,pohcompanyid,pohVendorID,DepartmentName,VendorName,
pohpono,pohPodate,pohvalue,
pohlcnumber,pohlcamount,pohLCAccountid,AccountDesc,pohlcdueon,pohlcremarks,
Vcurr.CurrencyID[VCurrID],Vcurr.Symbol[VCurr],LCcurr.CurrencyID[LCCurrID],LCcurr.Symbol[LCCurr]
from loPurchaseOrderHeader po inner join aaccountmaster am
on po.pohLCAccountid = am.AccountID  and po.pohcompanyid = am.CompanyID
and po.pohtype = ''p''  and po.pohlcopened = 1  and po.pohcancel = 0
inner join avendormaster v on vendorid=pohVendorID
inner join adepartmentmaster on departmentid=pohDepartmentid
inner join acurrencymaster Vcurr on Vcurr.CurrencyID=v.currencyid
inner join acurrencymaster LCcurr on LCcurr.CurrencyID=am.currencyid
where pohcompanyid=@intCompanyID and (pohDepartmentid=@intDepartmentID or @intDepartmentID=0)
and (pohLCAccountid=@intAccountID or @intAccountID=0) and (pohVendorID=@intVendorID or @intVendorID=0)
and ((pohPodate>=@strFromDate and pohPodate<=@strToDate and @strType=''D'') or (pohPodate<=@strToDate and @strType=''N''))
)PO
left outer join
(
select
phpaymentid,pddhqpoid,phdepartmentid,phcompanyid,phPaymentDate,
case when phlcpayment=''LCM'' then sum(isnull(pddAccountAmount,0)- isnull(pddVendorExchangeDifference,0))over (partition by pddhqpoid,phdepartmentid,phcompanyid,phPaymentDate,phlcpayment) end Margin,  ---To get LC Margin amount(phlcpayment=''LCM'' only)
sum(isnull(pddAccountAmount,0) - IsNull(pddVendorExchangeDifference, 0)) over (partition by pddhqpoid,phdepartmentid,phcompanyid,phPaymentDate) as LCSettled,  ---To get total settled LC amount(both phlcpayment=''LCM'' OR phlcpayment=''LCO'')
sum(isnull(pddcustomeramount,0)) over (partition by pddhqpoid,phdepartmentid,phcompanyid,phPaymentDate)as LCSettledvendoreqi  ---To get Cust. Equi. of total settled LC amount(both phlcpayment=''LCM'' OR phlcpayment=''LCO'')
from ahqpaymentvoucherdebitdetails, ahqpaymentvoucherheader
where
pddcompanyid=phcompanyid and pddpaymentid=phpaymentid and (phlcpayment=''LCM'' OR phlcpayment=''LCO'')
and phcancelled=0
)LCPay
on PO.pohPoid=LCPay.pddhqpoid and PO.pohDepartmentid=LCPay.phdepartmentid and PO.pohcompanyid=LCPay.phcompanyid
where phpaymentid is null or Margin is not null--to avoid LCO type, but already find total amount settled in LCSettled
set nocount off
end
-----------------------------------------' 
END
GO
/****** Object:  View [dbo].[VwCommisionInvDetails]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwCommisionInvDetails]'))
EXEC dbo.sp_executesql @statement = N'
--created by 	:	dheena, Hariharan , Hariharan
--created date :	11/11/2003, 27/11/2003, 17/01/2004
--purpose :Collect all Clearencerequest and Purchase order
--Hints - if type P ---> Purchase Order else R--->Clearence request
--		: Modified the view to avoid avendormasterr
CREATE view [dbo].[VwCommisionInvDetails] as
/* select '''' Reqid,b.PONo ProcessNO,
ltrim(rtrim(c.VendorName))+space(2)+b.PONo+space(2)+cast(b.podate as
varchar) descr,
sum(Amount) amt,0.00 OCAamount ,''Purchase Order'' SerDesc,''P'' Type,
b.POID,bndShopId,bndboatnoteId,cast (b.CashPaidByShop as int) cashpaid
from losshipmentBndetail left outer join loslpdetail a
on bndlppoid=a.POID and bndShopId=a.shopid
and bndlpdetailid=DetailID,loslpheader b,avendormaster c where
a.POID=b.POID and b.vendorid=c.vendorid and a.shopid=b.shopid
and bndShopId=a.shopid group by b.POID,b.PONo,b.PONo,b.podate,
c.VendorName,bndShopId,bndboatnoteId,cast(b.CashPaidByShop as int)
union all
select c.ClearenceReqID,c.ClearenceReqNo ,ltrim(rtrim(VendorName))
+ space(2)+PONo+space(2)+cast(podate as varchar),sum(amount) ,
max(isnull(ocamt,0)) ,''Clearence Request'',''R'','''',bndShopId,bndboatnoteId,''''
from losshipmentBndetail  left outer join ShipmentClearencerequestdetails b on
bndclearanceId=b.ClearenceID  and bndShopId=b.shopid and bnddetailId=b.DetailID
left outer join (select Clearenceid, shopid, ClearenceReqId, sum(isnull(OcAmt,0)) ocAmt
from  ShipmentClearenceOCDetails group by Clearenceid, shopid, ClearenceReqId) e on
b.ClearenceReqID=e.ClearenceReqID and b.ShopID=e.ShopID
,ClearenceRequestHeader c , ShipmentClearenceItemDetails d
where bndShopId=b.ShopId  and bndclearanceId is not
null  and b.ShopId=c.shopid and b.ClearenceReqID=c.ClearenceReqID
and d.ClearenceID=bndclearanceId and d.ShopID=c.ShopID
group by b.ClearenceID, c.ClearenceReqID, c.ClearenceReqNo,
VendorName,PONo,podate,bndShopId,bndboatnoteId */
--created by  : dheena, Hariharan
--created date : 11/11/2003, 27/11/2003
--purpose :Collect all Clearencerequest and Purchase order
--Hints - if type P ---> Purchase Order else R--->Clearence request
-- modofed by dheena add one more field name pono
select '''' Reqid,b.PONo ProcessNO,
ltrim(rtrim(lcr.VendorName))+space(2)+b.PONo+space(2)+cast(b.podate as
varchar) descr, sum(Amount) amt,0.00 OCAamount ,''Purchase Order''
SerDesc,''P'' Type,
b.POID,bndShopId,bndboatnoteId,cast (b.CashPaidByShop as int) cashpaid,
lcr.pono clearencepono
from
losshipmentBndetail
left outer join loslpdetail a on bndlppoid=a.POID and bndShopId=a.shopid
and bndlpdetailid=DetailID,loslpheader b,
losLocalClearenceRequestheader lcr
where a.POID=b.POID and a.shopid=b.shopid
and bndShopId=a.shopid and b.shopid=lcr.shopid
and b.ClearenceReqID = lcr.ClearenceReqID
group by b.POID,b.PONo,b.PONo,b.podate,lcr.VendorName,bndShopId,
bndboatnoteId,cast(b.CashPaidByShop as int),lcr.pono
union all
select c.ClearenceReqID,c.ClearenceReqNo ,ltrim(rtrim(VendorName))
+ space(2)+PONo+space(2)+cast(podate as varchar),sum(amount) ,
max(isnull(ocamt,0)) ,''Clearence
Request'',''R'','''',bndShopId,bndboatnoteId,'''',c.pono
from
losshipmentBndetail  left outer join ShipmentClearencerequestdetails b on
bndclearanceId=b.ClearenceID  and bndShopId=b.shopid  and
bnddetailId=b.DetailID
left outer join (select
Clearenceid, shopid, ClearenceReqId,
sum(isnull(OcAmt,0)) ocAmt
from  ShipmentClearenceOCDetails group by Clearenceid,
shopid, ClearenceReqId) e on
b.ClearenceReqID=e.ClearenceReqID and b.ShopID=e.ShopID
,ClearenceRequestHeader c , ShipmentClearenceItemDetails d
where bndShopId=b.ShopId  and bndclearanceId is not
null  and b.ShopId=c.shopid and b.ClearenceReqID=c.ClearenceReqID
and d.ClearenceID=bndclearanceId and d.ShopID=c.ShopID
group by b.ClearenceID, c.ClearenceReqID, c.ClearenceReqNo,
VendorName,PONo,podate,bndShopId,bndboatnoteId'
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff_BACKUP24022012]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spaccountsarriveexdiff_BACKUP24022012]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Create on  : 05/12/2002
-- Create by  : leo
-- Last MOdified on : 14/04/2003, 17/11/2003
-- Modified by  : leo, Hariharan R
-- all the entries has to be posted to accounts before doing this procedure
-- Included the code for removing the controll accounts
--Modified to consider dep wise and company currrency wise and corrected
-- difference amount picking
--------------------------------------------------------------------------------------
-- Modified By :-Benzigar S D
-- Modified On :-28/07/2009
-- Comment     :-Previously spopeningbalance is used to tale Opening Balance.
--               Now spopeningbalance_Adjustment is used for this.
--               In spopeningbalance journaldate-1 is taking.
--               But here in adjustmentjournaldate is needed
--------------------------------------------------------------------------------------
CREATE proc [dbo].[spaccountsarriveexdiff_BACKUP24022012] @intcompanyid as int, @strexrates as varchar(250),
@strcurdate as varchar(10),@intDepartmentID as int, @Depwise char(1) =''d'',
@filtergroup as int = 0   as
begin
set nocount on
declare @intcount as int,
@intaccid as int,
@numDepbal as numeric(18,2),
@numresbal as numeric(18,2),
@numconsbal as numeric(18,2),
@straccdesc as varchar(250),
@intDepCurrID as int,
@intAccCurrID as int,
@intConsCurrID as int,
@numdepamount as numeric(18,2),
@numConsamount as numeric(18,2),
@straccounttype as char(1),
@bitjournalcredit as bit,
@numdiffamt as numeric(18,2)
create table #temp1(
companyid int,
accountid int,
accountdesc varchar(250),
CurrencyID int,
type char(1)
)
create table #temp2(
companyid int,
accountid int,
accountdesc varchar(250),
DepBalance numeric(18,2),
consbalance numeric(18,2),
resbalance numeric(18,2),
depamount  numeric(18,2),
consamount  numeric(18,2),
journalcredit bit
)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the account heads other than company currency are taken into the temp table
if @Depwise =''d''
Begin
insert into #temp1
select
a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from
aaccountmaster a, adeptaccounts d, agroupmaster g
where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =
d.dacompanyid and a.accountid = d.daaccountid and a.companyid
=@intcompanyid and a.currencyid <> @intDepCurrID  and d.dadepartmentid =
@intdepartmentid
end
else
Begin
insert into #temp1
select
a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from
aaccountmaster a, adeptaccounts d, agroupmaster g
where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =
d.dacompanyid and a.accountid = d.daaccountid and a.companyid
=@intcompanyid and a.currencyid <> @intConsCurrID  and d.dadepartmentid =
@intdepartmentid
End
delete from #temp1 where companyid = @intcompanyid and accountid in (
select distinct debtoraccid from acustomermaster)
delete from #temp1 where companyid = @intcompanyid and accountid in (
select distinct creditoraccid from avendormaster)
if @filtergroup >0
delete #temp1 from agroupmaster g, aaccountmaster m where #temp1.accountid = m.accountid
and m.groupid = g.groupid and g.groupid not in (@filtergroup)
select @intcount = count(*) from #temp1
while @intcount <> 0
begin -- for while
select @intaccid = accountid, @straccdesc = accountdesc, @intAccCurrID=CurrencyID,
@straccounttype = type from #temp1
set @numDepbal =0.0
if @Depwise =''d''
Begin
--exec spopeningbalance @strcurdate, @intaccid, @intcompanyid,''dr'', @numDepbal output, @intDepartmentID
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''dr'', @numDepbal output, @intDepartmentID
End
else
Begin
--exec spopeningbalance @strcurdate, @intaccid, @intcompanyid,''cr'', @numDepbal output, @intDepartmentID
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''cr'', @numDepbal output, @intDepartmentID
End
set @numresbal =0.0
--exec spopeningbalance @strcurdate, @intaccid, @intcompanyid,''ar'', @numresbal output, @intDepartmentID
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''ar'', @numresbal output, @intDepartmentID
if @Depwise =''d''
Begin
exec spConvertequiamount @intAccCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
End
else
Begin
exec spConvertequiamount @intAccCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
End
if abs(@numDepbal - (@numdepamount)) >= 1 -- this has the exchange difference
begin
if ((@numdepamount > @numDepbal) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =0
if ((@numdepamount < @numDepbal) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =1
if ((@numdepamount > @numDepbal) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =1
if ((@numdepamount < @numDepbal) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =0
set @numdiffamt  = abs(@numdepamount - @numDepbal)
if @Depwise =''d''
Begin
exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc,
@numDepbal, @numConsbal,@numresbal,@numdepamount, @numConsamount, @bitjournalcredit)
ENd
else
Begin
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc, @numDepbal,
@numConsbal,@numresbal,@numConsamount , @numdepamount, @bitjournalcredit)
End
end
-- select * from #temp1
delete from #temp1 where accountid = @intaccid
select @intcount = count(*) from #temp1
end -- for while
select * from #temp2 order by accountdesc asc
set nocount off
end
-------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spaccountsarriveexdiff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Create by  : leo
-- Last MOdified on : 14/04/2003, 17/11/2003
-- Modified by  : leo, Hariharan R
-- all the entries has to be posted to accounts before doing this procedure
-- Included the code for removing the controll accounts
--Modified to consider dep wise and company currrency wise and corrected
-- difference amount picking
--------------------------------------------------------------------------------------
-- Modified By :-Benzigar S D
-- Modified On :-28/07/2009
-- Comment     :-Previously spopeningbalance is used to tale Opening Balance.
--               Now spopeningbalance_Adjustment is used for this.
--               In spopeningbalance journaldate-1 is taking.
--               But here in adjustmentjournaldate is needed
/*
Ref No		: 01
Modified By : SHINE DAS
Modified On : 23.02.2012
Client		: SIMDI
*/
/*
Ref No		: 02
Modified By : SHINE DAS
Modified On : 07.05.2012
Client		: SIMDI
Purpose		: Jomin reported that department wise TB is not tallying after this update.
So made corrections.
*/
--------------------------------------------------------------------------------------
CREATE proc [dbo].[spaccountsarriveexdiff] @intcompanyid as int, @strexrates as varchar(250),
@strcurdate as varchar(10),@intDepartmentID as int, @Depwise char(1) =''d'',
@filtergroup as int = 0   as
begin
set nocount on
declare @intcount as int,
@intaccid as int,
@numDepbal as numeric(18,2),
@numresbal as numeric(18,2),
@numconsbal as numeric(18,2),
@straccdesc as varchar(250),
@intDepCurrID as int,
@intAccCurrID as int,
@intConsCurrID as int,
@numdepamount as numeric(18,2),
@numConsamount as numeric(18,2),
@numresamountinConsCurr as numeric(18,2),   -- Ref No : 01
@straccounttype as char(1),
@bitjournalcredit as bit,
@numdiffamt as numeric(18,2)
create table #temp1(
companyid int,
accountid int,
accountdesc varchar(250),
CurrencyID int,
type char(1)
)
create table #temp2(
companyid int,
accountid int,
accountdesc varchar(250),
DepBalance numeric(18,2),
consbalance numeric(18,2),
resbalance numeric(18,2),
depamount  numeric(18,2),
consamount  numeric(18,2),      -- Ref No : 01
resamountinConsCurr  numeric(18,2), ---- Ref No : 01
journalcredit bit
)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the account heads other than company currency are taken into the temp table
if @Depwise =''d''
Begin
insert into #temp1
select
a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from
aaccountmaster a, adeptaccounts d, agroupmaster g
where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =
d.dacompanyid and a.accountid = d.daaccountid and a.companyid
=@intcompanyid and a.currencyid <> @intDepCurrID  and d.dadepartmentid =
@intdepartmentid
end
else
Begin
insert into #temp1
select
-- Ref No	: 02 Commented
--a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from
--aaccountmaster a, adeptaccounts d, agroupmaster g
--where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =
--d.dacompanyid and a.accountid = d.daaccountid and a.companyid
--=@intcompanyid and a.currencyid <> @intConsCurrID  and d.dadepartmentid =
--@intdepartmentid
-- Ref No	: 02 Added
a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from
aaccountmaster a, adeptaccounts d, agroupmaster g
where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =
d.dacompanyid and a.accountid = d.daaccountid and a.companyid
=@intcompanyid  and d.dadepartmentid = @intdepartmentid
End
-- Ref No	: 02 Commented
--delete from #temp1 where companyid = @intcompanyid and accountid in (
--select distinct debtoraccid from acustomermaster)
-- Ref No	: 02 Commented
--delete from #temp1 where companyid = @intcompanyid and accountid in (
--select distinct creditoraccid from avendormaster)
if @filtergroup >0
delete #temp1 from agroupmaster g, aaccountmaster m where #temp1.accountid = m.accountid
and m.groupid = g.groupid and g.groupid not in (@filtergroup)
select @intcount = count(*) from #temp1
while @intcount <> 0
begin -- for while
select @intaccid = accountid, @straccdesc = accountdesc, @intAccCurrID=CurrencyID,
@straccounttype = type from #temp1
set @numDepbal =0.0
-- Ref No : 01 ----------start
/* SEEMS UNECESSARY
if @Depwise =''d''
Begin
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''dr'', @numDepbal output, @intDepartmentID
End
else
Begin
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''cr'', @numDepbal output, @intDepartmentID
End
*/
----- Ref No : 01 End
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''dr'', @numDepbal output, @intDepartmentID
-- Ref No : 01 Start
-- IN OLD CODE SNIPPET IT WAS USED WRONG VARIABLE  @numDepbal to TO FIND BALANCE IN COMPANY CURR.
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''cr'', @numconsbal output, @intDepartmentID    ---shine
-- Ref No : 01 End
set @numresbal =0.0
exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,''ar'', @numresbal output, @intDepartmentID
-- Ref No : 01 ----------start
/* SEEMS UNECESSARY
----if @Depwise =''d''
---- Begin
----  exec spConvertequiamount @intAccCurrID, ''m'', @intDepCurrID,
----   ''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
---- End
----else
----Begin
---- exec spConvertequiamount @intAccCurrID, ''m'', @intConsCurrID,
----  ''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
---- End
--exec spConvertequiamount @intAccCurrID, ''m'', @intDepCurrID,
-- ''m'', @strexrates , @numDepbal, @numdepamount output,  ''r''
*/
----- Ref No : 01 End
exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numDepbal, @numdepamount output,  ''r''
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates ,@numconsbal , @numConsamount output,  ''r''
-- Ref No : 01 ----------start
exec spConvertequiamount @intAccCurrID, ''m'', @intConsCurrID,
''m'', @strexrates ,@numresbal , @numresamountinConsCurr output,  ''r''
----- Ref No : 01 End
-- Ref No	: 02 Commented Below start
----   if abs(@numconsbal - (@numdepamount)) >= 1 -- this has the exchange difference
----begin
---- if ((@numconsbal > @numdepamount))
----  set @bitjournalcredit = 0
---- if ((@numconsbal < @numdepamount))
----  set @bitjournalcredit =1
-- Ref No	: 02 Commented End
-- Ref No	: 02 Added Below start
if abs(@numconsbal - (@numdepamount)) >= 1 -- this has the exchange difference
BEGIN
if ((@numconsbal > @numdepamount) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =0
if ((@numconsbal < @numdepamount) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =1
if ((@numconsbal > @numdepamount) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =1
if ((@numconsbal < @numdepamount) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =0
---           Ref No	: 02 end
/*
if abs(@numresbal - (@numConsamount)) >= 1 -- this has the exchange difference
BEGIN
if ((@numConsamount > @numresamountinConsCurr) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =0
if ((@numConsamount < @numresamountinConsCurr) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =1
if ((@numConsamount > @numresamountinConsCurr) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =1
if ((@numConsamount < @numresamountinConsCurr) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =0
*/
set @numdiffamt  = abs(@numconsbal - @numdepamount)
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
-- Ref No : 01 ----------start
/* SEEMS UNECESSARY
--exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
-- ''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
*/
----- Ref No : 01 End
insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc, @numDepbal,
@numConsbal,@numresbal,@numConsamount, @numdiffamt,@numresamountinConsCurr, @bitjournalcredit)
END
-- Ref No : 01 ----------start Commented and new snippet added above
/*
if abs(@numDepbal - (@numdepamount)) >= 1 -- this has the exchange difference
begin
if ((@numdepamount > @numDepbal) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =0
if ((@numdepamount < @numDepbal) and (@straccounttype =''a'' or @straccounttype =''e''))
set @bitjournalcredit =1
if ((@numdepamount > @numDepbal) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =1
if ((@numdepamount < @numDepbal) and (@straccounttype =''l'' or @straccounttype =''i''))
set @bitjournalcredit =0
set @numdiffamt  = abs(@numdepamount - @numDepbal)
if @Depwise =''d''
Begin
exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc,
@numDepbal, @numConsbal,@numresbal,@numdepamount, @numConsamount, @bitjournalcredit)
ENd
else
Begin
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc, @numDepbal,
@numConsbal,@numresbal,@numConsamount , @numdepamount, @bitjournalcredit)
End
end
----- Ref No : 01 End
*/
-- select * from #temp1
delete from #temp1 where accountid = @intaccid
select @intcount = count(*) from #temp1
end -- for while
select * from #temp2 order by accountdesc asc
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceconscheck]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceconscheck]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spBalanceconscheck] @strDate as varchar(8), @intGroupId as int, @intdep as int =0
as
Set nocount on
Begin
	Declare @intAccCount as int
	Declare @intDepCount as int
	Declare @numDepBalSum as numeric(18,2)
	Declare @numDepBal as numeric(18,2)
	Declare @numAccBal as numeric(18,2)
	Declare @intAcId as int
	Declare @intDepId as int
Create table #acc(acid int, acbal numeric(18,2), acbalsum numeric(18,2), acStatus int)
Create table #dep(depid int)
insert #acc
select  AccountId, 0, 0, 0 from aaccountmaster where groupid = @intGroupId
Select @intAccCount = count(*) from #acc where acstatus = 0
while @intAccCount <>0
Begin
	Select top 1 @intAcId =  acid  from #acc where acstatus = 0
	set @numAccBal = 0.0
	if @intdep <>0
	Begin
		insert #dep
		select Departmentid from aDepartmentMaster where departmentid = @intdep		
	End
	else
	Begin
		insert #dep
		select Departmentid from aDepartmentMaster
	End
	Select @intDepCount = count(*) from #dep
	set @numDepBalSum = 0	
	while @intDepCount <>0
	Begin
		Select top 1 @intDepId = depid from #dep
		set @numDepBal = 0.0
		exec spopeningbalance @strDate, @intAcid, 1, ''c'', @numDepBal output, @intDepId, 0
		set @numDepBalSum  = @numDepBalSum + isnull(@numDepBal,0)
		Delete from #dep where depId = @intDepId
		Select @intDepCount = count(*) from #dep	
	End
	exec spopeningbalance @strDate, @intAcid, 1, ''c'', @numAccBal output, 0, 0
	Update #acc set acbal = isnull(@numAccBal,0), acbalsum = isnull(@numDepBalSum,0) ,
	acStatus =1 where AcId = @intAcId
	Select @intAccCount = count(*) from #acc where acstatus = 0
End
Select * from #acc
drop table #dep
End
Set noCount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAgreement]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAgreement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------
-- Created on 	: 22/08/2003
-- Created by 	: R Harikrishnan
-- Comments	: For Agreement Transaction Report
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spAgreement]
	@intCompanyID 	AS INT,
	@intShopID 	AS INT,
	@intAgreementID AS INT
AS
BEGIN
	DECLARE @strDepCurrSymbol AS VARCHAR(25)
	SELECT
		@strDepCurrSymbol=ISNULL(cm.Symbol,'''')
	FROM
		aShops sm,aDepartmentMaster dm,aCurrencyMaster cm
	WHERE 	
		sm.CompanyID = dm.CompanyID and sm.DepartmentID=dm.DepartmentID and
		dm.CompanyID=cm.CompanyID and dm.depCurrencyID=cm.CurrencyID and
		sm.CompanyID=@intCompanyID and sm.ShopID=@intShopID
	SELECT
		agh.mghAgreementno, agh.mghAgreementDate, agh.mghcontactpersonname,
		agh.mghcontactphoneno, 	agh.mghleaseendingdate, agh.mghleasecommencingdate,
		agh.mghrentlastdate, agh.mghelectricityreadingstart, agh.mghelectricityreadingend,
		agh.mghwaterreadingstart, agh.mghwaterreadingend, agh.mghsecurittyamount, agh.mghdiscount,
		CASE WHEN agh.mghmodeofpayment=''C'' THEN ''Cash'' WHEN agh.mghmodeofpayment=''H'' THEN ''Cheque''
		ELSE ''Others'' END PaymentType, 	agh.mghRemarks, agh.mghChequeNo, agh.mghChequeDate,
		agd.mgdPersonName, agd.mgdcheckintime, agd.mgdcheckouttime, agd.mgdPassPortNo,
		agd.mgdWorkPermitVisaNo, agd.mgdPPExpiryDate, agd.mgdVisaExpiryDate,
		agd.mgdstatus, agd.mgdremarks, sm.sperName Incharge, am.AccountDesc CashAccount,
		ad.apdapartmentno,rh.rhReserVationNo,cm.CustomerName,curr.Symbol,
		agh.mghApartmentRate rdApartmentRate,rtd.sername RateType,@strDepCurrSymbol DepCurrSymbol
	FROM
		losApartmentAgreementHeader agh	LEFT OUTER JOIN aSalesPersonMaster sm
		ON agh.mghApartmentIncharge=sm.Sperid and agh.mghCompanyID=sm.CompanyID,
		aAccountMaster am,losApartmentAgreementDetails agd, losApartmentDetail ad,
		losReservationHeader rh,aCustomerMaster cm, aCurrencyMaster curr,
		(select
			ad.apdcompanyid,ad.apdShopid,ad.apdapartmentid,
			rd.rdroomratedetailid,rd.rdApartmentRate,sm.sername
		from
			losApartmentDetail ad,losApartmentRatesDetail rd,aServiceMaster sm
		Where
			ad.apdcompanyid=rd.rdcompanyid and ad.apdShopid=rd.rdshopid and
			ad.apdapartmentcategoryid=rd.rdapartmentcategoryid and 	
			rd.rdcompanyid=sm.sercompanyid and rd.rdRoomRateTypeId=sm.serid and
			ad.apdCompanyID=@intCompanyID and ad.apdShopID=@intShopID and
			sm.serservicetype=''R'')rtd
	WHERE
		agh.mghCompanyID = am.CompanyID and agh.mghAccountId = am.AccountID and
		agh.mghCompanyId=agd.mgdCompanyId and agh.mghShopId=agd.mgdShopId and
		agh.mghAgreementid=agd.mgdAgreementid and agh.mghCompanyID=ad.apdcompanyid and
		agh.mghShopId=ad.apdShopid and agh.mghApartmentId =ad.apdApartmentid and
		agh.mghCompanyId=rh.rhCompanyID and agh.mghShopId=rh.rhShopID and
		agh.mghReservationID=rh.rhReservationID and rh.rhCompanyID = cm.CompanyID and
		rh.rhCustomerID = cm.CustomerID and agh.mghCompanyId=@intCompanyID and
		am.CompanyID= curr.CompanyID and am.CurrencyID=curr.CurrencyID and
		agh.mghCompanyID=rtd.apdcompanyid and agh.mghShopId=rtd.apdShopid and
		agh.mghApartmentID=rtd.apdapartmentid and agh.mghRateDetailId=rtd.rdroomratedetailid and
		agh.mghShopId=@intShopID and agh.mghAgreementid=@intAgreementID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGenPrefix]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGenPrefix]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE proc   [dbo].[spGenPrefix] @interfaceid as int,@intShopID int  as
Declare @intnextMaxno as int,
@intMaxno as varchar(50),
@strPrefix as varchar(50),
@strPrefix1 as varchar(50)
if @interfaceid<>0 and @intShopID<>0
Begin
SELECT @strPrefix=Prefix FROM aPrefix WHERE
InterfaceID = @interfaceid and
shopid=@intShopID
end
if @strPrefix<>''''
Begin
set @strPrefix1= @strPrefix +''%''
Select @intnextMaxno=isnull(max(convert(int,right(poshBillNo,
len(poshBillNo)-Len(@strPrefix) ))),0)
from LosPosFAndBHeader where poshbillorprocess = ''B'' and
poshshopid = @intShopID  and
poshBillNo Like @strPrefix1
End
if @intnextMaxno=0
Begin
	    set @intMaxno=1
		if @strPrefix<>''''
		   begin
				set @intMaxno = @strPrefix+cast(@intMaxno as varchar(50))
		   end		
end
else
Begin
set @intnextMaxno=@intnextMaxno+1
set @intMaxno = @strPrefix+cast(@intnextMaxno as varchar(50))
End
select  @intMaxno' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudUserFormat]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudUserFormat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified by        : Hariharan R
-- Modified Date      : 12/08/2004
-- Comments           : Budgeting in Account Forma
-----------------------------------------------------------------------------------------
--Exec spBudUserFormat ''20040412'',1,12,1,0,0,15,''A''
CREATE PROCEDURE [dbo].[spBudUserFormat] (@strToDate as varchar(10),
	                               @intCompanyID as int,
	                       @intformatid as int,
	               @intDepartmentId as int = 0,
				       @intconsolidation  as int=0,
				       @BitCons as int=0,
				       @PlanId as int,
				       @Rpttype as varchar(4),
				       @strFromDate as varchar(10)='''') as
--Rpttype used for differenticate the reports planned and actual figure report
-- ''P'' For Plan Value Report
-- ''A'' For Plan value and Actual Value combination report
Begin
set nocount on
declare	
	 @dtToDate   datetime,
	 @intLastFinId  integer,
	 @dtStartDate  datetime,	
	 @dtEndDate  Datetime,
	 @dtCurrFinUnclosedSDate  datetime,	
	 @intYear as int,
	 @OpBalance as numeric(18,2) 		
	
Create table #BudUserFormat(
	 CompanyID int,
	 departmentid int,	
	 accountid int,
	 AccCode varchar(50),
	 AccDesc varchar(100),
	 AcType varchar(1),
	 GroupID int,
	 GroupName varchar(100),
	 reportgroupid int,
	 ParentGroupID int,
	 iscaption varchar(5),
	 repgroupname varchar(50),
	 note varchar(50),
	 dorder int,
	 InFlow int,
	 PlanYear  varchar(10),
	 PlannedAmt numeric(18,2),
	 LastYearAmt numeric(18,2),	
	 ActualAmt numeric(18,2),
	 openingamt numeric(18,2))
if @rpttype =''A''
	Begin
	Create table #vwJournalDetails
		 (companyid int,
		  journalid	int,
		  journaldetailid	int,
		  journalcredit	bit,
		  accountid	int,
		  Amount	numeric(18,2),
		  ActualAmount	numeric(18,2),
		  departmentid	int,
		  depamount	numeric(18,2),
		  Postgroup int)
	Create table #Tempjournalheader
		 (JournalID	int,
		 CompanyID	int,
		 JournalDate	smalldatetime,
		 ReferenceNo	varchar(100),
		 Remarks	varchar(250),
		 Type	char(10),
		 Cancel	bit,
		 Realised	bit,
		 CurrencyId	int,
		 FinancialID	int,
		 chequedate	datetime,
		 updatetime	datetime,
		 bankdate	datetime)
	end
	set @dttodate = convert(Datetime, @strToDate)
	-- create the temporary table to insert sub departments
	-- table name is given as #SubDepts1 to avoid conflicts
	-- with #SubDepts inside the sp
	create table #SubDepts1(DeptId int)
	 if @intconsolidation=0
	    insert into #SubDepts1 values(@intDepartmentId)
	 else
	    -- get the sub depts into the temporary table
	insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
	
	     Insert into #BudUserFormat 	
		Select a.CompanyId, accfor.departmentid, a.AccountId, a.AccountCode,
		a.AccountDesc, 	g.AccountType, g.GroupID, g.GroupDesc,
		gr.Groupid, isnull(ParentGroupID,0) ParentGroupID, gr.iscaption,
		gr.groupname, gr.groupcode, gr.displayorderid,	
		cast(gr.inflow as varchar(2))inflow, a.bphplanyear, a.bpdAmount,
		0.00 LastYearAmt,0.00 Actualamt,0.00 openingamt
		From aaccrepformat accFor, aAccRepGroup gr
		left outer Join
		(select a.companyid, a.accountcode,a.accountdesc,a.accountid,b.formatid,
		 a.groupid,b.groupid repgrpid,bphplanyear,sum(bpdAmount)bpdamount
		 from aAccountMaster a, aRepFormatAccounts b,
		 budgetplanheader BudH,budgetplandetail BudD
		 where a.accountid=b.accountid and a.companyid=b.companyid and
		 budd.bpdbudgetheadid= a.accountid and
		 BudH.bphBudgetPlanID = Budd.bpdBudgetPlanID and
	   	 BudH.bphCompanyID = Budd.bpdCompanyID and budd.bpdrevised=0
		 and bphcancelled=0
		 and bpdmonthno <= month(@dttodate) and bphplanyear=year(@dttodate) and	
		 bpdMonthNo >= month(@strFromDate) and
		 BudH.bphBudgetPlanID=@planid and b.formatid= @intformatid
		 group by  a.companyid, a.accountcode,a.accountdesc,
		 a.accountid,b.formatid,
		 a.groupid,b.groupid ,bphplanyear ) a
		 on gr.CompanyId = a.CompanyId  and  gr.groupid =a.repgrpid
		 and gr.formatid=a.formatid
	 	 LEFT outer join aGroupMaster g on a.GroupId = g.groupid and
			a.CompanyId = g.CompanyId
		 where
		      gr.FormatId =accfor.formatid and gr.companyid=accfor.companyid
		      and gr.formatid= @intformatid
	--updating the actual amount if the reporttype ''A''
	
if @Rpttype=''A''
Begin
	if @strFromDate<>''''
	Begin
		Select @intLastFinId = max(FinancialId) from vwFinYearPeriod
		where CompanyId = @intCompanyId  and year(sdate)=year(@strToDate)
		if @intLastFinId = 0
	   	begin	
			Select 	@dtStartDate = sdate, @strFromDate =
			convert(varchar(10), sdate, 112) from vwFinYearPeriod where
			financialid = (Select min(financialid) from afinancialyear where
			companyid = @intCompanyId) and CompanyId= @intCompanyId
	   	End
		ELSE
	  	begin	
			Select 	@dtStartDate = sdate,
			@strFromDate = convert(varchar(10), sdate, 112)
			from vwFinYearPeriod where financialid = @intLastFinId and
			CompanyId= @intCompanyId		
	  	end		
	End
	Else
	Begin
		set @dtStartDate = convert(datetime, @strFromDate)
	End
	-- Taking the Last Year value
insert #Tempjournalheader
	Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtStartDate
	and JournalDate <= @dtToDate and h.CompanyId = @intCompanyId
	if @intDepartmentId = 0
	   begin
		insert #vwJournalDetails
		Select d.* from #Tempjournalheader h (NOLOCK),
		vwJournalDetails  d (NOLOCK) where JournalDate>= @dtStartDate and
		JournalDate <= @dtToDate and h.JournalId = d.JournalId and
		h.CompanyId = d.CompanyId and h.Cancel = 0 and
		h.CompanyId = @intCompanyId 	
	   end
	else
	  begin
		insert #vwJournalDetails
		Select d.* from #Tempjournalheader h (NOLOCK),
		vwJournalDetails  d (NOLOCK) where JournalDate>= @dtStartDate and
		JournalDate <= @dtToDate and h.JournalId = d.JournalId and
		h.CompanyId = d.CompanyId and h.Cancel = 0 and
		h.CompanyId = @intCompanyId and d.departmentid in
		(Select Deptid from #SubDepts1)
	  end
	-- Collected the journal and others into temporay table for process  and update the figure
	-- For Last year value	
		
		Update #BudUserFormat set ActualAmt  = ActualAmt + trialDeb.amount from (Select v.AccountId,
		v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
		Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
		#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
		h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
		h.JournalDate >= @dtStartDate and
		h.JournalDate <= @dtToDate
		group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
		trialDeb.Accountid =#BudUserFormat.AccountId and
		trialDeb.DepartmentId = #BudUserFormat.DepartmentId
		and trialDeb.CompanyId = #BudUserFormat.CompanyID and
		trialDeb.CompanyId = @intCompanyId
		and (#BudUserFormat.AcType =''A'' or #BudUserFormat.AcType =''E'')
		Update #BudUserFormat set ActualAmt  = ActualAmt - trialDeb.amount from (Select v.AccountId,
		v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
		Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
		#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
		h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
		h.JournalDate >= @dtStartDate and
		h.JournalDate <=  @dtToDate
		group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
		trialDeb.Accountid = #BudUserFormat.AccountId and
		trialDeb.DepartmentId = #BudUserFormat.DepartmentId
		and trialDeb.CompanyId = #BudUserFormat.CompanyID and trialDeb.CompanyId = @intCompanyId
		and (#BudUserFormat.AcType =''L'' or #BudUserFormat.AcType =''I'')
		Update #BudUserFormat set ActualAmt  = ActualAmt + trialDeb.amount from (Select v.AccountId,
		v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
		Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
		#vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and
		h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
		h.JournalDate >= @dtStartDate and
		h.JournalDate <=  @dtToDate
		group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
		trialDeb.Accountid = #BudUserFormat.AccountId and
		trialDeb.DepartmentId = #BudUserFormat.DepartmentId
		and trialDeb.CompanyId = #BudUserFormat.CompanyID and trialDeb.CompanyId = @intCompanyId
		and (#BudUserFormat.AcType =''L'' or #BudUserFormat.AcType =''I'')
		Update #BudUserFormat set ActualAmt  = ActualAmt - trialDeb.amount from (Select v.AccountId,
		v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
		Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
		#vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and
		h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
		h.JournalDate >= @dtStartDate and
		h.JournalDate <=  @dtToDate
		group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
		trialDeb.Accountid =#BudUserFormat.AccountId and
		trialDeb.DepartmentId = #BudUserFormat.DepartmentId
		and trialDeb.CompanyId = #BudUserFormat.CompanyID and trialDeb.CompanyId = @intCompanyId
		and (#BudUserFormat.AcType =''A'' or #BudUserFormat.AcType =''E'')
		--Taken Lastyear Value after clearing the temperary journal tables
		Delete From #vwJournalDetails
		Delete From #Tempjournalheader	
End	
	
	Select @intYear = bphPlanYear from BudgetPlanHeader where
	bphCompanyID = @intCompanyId and bphBudgetPlanID = @PlanId
-- *****FOR FINDING OPENING FIGURES OF PLANNED AND ACTUAL COLUMNS ****************
	insert #BudUserFormat
	Select  @intCompanyId, @intdepartmentid, null,  null, null, null, null, null, null,
	null, ''o'', ''Opening '', null, 0, 0, @intYear, 0, 0, 0, 0
	exec spBudgetOpening @strFromDate, @PlanId, @intformatid,
	@intCompanyId, @bitCons, @intDepartmentId, @intconsolidation, 0, @OpBalance output
	Update #BudUserFormat set PlannedAmt = @OpBalance where repGroupName =''Opening''
	and isCaption=''o''
	exec spBudgetOpening @strFromDate, @PlanId, @intformatid,
	@intCompanyId, @bitCons, @intDepartmentId, @intconsolidation, 1, @OpBalance output
	Update #BudUserFormat set ActualAmt = @OpBalance where repGroupName =''Opening''
	and isCaption=''o''
	Update #BudUserFormat set isCaption = ''n'' where isCaption =''o''
-- *****FOR FINDING OPENING FIGURES OF PLANNED AND ACTUAL COLUMNS ****************
	Select * from #BudUserFormat
	drop table #BudUserFormat
	set nocount off
End' 
END
GO
/****** Object:  View [dbo].[vwRommapartmentOccupancydtls]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRommapartmentOccupancydtls]'))
EXEC dbo.sp_executesql @statement = N'
---------------*****************************-------------------------------------
--created by 	:	dheena
--create date 	:	27082003
--MOdified by	: venki, Hariharan
--MOdified by	: 31/10/2003
--purpose room occupanct dtls report
--modified by venki 311003--changed chdate chking
-- added chcancelled = 0 and mghagreementid = chagreementid
--dheena add monthname and monthno 9-01-2004
CREATE  view [dbo].[vwRommapartmentOccupancydtls] as
select mghCompanyId,mghShopId,mghAgreementid,mghAgreementno,mghAgreementDate,
mghleaseendingdate,mghleasecommencingdate,customername,chDate,
apdapartmentno,apdapartmentid,customerid,mghCancelled,
datename(month,mghAgreementDate) monthname,
month(mghAgreementDate) monthno
from losApartmentAgreementHeader left outer join
losreservationheader on mghReservationID=rhreservationid
and mghCompanyId=rhcompanyid and mghShopId=rhshopid left outer join
acustomermaster  on rhcustomerid=customerid and rhcompanyid=companyid
left outer join LOSApartmentDetail on mghApartmentId=apdapartmentid
and mghCompanyId=apdcompanyid and mghShopId=apdShopid
left outer join losApartmentCheckOut on
mghShopId=chShopID and mghCompanyId=chCompanyId
and mghApartmentId=chApartmentId and mghagreementid = chagreementid
and chcancelled = 0 and chDate between
mghleasecommencingdate and mghleaseendingdate,
losApartmentAgreementDetails where mgdcompanyid=mghCompanyId
and mgdshopid=mghShopId and mghAgreementId=mgdAgreementId'
GO
/****** Object:  View [dbo].[vwShopTotalStockVerification]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopTotalStockVerification]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by  : Kishore
-- Created in  : 27/08/2003
-- Comments    : View for printing report vwShopTotalStockVerification
--               Created to use in report - rptShopTotalStockVerification
--		 Taken from v2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopTotalStockVerification] AS
--
SELECT h.svhId, h.svhShopId, svhNo, svhDate, svhVerificationBy,
svhCancelled, svhRemarks, svdItemId, svdAvailStock AvailableStock,
svdVerifiedBadStock VerifiedStock, svdVerifiedStock ActualVerifiedStock,
svdAvailBadStock AddedByUser, i.ItemCode, vw.ItemDescription, u.UnitCode,
svdCostPrice * svdVerifiedStock StockValue,
CASE SUBSTRING(svhFutureVc, 2, 1)
	WHEN ''n'' THEN ''No''
	WHEN ''c'' THEN ''Yes''
END Confirmed
FROM losStockVerificationHeader h, losStockVerificationDetail d,
aItem i, aUnit u, vwItemDescription vw
WHERE h.svhId = d.svdId
AND h.svhShopId = d.svdShopId
AND d.svdItemId = i.ItemId
AND i.ItemId = vw.ItemId
AND i.UnitsId = u.UnitId
AND LEFT(svhFutureVc, 1) = ''T''
AND svhCancelled = 0'
GO
/****** Object:  View [dbo].[vwShopStockWriteoff]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopStockWriteoff]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwShopStockWriteoff    Script Date: 18/01/2003 9:45:36 PM ******/
-- Modified by - Kishore
-- Modified on - 08/11/2002
-- Added writeOffQty and modified AferVerify
--Modified By Sreejith
--Modified on 20100920
--Added the fields dbo.LOsWriteOffHeader.whdoneby,dbo.LOsWriteOffHeader.whApprovedby,
--     dbo.LOsWriteOffHeader.whreceivedby,dbo.LOsWriteOffHeader.whIssuedby  ,dbo.LOsWriteOffDetail.WdDetailID
--     to the view
-------------------------------------------
--Modified by : VinothMurugan V.
--Date    : 24/11/2010
--Purpose   : Adding writtenvalue column
-------------------------------------------
CREATE VIEW [dbo].[vwShopStockWriteoff]
AS
SELECT     dbo.LOsWriteOffHeader.whShopID, dbo.LOsWriteOffHeader.WhID, dbo.LOsWriteOffDetail.WdDetailID,
dbo.LOsWriteOffHeader.WhNo, dbo.LOsWriteOffHeader.WhDate,
dbo.LOsWriteOffHeader.WhUserName, dbo.LOsWriteOffHeader.WhRemarks,
dbo.vwitemDescription.itemdescription, dbo.LOsWriteOffDetail.WdItemID, dbo.LOsWriteOffHeader.whtype,
dbo.LOsWriteOffDetail.WdAvailableQty AS BeforeVerify, dbo.LOsWriteOffDetail.WdWriteoffQty AS WriteOffQty,
dbo.LOsWriteOffDetail.WdAvailableQty - dbo.LOsWriteOffDetail.WdWriteoffQty AS AfterVerify  ,
dbo.LOsWriteOffHeader.whdoneby,dbo.LOsWriteOffHeader.whApprovedby,dbo.LOsWriteOffHeader.whreceivedby,
dbo.LOsWriteOffHeader.whIssuedby,WdWriteoffQty * wdcostprice as writtenvalue
FROM         dbo.LOsWriteOffHeader INNER JOIN
dbo.LOsWriteOffDetail ON dbo.LOsWriteOffHeader.whShopID = dbo.LOsWriteOffDetail.wdShopID AND
dbo.LOsWriteOffHeader.WhID = dbo.LOsWriteOffDetail.WdID INNER JOIN
dbo.vwitemDescription ON dbo.LOsWriteOffDetail.WdItemID = dbo.vwitemDescription.ItemID'
GO
/****** Object:  View [dbo].[vwShopStockVerification]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopStockVerification]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopStockVerification    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
--modified by: Benzigar S D
--Modified n : 18/08/2009
--Comment    : Added svdcostprice
CREATE view [dbo].[vwShopStockVerification] as
select svhShopId, svhid, svhno, svhdate, svhverificationby, svhremarks,svditemid,
ItemDescription, svdAvailStock as BeforeVerify, svdVerifiedStock as AfterVerify,svdcostprice
from losstockverificationheader, losstockverificationdetail, vwitemdescription
where svhShopId = svdShopid and svhid = svdid and svditemid = ItemID'
GO
/****** Object:  View [dbo].[vwSpecialDespatchOutQty]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialDespatchOutQty]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 18/01/2003 9:45:36 PM ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 31/07/2002 2:00:29 PM ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 20/11/2001 9:59:02 AM ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 17/11/2001 9:21:37 PM ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 16/06/2001 15:36:32 ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 09/03/2001 02:32:27 ******/
/****** Object:  View dbo.vwSpecialDespatchOutQty    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwSpecialDespatchOutQty] as
select ddGodownID,ddItemID,sum(dditemgoodqty) as despatchQty,dhDespatchDate from meispecialdespatchtoshopdetail,
meispecialdespatchtoshopheader where ddDespatchID=dhDespatchID and ddGodownID=dhGodownID and dhCancelled=0
group by ddGodownID,dhDespatchDate,ddItemID'
GO
/****** Object:  View [dbo].[vwspecialdespatch]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialdespatch]'))
EXEC dbo.sp_executesql @statement = N'
--modified By	:- Hariharan R
--Modified Date :- 26/09/2003
--modified By	:- venki 181203 specialinvoice finished chking
CREATE view [dbo].[vwspecialdespatch] as
select dhdespatchid, dhdespatchno, dhdespatchdate,IhInvoiceNo,IhCustomerID,IhInvoiceDate,dhvehicleno, dhRemarks,
ddGodownid, ddShopid, ddlocationid, ddShipmentid, ddItemid, ddItemGoodQty,ddPackQty,ddPackingTypeID
from
losSpecialInvoiceheader ih, MEiSpecialDespatchToShopheader dh, MEiSpecialDespatchToShopdetail dd
where dhIssuenoteid = ihinvoiceid and dhshopid = ihshopid and ddDespatchid = dhdespatchid and
dhshopid = ddshopid and dhgodownid = ddGodownid and ihtransfinished=1'
GO
/****** Object:  View [dbo].[vwShopDamageClearing]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopDamageClearing]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Object:  View dbo.vwShopDamageClearing    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 11/12/02
--Modified by 		: Santhosh m
--Comments		: Added dchcancelled on 30/09/2003
--
CREATE view [dbo].[vwShopDamageClearing] as
select dchShopid, dchClearingID, dchClearingNo, dchClearingDate, dchClearingDoneBy, dchRemarks,
dcditemid, ItemDescription, sum(dcdAvailableQty) as BeforeVerify, sum(dcdWriteOffQty) as AfterVerify,max(convert(int, dchcancelled)) as cancel
from losShopDamageClearingHeader, losShopDamageClearingDetails, vwItemDescription
where dchShopid = dcdShopid and dchClearingID = dcdClearingID and dcdItemID = ItemID
group by dchShopid, dchClearingID, dchClearingNo, dchClearingDate, dchClearingDoneBy, dchRemarks,
dcditemid, ItemDescription'
GO
/****** Object:  View [dbo].[vwservicetechniciandetails]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwservicetechniciandetails]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------
--Modified on                   : 29/06/2004
--Modified by                   : Hariharan
--Comments                      : serCallBkhno added , INVOICE TABLE GIVEN IN LEFT OUTER
--Modified on                   : 04/07/2009
--Modified by                   : jyothish
--Comments                      : Adding sales person ID
--Modified on                   : 19/07/2010
--Modified by                   : Shine Das
--Comments                      : Adding ModelNo,serCallBkhslno,Part_code
---------------------------------------------------------------
CREATE  VIEW [dbo].[vwservicetechniciandetails] as
select
serbookhInspectionNo serbookhno, serbookhInspectionDate serbookhdate,
sercallbkhpurchdate serbookhpurchdate, serbookhdeldate, '''' serinvhprocno,
'''' serinvhprocdate, '''' serinvno, '''' serinvhdate, sertechcompanyid, sertechbookid,
sertechshopid, sertechdetailid, sertechid, sertechstarttime starttime,
sertechendtime endtime, sertechcostperhr, sertechservicetype,
sertechcomments, sertechstatus, sercallbkhfuturevc serbookhfuturevc,
sercallbkhrecvdfrom customername, 0 serinvhcompleted,
sercallbkhfuturevc itemname,
isnull(serbookhserviceamt,0)+ isnull(serbookhpartscost,0)
serbookhestamount, isnull(serbookadvanceamount,0) serbookadvanceamount,
0 serinvhamount,spername, a.ItemCategoryID, ic.CategoryNameDescription,
''Diagnosis'' SerName, sertechstarttime,sertechendtime,
serbookhInspectionNo JObCardRefNo,'''' plannedstarttime,
'''' plannedendtime,los.serCallBkhno,los.serCallBkhdate ,Sperid,datediff ("mi",sertechstarttime ,sertechendtime) DateDf,ModelNo,serCallBkhslno,Part_code
from
losservicebookingheader bh,loscallbookingheader los,
losbookservtechniciandetails bks, asalespersonmaster sp, aitem a,
aitemCategory ic
where
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bh.serbookhcompanyid
and bh.serbookhshopid=los.serCallBkhshopid and sercallbkhItemId = a.Itemid
and a.itemCategoryid = ic.ItemCategoryid and
bks.sertechcompanyid = bh.serbookhcompanyid and bks.sertechbookid = serbookhid
and bks.sertechshopid = serbookhshopid and serbookhinpcancelled=0 and
serCallBkhcancelled=0 and serbookhid not in (
Select
isnull(serinvhbookingid,0)
from
losserviceheader
where serinvhshopid = serbookhshopid and serinvhjobinvcancelled=0)
and sperid = sertechid
union all
select
isnull(serbookhInspectionNo,'''') serbookhno,
isnull(serbookhInspectionDate ,'''')  serbookhdate,
isnull(sercallbkhpurchdate,'''') serbookhpurchdate, isnull(serbookhdeldate,'''') serbookhdeldate,
serinvhprocno, serinvhprocdate, serinvno,
serinvhdate, serinvtechcompanyid, serbookhid,
serinvtechshopid, serinvtechdetailid, serinvtechid,
seRINVtechstarttime, serINVtechendtime,
serINVtechcostperhr, serINVtechservicetype, serINVtechcomments, serINVtechstatus,
isnull(sercallbkhfuturevc,'''') serbookhfuturevc , isnull(sercallbkhrecvdfrom,'''') customername,
ls.serinvhcompleted, li.serinvhitemname, isnull(serbookhserviceamt,0)+ isnull(serbookhpartscost,0)
serbookhestamount , isnull(serbookadvanceamount,0) serbookadvanceamount,
li.serinvhamount, spername, a.ItemCategoryID, ic.CategoryNameDescription, serName,
serinvtechstarttime, serinvtechendtime, serinvhJobCardNo JObCardRefNo,
serinvTechEstStartDate,serinvTechEstEndDate,los.serCallBkhno,los.serCallBkhdate,Sperid, datediff ("mi",seRINVtechstarttime,serINVtechendtime) DateDf,ModelNo,serCallBkhslno,Part_code
from
losservinvoicetechniciandetails bks left outer join aServiceMaster
on serinvTechServiceID = serid, losserviceheader ls left outer join
losservicebookingheader bk on serinvhshopid = serbookhshopid
and ls.serinvhcompanyid = serbookhcompanyid and serinvhbookingid = serbookhid
and bk.serbookhinpcancelled=0
inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid
and bk.serbookhshopid=los.serCallBkhshopid  and serCallBkhcancelled=0
left outer join losserviceinvheader li   on ls.serinvhid = li.serinvhjobcardid
and ls.serinvhshopid=li.serinvhshopid and  ls.serinvhcompanyid = li.serinvhcompanyid
and 0 = li.serinvhcancelled  , aitem a,
aitemCategory ic, asalespersonmaster sp
where  bks.serinvtechcompanyid = ls.SerINVhcompanyid and sertechinvid  = ls.serinvhid
and bks.serinvtechshopid = ls.serinvhshopid and sperid = serinvtechid
and ls.serInvhItemId = a.Itemid and a.itemCategoryid = ic.ItemCategoryid
and serinvhjobinvcancelled=0'
GO
/****** Object:  View [dbo].[vwPayrollLinkwithPayment]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayrollLinkwithPayment]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created  by Venkitesh 130304
-- Purpose :- To get the information of balance figure and pending data
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE  view [dbo].[vwPayrollLinkwithPayment] as
select max(a.transid)transid,max(a.transno)transno,max(c.pddpaylinktransid)pddpaylinktransid,
max(deptamount)depamount,isnull(sum(c.pddamount),0)pddamount,
max(accountid)accountid,a.departmentid from  papayacclinkheader a,
papayacclinkdetails b
left outer join (select pddpaylinktransid,pddamount,pddaccountid,phDepartmentID from aHQPaymentVoucherHeader,
ahqpaymentvoucherdebitdetails  where
phPaymentID =pddPaymentID and
phCompanyID=pddCompanyID and phcancelled=0 )c  on
b.transid= pddpaylinktransid
and b.accountid = c.pddAccountID
where a.transid=b.transid and Cancelled=0
AND TRANSTYPE<>''p''
group by  accountid,a.departmentid
having isnull(sum( c.pddamount),0) < max(b.deptamount)'
GO
/****** Object:  View [dbo].[vwpaymentvoucherdebitdetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentvoucherdebitdetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpaymentvoucherdebitdetails    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
CREATE view [dbo].[vwpaymentvoucherdebitdetails] as
select pddcompanyid, pddpaymentid, a.accountdesc, pdd.pddamount from
aaccountmaster a, ahqpaymentvoucherdebitdetails pdd
where a.companyid = pdd.pddcompanyid and a.accountid = pdd.pddaccountid'
GO
/****** Object:  View [dbo].[vwPrePurchaseOrderTracking2]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPrePurchaseOrderTracking2]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created By   : Benzigar S D
--Created Date : 09082008
------------------------------------------------------------------------
create view [dbo].[vwPrePurchaseOrderTracking2] as
select vw.pohpoid,
case when vw.porequestid is not null then vw.porequestid else a.pohrequestid end as pohrequestid,
case when vw.pohshopid is not null then vw.pohshopid else a.pohshopid end as pohshopid,
vw.ShopRequetNO,
a.pohpono as HQRequestNo,vw.QuotationNO from vwPrepurchaseordertracking1 vw left outer join loprePurchaseOrderHeader a on
vw.pohquotationid=a.pohpoid or vw.porequestid=a.pohpoid'
GO
/****** Object:  View [dbo].[vwPurchaseBillNotCosted]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillNotCosted]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------
--Created BY    :Shinu
--Created Date  :10/07/2007
--Comments      :For Populating Pending Bill (Both Foreign and Local)
-------------------------------------------------------------------------------------------------------------
--Modified BY   :
--Modified Date :
--Comments      :
-------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwPurchaseBillNotCosted] AS
select	pbhCompanyID CompanyID,pbhBillID BillID,pbhBillNo BillNo,pbhvendorRefNo VendorBIllNo,
	pbhBillDate BillDate,pbhVendorID VendorID,VendorName,pbhBillAmount BillAmount,
	pbhDepartmentID DepartmentID,DepartmentName,pbhDepartmentID locationID,
	DepartmentName LocationName,''Foreign Purchases'' Type
from LOspPurchaseBillHeader
INNER JOIN aVendorMaster ON vendorID=pbhVendorID
INNER JOIN aDepartmentMaster ON DepartmentID= pbhDepartmentID
where pbhCancelled=0 and pbhused=0
UNION ALL
select  lphCompanyID,lphBillID,lphBillNo,'''',lphBillDate ,lphVendorID ,VendorName,lphBillAmount,
	lphDepartmentID,DepartmentName,lphshopID,ShopName, ''LocalPurchases'' Type
from LosLocalPurchaseHeader
INNER JOIN aVendorMaster ON vendorID=lphVendorID
INNER JOIN aDepartmentMaster ON DepartmentID= lphDepartmentID
INNER JOIN aShops ON ShopID= lphshopID
where lphCancelled=0 and lphcosted=0'
GO
/****** Object:  View [dbo].[vwPurchaseBillDetailwithunit]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetailwithunit]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwPurchaseBillDetailwithunit    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--Modified On : 17/06/2006
--modified By : aneesh [removed text in convert function and added varchar]
------------------------------------------------------------------------------
-- RefNo		 : RefNo-1
-- Modified By   : MANUNADH.U
-- Modified Date : 09-05-2012
-- Comment       : Added PackingTypeName to show in the rptpurchasebill.rpt
------------------------------------------------------------------------------
CREATE view [dbo].[vwPurchaseBillDetailwithunit]
as select pb.*,u.unitcode,u.unitname, p.packingtypecode,p.PackingTypeName,convert(varchar(250),vw.itemdescription)
itemdescription
from LOspPurchaseBillDetail pb
	left outer join aitem ai on pbdItemID=ItemID,
	apackingtype p, aunit u, vwitemdescription vw
where p.packingtypeid= pb.pbdpackingtypeid and ai.unitsid = u.unitid and ai.itemid= vw.itemid'
GO
/****** Object:  View [dbo].[vwreexportquotation]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportquotation]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified By 	 : Hariharan
-- Modified Date : 14/03/2004	
CREATE view [dbo].[vwreexportquotation] AS
select  distinct
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,ac.customerid,ac.customername,ac.Address1 ,	
	ac.Address2, ac.Address3, ac.custsymbol symbol, redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, dh.rehexportid as requestid,dh.rehexportno as requestno,
	dh.rehExportDate as requestdate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end rehcancelled,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,
	 ''0'' identifiedstatus ,rehProformaID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProformaID = dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				customerid, customername,Address1,Address2, Address3,
				acur.currencyid,acu.companyid ,acur.Symbol  custsymbol
			from
				acustomermaster acu left outer join acurrencymaster acur
		on acur.CurrencyID=acu.currencyid and acu.CompanyID=acur.CompanyID
				) ac
	On ac.customerid = rehcustomerid and ac.companyid=rehcompanyid,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and left(rehtype,1)=''Q'' and ac.customerid is not null
union all
select
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,vm.vendorid,vm.vendorname,
	vm.address1 address1,vm.address2 address2,vm.address3 address3,
	vm.vensymbol symbol,  redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, dh.rehexportid as requestid,dh.rehexportno as requestno,
	dh.rehExportDate as requestdate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address1,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal ,''1'',rehProformaID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProformaID = dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				vendorid, vendorname,Address1,Address2, Address3,bcur.currencyid,
				bcur.symbol vensymbol
			from
				avendormaster vm left outer join acurrencymaster bcur
		on bcur.CurrencyID=vm.currencyid and vm.CompanyID=bcur.CompanyID
				)vm
	On vm.vendorid = rehvendorid ,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and left(rehtype,1) =''Q'' and vm.vendorid is not null'
GO
/****** Object:  View [dbo].[vwreexportpurchaserequest]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportpurchaserequest]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--done by venki 260903
CREATE view [dbo].[vwreexportpurchaserequest] as
select
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode, customername,Address1,Address2, Address3, Symbol, redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address, ''0'' identifiedstatus
from
	
	losexportheader ih ,losexportdetail dh, aitem a, apackingtype p,
	vwitemdescription vw, aunit u, acustomermaster ac, acurrencymaster c
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and ac.customerid = rehcustomerid and ac.currencyid=c.currencyid and
	rehtype=''R''
union all
select
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode, vendorname,Address1,Address2, Address3, Symbol, redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address, ''1'' identifiedstatus
from
	
	losexportheader ih ,losexportdetail dh, aitem a, apackingtype p,
	vwitemdescription vw, aunit u, avendormaster ac, acurrencymaster c
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and ac.vendorid = rehvendorid and ac.currencyid=c.currencyid and
	rehtype=''R'''
GO
/****** Object:  View [dbo].[vwreexportPurchaseOrder]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportPurchaseOrder]'))
EXEC dbo.sp_executesql @statement = N'
--MOdified by 	: Hariharan
--Modified Date	: 09/03/2004
CREATE VIEW [dbo].[vwreexportPurchaseOrder] AS
select  distinct
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,ac.customerid,ac.customername,ac.Address1 add1,	
	ac.Address2, ac.Address3, ac.custsymbol symbol, redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, dh.rehexportid as quotationid,dh.rehexportno as quotationno,
	dh.rehExportDate as quotationdate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address1,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,
	 ''0'' identifiedstatus ,rehProformaID, rehBankName, rehBankaddress, rehSwiftaddress, rehAdvanceAmt,
	rehPriceType, rehpaymentterm, rehDeliveryDate, rehBankCashAccID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProforma=dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				customerid, customername,Address1,Address2, Address3,
				acur.currencyid,acu.companyid ,acur.Symbol  custsymbol
			from
				acustomermaster acu left outer join acurrencymaster acur
		on acur.CurrencyID=acu.currencyid and acu.CompanyID=acur.CompanyID
				) ac
	On ac.customerid = rehcustomerid and ac.companyid=rehcompanyid,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and rehtype=''P''and ac.customerid is not null
union all
select
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,vm.vendorid,vm.vendorname,
	vm.address1 vendadd1,vm.address2 venadd2,vm.address3 vendadd3,
	vm.vensymbol symbol,  redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, dh.rehexportid as quotationid,dh.rehexportno as quotationno,
	dh.rehExportDate as quotationdate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address1,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal ,''1''  identifiedstatus ,rehProformaID,
	rehBankName, rehBankaddress, rehSwiftaddress, rehAdvanceAmt,
rehPriceType, rehpaymentterm, rehDeliveryDate, rehBankCashAccID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProforma=dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				vendorid, vendorname,Address1,Address2, Address3,bcur.currencyid,
				bcur.symbol vensymbol
			from
				avendormaster vm left outer join acurrencymaster bcur
		on bcur.CurrencyID=vm.currencyid and vm.CompanyID=bcur.CompanyID
				)vm
	On vm.vendorid = rehvendorid ,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and rehtype=''P'' and vm.vendorid is not null'
GO
/****** Object:  View [dbo].[vwReplacementReceipt]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReplacementReceipt]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwReplacementReceipt]
/*
Purpose          : For Replacement Receipt ItemID Population
Type             : Transaction
Transaction Name : Replacement Receipt
Created on       : 02/11/2002
Created by       : Harikrishnan R
Last Modified By : Harikrishnan R, Hariharan R
Last Modified On : 20/11/2002, 07/10/2003
--Comments	 : COrrected the query to take non cancelled records from receiveheader
*/
as
select
a.repreqdcompanyid,a.repreqdshopid,a.repreqdid,a.repreqditemid,a.repreqdbookid,
Avg(isnull(a.repreqqty,0))-sum(isnull(b.rrvdqty,0)) as Qty,
case when Avg(a.repreqqty)>sum(b.rrvdqty) then ''P'' when
Avg(a.repreqqty)<=sum(b.rrvdqty) then ''F'' end Status
from losreplacerequestdetails a left outer join
(select b.* from areprecvendordetail b, areprecvendorheader d where
b.rrvdcompanyid =d.rrvhcompanyid and b.rrvdreceiveid=d.rrvhreceiveid and d.rrvhcancelled=0)
b on a.repreqdid = b.rrvdrepreqid and
a.repreqdcompanyid = b.rrvdcompanyid and a.repreqdshopid = b.rrvdshopid and
a.repreqditemid = b.rrvditemid and a.repreqdbookid=b.rrvdbookingid
left outer join
areprecvendorheader d on b.rrvdcompanyid =d.rrvhcompanyid and
b.rrvdreceiveid=d.rrvhreceiveid and d.rrvhcancelled=0
group by  a.repreqdcompanyid,a.repreqdshopid,a.repreqdid,a.repreqdbookid,a.repreqditemid'
GO
/****** Object:  View [dbo].[vwreexportInvoice]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportInvoice]'))
EXEC dbo.sp_executesql @statement = N'
--Modified by 	: Hariharan
--Modified Date	: 09/03/2004	
--COmments	: Altered to include new fields
CREATE view [dbo].[vwreexportInvoice] AS
select  distinct
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,ac.customerid,ac.customername,ac.Address1 address,	
	ac.Address2, ac.Address3, ac.custsymbol symbol, redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address1,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,
	''0'' identifiedstatus ,rehProformaID, rehBankName, rehBankaddress, rehSwiftaddress, rehAdvanceAmt,
	convert(INT,rehPriceType)  rehPriceType, rehpaymentterm, rehDeliveryDate, rehBankCashAccID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProforma=dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				customerid, customername,Address1,Address2, Address3,
				acur.currencyid,acu.companyid ,acur.Symbol  custsymbol
			from
				acustomermaster acu left outer join acurrencymaster acur
		on acur.CurrencyID=acu.currencyid and acu.CompanyID=acur.CompanyID
				) ac
	On ac.customerid = rehcustomerid and ac.companyid=rehcompanyid,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and rehtype=''I'' and ac.customerid is not null
union all
select
	case when (redDescription is null or redDescription ='''') then vw.itemdescription else
	redDescription end itemdescription, ih.rehexportid,ih.rehexportno,ih.rehReferenceNo,
	ih.rehshopid, ih.rehExportDate, ih.rehDueDate, redItemID, redQuantity, redPQuantity,
	redUnitPrice, redActualUnitPrice,  redCostPrice, UnitCode,
	packingtypecode,vm.vendorid,vm.vendorname,
	vm.address1 vendadd1,vm.address2 venadd2,vm.address3 vendadd3,
	vm.vensymbol symbol,  redPckingTypeID,
	u.unitid, a.itemcode, rehRemarks, unitname, packingtypename, rehExchangeRate,
	rehDepExRate, case when rehCancelled =0 then rehCancelledremarks
	else '''' end address1,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,
	''1'' identifiedstatus ,rehProformaID, rehBankName, rehBankaddress, rehSwiftaddress, rehAdvanceAmt,
	 convert(INT,rehPriceType) rehPriceType, rehpaymentterm, rehDeliveryDate, rehBankCashAccID
	-- ihRecAddUser, ihRecModifyUser,
from
	losexportheader ih left outer join
			(select
				rehProforma , rehexportid,rehshopid,rehexportno,rehExportDate
			from
				losexportheader dh
			where  dh.rehCancelled=0) dh
	on ih.rehProforma=dh.rehexportid and ih.rehshopid=dh.rehshopid	
	Left Outer Join (select
				ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
			from
				losexportOC
			group by
				ioShopID,ioInvoiceId) OtherCharges
	On ih.rehshopid = OtherCharges.ioShopId and ih.rehExportID=ioInvoiceId
	Left Outer Join (select
				vendorid, vendorname,Address1,Address2, Address3,bcur.currencyid,
				bcur.symbol vensymbol
			from
				avendormaster vm left outer join acurrencymaster bcur
		on bcur.CurrencyID=vm.currencyid and vm.CompanyID=bcur.CompanyID
				)vm
	On vm.vendorid = rehvendorid ,
	losexportdetail, aitem a, apackingtype p, vwitemdescription vw, aunit u 	
where
	ih.rehshopid= redshopid and ih.rehexportid=redExportID and
	redPckingTypeID=p.packingtypeid and redItemID=a.itemid and a.itemid=vw.itemid and
	u.unitid=a.unitsid  and rehtype=''I'' and vm.vendorid is not null
--SP_HELP LOSEXPORTHEADER'
GO
/****** Object:  View [dbo].[vwgroupmasterwithlevel]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgroupmasterwithlevel]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwgroupmasterwithlevel    Script Date: 18/01/2003 9:45:36 PM ******/
--Last modified on 	: 09/12/2002
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwgroupmasterwithlevel] as
select * from gmwithlevel
union all
select * from gmlevelone
union all
select * from gmleveltwo
union all
select * from gmlevelthree
union all
select * from gmlevelfour'
GO
/****** Object:  View [dbo].[vwOnsiteJobCardforprinting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwOnsiteJobCardforprinting]'))
EXEC dbo.sp_executesql @statement = N'
--created by sreejith on 02/04/2010
--select * from vwOnsiteJobCardforprinting
--modified by Sreejith on 28/05/2010
--removed the condition  and lsh.serinvhcompleted=1 to show the report even its not completed.
--Added  jyothish serinvdItemTaxPercentage ,serinvdItemTaxAmount,repinvdItemTaxPercentage ,repinvdItemTaxAmount,CUSTOMERTIN
CREATE view [dbo].[vwOnsiteJobCardforprinting]
as
select lc.serCallBkhid as Id,lc.serCallBkhdate,lsh.serinvhid,lsh.serinvhshopid as shopid,lsh.serinvhcompanyid as companyid,lc.serCallBkhno,lc.serCallBkhOnSite,lsh.serinvhitemname,l.serbookhInspectionNo,
serinvhprocno ,lsh.serinvhPaceofWork,lc.serCallBkhWarrantyFrom,lc.serCallBkhWarrantyTo,lih.serinvno,lsh.serinvhprocdate as Date,serCode Code, SerName Description, serinvdcharge ActRate, serinvdchargetaken Rate,
serinvdqty Qty, serinvdcomments Comments, ''Services'' Type,  SerInvHDate,
SerInvHProcDate,lsh.serinvhcustname,lc.serCallBkhrecvdfrom,
lc.serCallBkhtelephone as contactno,spm.Spername as InCharge,lsh.serinvhdespdate,lsh.serinvhremarks ,serinvdItemTaxPercentage ,serinvdItemTaxAmount  from losserviceheader lsh
inner join losserestimateapproval la on la.seaAppbookingId=lsh.serinvhbookingid and la.seaAppShopId=lsh.serinvhshopid
and lsh.serinvhjobinvcancelled=0  and seaAppCancelled=0
inner join losservicebookingheader l on l.serbookhid=la.seaAppbookingId and l.serbookhshopid=la.seaAppShopId
left outer join losserviceinvheader lih on  lsh.serinvhid=lih.serinvhjobcardid and lsh.serinvhshopid=lih.serinvhshopid
and lih.serinvhcancelled=0
inner join loscallbookingheader lc on l.serbookhRefId=lc.serCallBkhid  and l.serbookhshopid=lc.serCallBkhshopid
and lc.serCallBkhOnSite=1
inner join asalespersonmaster spm on lsh.serinvhpreparedby=spm.Sperid
inner join ashopsalespersondetails spd on spm.Sperid=spd.SperID and lsh.serinvhshopid=spd.SperShopid
left outer join (select a1.sertechinvid invid,max(a1.serinvtechdetailid) detailid,max(a1.serinvtechendtime) endtime ,
max(a1.serinvTechEstEndDate) enddate,max(a1.serinvtechid) techid,a1.serinvtechcompanyid tempcompanyid
,a1.serinvtechshopid tempshopid from losservinvoicetechniciandetails a1
where a1.serinvTechEstEndDate in (select max(a2.serinvTechEstEndDate)
from losservinvoicetechniciandetails a2  where a1.serinvtechcompanyid=a2.serinvtechcompanyid
and a1.serinvtechshopid=a2.serinvtechshopid and a1.sertechinvid = a2.sertechinvid
group by a2.serinvTechEstEndDate)  group by
a1.sertechinvid,a1.serinvtechcompanyid,a1.serinvtechshopid) as temptechnican
on lsh.serinvhid=invid  and lsh.serinvhcompanyid=tempcompanyid and
lsh.serinvhshopid=tempshopid
left outer join losinvservicedetails  lsd
on lsh.serinvhcompanyid = serinvdcompanyid and  lsh.serinvhshopid = lsd.serinvdshopid and
lsh.serinvhid = lsd.serinvdinvoiceid  Left Outer Join aservicemaster m
on lsd.serinvdserviceid = serid and  lsd.serinvdcompanyid = sercompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and lsh.serinvhcompanyid=acc.companyid'
GO
/****** Object:  View [dbo].[vwpaymentandreceipt]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentandreceipt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpaymentandreceipt    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 07/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwpaymentandreceipt] as
select jh.companyid, jh.journalid, month(jh.journaldate) tmonth, jh.journaldate, jh.referenceno,
jp.particulars, case when jd.journalcredit =0 then amount else 0 end debitamt, case when
jd.journalcredit =1 then ''To'' else ''By'' end as Prefix, case when jd.journalcredit =1 then
amount else 0 end creditamt, jh.financialid, case when jd.journalcredit =0 then depamount
else 0 end depdebitamt, case when jd.journalcredit =1 then depamount else 0 end depcreditamt,
jd.departmentid
from moajournalheader jh, moajournaldetails jd,
acompanymaster c, vwjournalparticulars jp, aaccountmaster am, asettings s where
jp.companyid = jh.companyid and jp.journalid = jh.journalid and jd.journalcredit =
abs(1 - jp.journalcredit) and s.companyid = am.companyid and s.bankgroupid = am.groupid and
am.companyid = jd.companyid and am.accountid = jd.accountid and jh.companyid = c.companyid and
jh.companyid = jd.companyid and jh.journalid = jd.journalid and jh.cancel =0'
GO
/****** Object:  View [dbo].[VwPartsReplacerequestdtls]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwPartsReplacerequestdtls]'))
EXEC dbo.sp_executesql @statement = N'
--Modified by 	: Hariharan R
--created date  : 03/07/2003
--puprpose 	: Parts Replacement Request details  in service modules
--Comments	: The request details are linked with receive details table
--		: as the requestid is kept in there.
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE view [dbo].[VwPartsReplacerequestdtls] as
select repreqhid,repreqno,repreqshopid,repreqdcompanyid,bk.serbookhcompanyid , los.sercallbkhno serbookhno,
los.sercallbkhdate serbookhdate,serbookhshopid, los.sercallbkhslno serbookhslno, bk.serbookhdeldate,
sercallbkhpurchdate serbookhpurchdate, los.sercallbkpartcode serbookpartcode,itemdescription,
isnull(repreqqty,0) qty,repreqhreceived,los.sercallbkhcategid serbookhcategid, code, repreqdtagno,
vendorname,repreqhdate, isnull(reprecqty, 0) reprecqty, serbooksermode,vendorid
from losreplacerequestheader
left outer join losreplacerequestdetails on
repreqhid=repreqdid and repreqshopid = repreqdshopid and
repreqhcompanyid = repreqdcompanyid
left outer join losreplacereceiveDetails on
repreqditemid=reprecditemid
and repreqdshopid= reprecdshopid
and repreqdid = repRepReqID
and repreqdcompanyid = reprecdcompanyid
left outer join  losreplacereceiveheader on
reprecdid = reprechid   and reprecdshopid = reprechshopid
and reprecdcompanyid = reprechcompanyid
left outer join avendormaster on repreqhvendorid=vendorid
, losservicebookingheader bk,vwitemdescription , loscallbookingheader los
where serbookhid =repreqdbookid and serbookhcompanyid=repreqhcompanyid
and repreqdcompanyid=repreqdcompanyid  and repreqdshopid=repreqshopid
and serbookhshopid=repreqshopid and repreqditemid = itemid and
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid'
GO
/****** Object:  View [dbo].[vwpandcPurchasebillamount]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpandcPurchasebillamount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpandcPurchasebillamount    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 11/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwpandcPurchasebillamount] as
select pbh.pbhbillid, isnull(sum(pbd.pbdItemQuantity * pbd.pbdItemUnitPrice),0) as itemamt,
isnull(sum(pbd.pbdItemQuantity * pbd.pbddummyunitPrice),0) as Dummyitemamt,
isnull(sum(pboc.pboAmount),0) as ocamount, isnull(pbh.pbhDiscount,0) pbhdiscount ,
pbh.pbhadjustmentamount, isnull(poh.pohLCAmount,0) as Lcamount
from
losppurchasebillheader pbh
left outer join losppurchasebilldetail pbd on pbh.pbhBillID = pbd.pbdBillID
left outer join losppurchasebilloc pboc on pbh.pbhbillid = pboc.pboBillID
left outer join lopurchaseorderheader poh on pbh.pbhPOID = poh.pohPoid
and poh.pohcancel =0  and poh.pohLCopened =1
where pbh.pbhCancelled =0 and pbh.pbhPosted =0
group by pbh.pbhbillid ,pbh.pbhdiscount, pbh.pbhadjustmentamount, poh.pohlcamount'
GO
/****** Object:  View [dbo].[vwPaymentsOnPO]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPaymentsOnPO]'))
EXEC dbo.sp_executesql @statement = N'
/*
CREATED BY :SHINE
CREATED ON : 24.03.2012
PURPOSE	   : To select Payments Against a Purchase Order
*/
CREATE VIEW [dbo].[vwPaymentsOnPO] AS
select pvdd.pddhqpoid POID,phPaymentNo,pvh.phexchangerate from aHQpaymentvoucherheader pvh
INNER JOIN aHQPaymentVoucherDebitDetails pvdd on pvh.phPaymentID = pvdd.pddPaymentID where
pvh.phcancelled=0 and pvh.phpohid IS NULL'
GO
/****** Object:  View [dbo].[vwHQbatchno]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQbatchno]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwHQbatchno] as
select lpbd.pbdbillid,lpbd.pbditemid,lpbd.pbdbatchno,hqd.dnmdespatchnoteid from lospPurchaseBilldetail lpbd,aHQDespatchNoteMain hqd
where lpbd.pbdbillid=hqd.dnmbillid'
GO
/****** Object:  View [dbo].[vwJobcardServicePartsForPrinting]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwJobcardServicePartsForPrinting]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By  : Hariharan
--Modified Date : 18/04/2004
--  : Corrected to print the parts replace details also in case if Invoice not done
--jyothish added item desptch
----------------------------------------------------------------------------------
--Ref.No.1
--Modified By  : Aadyakumar.D.V  ,jyothish s r
--Modified Date : 01/10/2011  06/10/2011
--Added serinvdItemTaxPercentage ,serinvdItemTaxAmount,repinvdItemTaxPercentage ,repinvdItemTaxAmount,CUSTOMERTIN
--added serCallBkhcustomerName
-----------------------------------------------------------------------------------
CREATE  view [dbo].[vwJobcardServicePartsForPrinting] as
select li.serinvhcompanyid CompanyId, li.serinvhid jobcardid, li.SerinvhId InvoiceId, li.serinvhshopid ShopId,
serCode Code, SerName Description, serinvdcharge ActRate, serinvdchargetaken Rate,
serinvdqty Qty, serinvdcomments Comments, ''Services'' Type, SerInvNo, SerInvHDate,
SerInvHProcNo, SerInvHProcDate, case when li.SerInvHCustName ='''' then serCallBkhcustomerName   else li.SerInvHCustName  end   as SerInvHCustName , li.SerInvHRefNo, li.SerInvHRemarks,
SerInvHBookingId, li.SerInvHItemName, li.SerInvHItemId, SerInvHDueDate, SerInvDQty PackQty,
isnull(serbookadvanceamount,0) BookingAdvance, aUnit.UnitCode,
serInvhCashAcc ,
case when serInvhCashAcc is null then cur2.Symbol else
cur1.Symbol end currencysymbol,isnull(li.serinvhamount,0.00) amount,spername,enddate,endtime
,sercallbkhdate serbookhdate,serbookhinspectiontime,aitem.ModelNo
,serinvhPaceofWork,li.serinvhmetereading,sercallbkrefno serbookrefno,aitem.Part_code, li.serinvhJobCardNo,
isnull(itemDespatch,0)itemDespatch,serinvdItemTaxPercentage ,serinvdItemTaxAmount,CUSTOMERTIN --Ref.No.1
from  losserviceheader li
left outer join   losserviceinvheader    on li.serinvhid=losserviceinvheader.serinvhjobcardid and li.serinvhshopid=losserviceinvheader.serinvhshopid
and li.serinvhcompanyid=losserviceinvheader.serinvhcompanyid
left outer join losservicebookingheader bk on
li.serinvhshopid = serbookhshopid and  serinvhbookingid = serbookhid and
li.serinvhcompanyid = serbookhcompanyid inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid left outer join losinvservicedetails
on li.serinvhcompanyid = serinvdcompanyid and  li.serinvhshopid = serinvdshopid and
li.serinvhid = serinvdinvoiceid  Left Outer Join aservicemaster m
on serinvdserviceid = serid and  serinvdcompanyid = sercompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid
left outer join acustomermaster cu on losserviceinvheader.serinvhCustomerId= cu.customerid
and losserviceinvheader.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
left outer join (select a1.sertechinvid invid,max(a1.serinvtechdetailid) detailid,max(a1.serinvtechendtime) endtime ,
max(a1.serinvTechEstEndDate) enddate,max(a1.serinvtechid) techid,a1.serinvtechcompanyid tempcompanyid
,a1.serinvtechshopid tempshopid from losservinvoicetechniciandetails a1
where a1.serinvTechEstEndDate in (select max(a2.serinvTechEstEndDate)
from losservinvoicetechniciandetails a2  where a1.serinvtechcompanyid=a2.serinvtechcompanyid
and a1.serinvtechshopid=a2.serinvtechshopid and a1.sertechinvid = a2.sertechinvid
group by a2.serinvTechEstEndDate)  group by
a1.sertechinvid,a1.serinvtechcompanyid,a1.serinvtechshopid) as temptechnican
on li.serinvhid=invid  and li.serinvhcompanyid=tempcompanyid and li.serinvhshopid=tempshopid
left outer join asalespersonmaster on techid=sperid
, aItem , aUnit where li.serinvhitemid = aItem.ItemId and
aItem.UnitsId = aUnit.UnitId and (m.SerCode IS NOT NULL or m.SerCode IS NOT NULL)
union all
select repinvcompanyid, losserviceheader.serinvhid, repinvinvoiceid, repinvdshopid, n.itemcode, n.itemdescription,
repinvdsellrate, repinvdrate, repinvdqty, repinvdcomments, ''Parts Replaced'',  serinvno,
serinvhdate, serinvhprocno, serinvhprocdate,  case when losserviceheader.serinvhcustname ='''' then serCallBkhcustomerName  else losserviceheader.serinvhcustname   end   as serinvhcustname ,
losserviceheader.SerInvHRefNo, losserviceheader.serinvhremarks,
serinvhbookingid, losserviceheader.serinvhitemname, losserviceheader.serinvhitemid,serinvhduedate,repinvpackqty,
isnull(serbookadvanceamount,0) bookingadvance, aUnit.UnitCode, li.serinvhcashacc,
case when li.serinvhcashacc is null then cur2.Symbol else
cur1.Symbol end currencysymbol,isnull(losserviceheader.serinvhamount,0.00) amount,spername,enddate,endtime,
sercallbkhdate,serbookhinspectiontime,m.ModelNo model_no,serinvhPaceofWork,losserviceheader.serinvhmetereading
,sercallbkrefno serbookrefno,m.Part_code, serinvhJobCardNo ,
isnull(itemDespatch,0)itemDespatch ,repinvdItemTaxPercentage ,repinvdItemTaxAmount ,CUSTOMERTIN --Ref.No.1
from losinvpartsreplacedetails , losserviceheader
left outer join  losserviceinvheader li on losserviceheader.serinvhid = li.serinvhjobcardid
and losserviceheader.serinvhshopid=li.serinvhshopid
and losserviceheader.serinvhcompanyid = li.serinvhcompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid
left outer join losservicebookingheader bk on losServiceHeader.serinvhshopid = serbookhshopid
and serinvhbookingid = serbookhid and losServiceHeader.serinvhcompanyid = serbookhcompanyid
inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid
left outer join acustomermaster cu on li.serinvhCustomerId= cu.customerid
and li.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
left outer join (select a1.sertechinvid invid,max(a1.serinvtechdetailid) detailid,max(a1.serinvtechendtime) endtime ,
max(a1.serinvTechEstEndDate) enddate,max(a1.serinvtechid) techid,a1.serinvtechcompanyid tempcompanyid
,a1.serinvtechshopid tempshopid from losservinvoicetechniciandetails a1
where a1.serinvTechEstEndDate in (select max(a2.serinvTechEstEndDate)
from losservinvoicetechniciandetails a2  where a1.serinvtechcompanyid=a2.serinvtechcompanyid
and a1.serinvtechshopid=a2.serinvtechshopid and a1.sertechinvid = a2.sertechinvid
group by a2.serinvTechEstEndDate)  group by
a1.sertechinvid,a1.serinvtechcompanyid,a1.serinvtechshopid) as temptechnican
on losserviceheader.serinvhid=invid  and losserviceheader.serinvhcompanyid=tempcompanyid and
losserviceheader.serinvhshopid=tempshopid
left outer join asalespersonmaster on techid=sperid
, aitem m, aItem n, aUnit
where losserviceheader.serinvhcompanyid = repinvcompanyid  and losserviceheader.serinvhshopid = repinvdshopid
and losserviceheader.serinvhid = repinvinvoiceid and repinvdpartsid = n.itemid and losServiceHeader.serInvhItemId = m.ItemId
and m.UnitsId = aUnit.UnitId'
GO
/****** Object:  View [dbo].[purchasetransflow]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchasetransflow]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[purchasetransflow] as
select a.pohpoid,a.pohpono,a.pohpodate,b.vendorname,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.pohquotconfirmed, a.pohpoonhold, c.purchaseAmount ,
isnull(remarks,'''') remarks,case when a.pohrequestid is not null then mos.Grhrequestno end as ShopRequetNO,
case when a.pohquotationid is not null then ab.pohpono end as QuatationNo,
case when vw.pohQuotationid is not null then a.pohpono end as HQRequestNo
from loPurchaseOrderHeader a inner join  avendormaster b on  a.pohvendorid=b.VendorID left outer join mosgoodsrequestheader mos on a.pohrequestid=mos.grhrequestid and a.pohshopid =mos.grhshopid
left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
left outer join purchsetracking vw on a.pohpoid=vw.pohquotationid
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))'
GO
/****** Object:  View [dbo].[vwTransferOutshoptoGdn]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOutshoptoGdn]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwTransferOutshoptoGdn    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwTransferOutshoptoGdn] as
select dgdshopid,dgditemid,dghDate,sum(dgdDespatchedGoodQty) as transferqty from
mesDespatchTOGodownheader,mesDespatchTOGodowndetail where dghShopId=dgdShopid
and dgdID=dghID and dghCancelled=0 group by dgdShopid,dghDate,dgdItemid'
GO
/****** Object:  View [dbo].[vwTransferIn]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferIn]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwTransferIn    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwTransferIn] as
select asdItemID,asdGodownId,sum(asdReceivedGoodQty) as transferin,ahArrivalDate from loiarrivalshipmentdetail,
loiarrivalheader where asdgodownid=ahlocalgodownid and asdarrivalid=aharrivalid and ahCancelled=0
group by asdGodownID,aharrivaldate,asdItemID'
GO
/****** Object:  View [dbo].[vwwarrentyclaim]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwwarrentyclaim]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Benzigar S D
--Created On : 07/01/2009
--Comment : For Warrenty Claim Report
--Modified By: Nidheesh P V
--Modified On: 24/04/10
--Comments:Included exchangerate,currencyid
CREATE view [dbo].[vwwarrentyclaim] as
select lwh.wchid,lwh.wchshopid,lwh.wchcustomerid,lwh.wchcustomername,lwh.wchdate,lwh.wchno,sum(lwd.wcdcostprice*wchdepexrate)Depcostprice,sum(lwd.wcdcostprice*wchcomexrate)Comcostprice,
lwh.wchmodel,lwh.wchunitserial,lwh.wchlabourcost,lwh.wchpartcostsupplier,lwh.wchlabourcostsupplier,lwh.wchcreditdate,  ash.departmentid ,lwh.wchRefNo,d.depcurrencyid,ac.CurrencyID
from loswarrentyclaimheader lwh,losWarrentyClaimDetail lwd,ashops ash,adepartmentmaster d,acompanymaster ac
where lwh.wchid=lwd.wcdid and lwh.wchshopid=ash.shopid and lwh.wchtype=''WC'' and lwh.wchcancelled=0 and ash.departmentid=d.DepartmentID and ac.CompanyID=lwh.wchCompanyID
group by lwh.wchid,lwh.wchshopid,lwh.wchcustomerid,lwh.wchcustomername,lwh.wchdate,lwh.wchno,lwd.wcdcostprice,
lwh.wchmodel,lwh.wchunitserial,lwh.wchlabourcost,lwh.wchpartcostsupplier,lwh.wchlabourcostsupplier,lwh.wchcreditdate,
ash.departmentid,lwh.wchRefNo, d.depcurrencyid,ac.CurrencyID'
GO
/****** Object:  View [dbo].[vwadvancepaidDebits]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidDebits]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwadvancepaidDebits    Script Date: 16/06/2001 15:36:32 ******/
/****** Object:  View dbo.vwadvancepaidDebits    Script Date: 09/03/2001 02:32:27 ******/
--Modified By: VinothMurugan V.
--Date	     : 14/10/2010
--Purpose    : adding confirm bir
CREATE view [dbo].[vwadvancepaidDebits] as
select DCNID, DCNcompanyid, DCNVendorId from debitcreditnote where DCNcancelled = 0
and DCNDebit = 1  and DCNConfirmed = 1'
GO
/****** Object:  View [dbo].[vwadvancepaidCredits]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidCredits]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE view [dbo].[vwadvancepaidCredits] as
select DCNID, DCNcompanyid, DCNCustomerId,dcnexchangerate from debitcreditnote where DCNcancelled = 0
and DCNDebit = 0'
GO
/****** Object:  View [dbo].[vwInventoryAge]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInventoryAge]'))
EXEC dbo.sp_executesql @statement = N'
--select * from vwInventoryAge where pbdItemID=5557
-- Created by  : Shinu
-- Created on  : 04/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Inventory Ageing
--Include local purchase
--by Abhishek on 23-07-2010 for kooddoo
------------------------------------------------
--Modified By: Nidheesh
--Modified on: 29/07/2010
--Comments: Included vwCompanyTotalStock
CREATE VIEW [dbo].[vwInventoryAge] as
select CompanyTotalStock.pbhCompanyID,pbdBillID,pbhBillNo,CompanyTotalStock.pbhDepartmentID,--pbhBillDate,StockDate,
case when pbhBillDate is null then StockDate else pbhBillDate end pbhBillDate,
CompanyTotalStock.Due,pbhVendorID,ai.ItemID[pbdItemID],ItemCode,
ItemDescription,UnitsID,Brand,modelno,isnull(part_code,'''')part_code,
ItemCategoryID,PackingTypeID[pbdPackingtypeID],isnull(pbdItemQuantity,0)pbdItemQuantity,pbdItemUnitPrice,Stock ,OpeningStock FROM
(
select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,DepartmentID[pbhDepartmentID],sum(v.Stock)Stock,sum(v.OpeningStock)OpeningStock,op.StockDate[StockDate],
case when getdate() -op.StockDate between 0 and 30 then ''0 - 30''
when getdate() -op.StockDate between 30 and 180 then ''30 - 180''
when getdate() -op.StockDate between 180 and 365 then ''180 - 365''
when getdate() -op.StockDate between 365 and 700 then ''365 - 700''
when getdate() -op.StockDate >700 then ''>700'' end Due
from vwCompanyTotalStock v
inner join ashops on shopid=LocationID INNER JOIN mosshopstock op on LocationID=op.shopid and v.ItemID=op.ItemID
inner join aitempackingdetail p on p.itemid=v.ItemID
group by v.ItemID,v.companyId,LocationID,DepartmentID,StockDate,PackingTypeID
UNION ALL
select v.companyId[pbhCompanyID],v.ItemID,PackingTypeID,LocationID,DepartmentId[pbhDepartmentID],sum(Stock)Stock,sum(OpeningStock)OpeningStock,gsStockDate[StockDate],
case when getdate() -gsStockDate between 0 and 30 then ''0 - 30''
when getdate() -gsStockDate between 30 and 180 then ''30 - 180''
when getdate() -gsStockDate between 180 and 365 then ''180 - 365''
when getdate() -gsStockDate between 365 and 700 then ''365 - 700''
when getdate() -gsStockDate >700 then ''>700'' end Due
from vwCompanyTotalStock v
inner join agodown on GodownID=LocationID inner join moigodownstock op on LocationID=op.gsGodownID and v.ItemID=op.gsItemID
inner join aitempackingdetail p on p.itemid=v.ItemID
group by v.ItemID,v.companyId,LocationID,DepartmentId,gsStockDate,PackingTypeID
)CompanyTotalStock
left outer JOIN aItem ai ON ai.ItemID=CompanyTotalStock.ItemID
left outer join
(
select pbhCompanyID,pbdBillID,pbhBillNo,pbhDepartmentID,pbhBillDate,pbhVendorID,pbdItemID,pbdPackingtypeID,
pbdItemQuantity,pbdItemUnitPrice,
case when getdate() -pbhBillDate between 0 and 30 then ''0-30''
when getdate() -pbhBillDate between 30 and 180 then ''30 - 180''
when getdate() -pbhBillDate between 180 and 365 then ''180 - 365''
when getdate() -pbhBillDate between 365 and 700 then ''365 - 700''
when getdate() -pbhBillDate >700 then ''>700'' end Due
from losppurchasebilldetail INNER JOIN  losppurchasebillheader ON pbdBillID=pbhBillID AND
pbhCancelled=0 AND pbhDespatched=1
UNION ALL
--Local purchase
select lphCompanyID,lphBillID,lphBillNo,lphDepartmentID,lphBillDate,lphVendorID,lpdItemID,null,
lpdItemQuantity,lpdPOUnitPrice,
case when getdate() -lphBillDate between 0 and 30 then ''0-30''
when getdate() -lphBillDate between 30 and 180 then ''30 - 180''
when getdate() -lphBillDate between 180 and 365 then ''180 - 365''
when getdate() -lphBillDate between 365 and 700 then ''365 - 700''
when getdate() -lphBillDate >700 then ''>700'' end Due
from losLocalPurchaseDetail inner join LosLocalPurchaseHeader
on lpdBillID=lphBillID and lphCancelled=0
) BILLDETAILS
ON ai.ItemID=pbdItemID and CompanyTotalStock.pbhDepartmentID=BILLDETAILS.pbhDepartmentID'
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateLOUserRights]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateLOUserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
/*
Created by :  Shinu
Created on : 03/02/2007
Modified by :
Modified on :
Purpose      : To Update Local User Rights Table while Updating Local User Groups
*/
---------------
--Modified by :  vinothMurugan V.
--Date        :  19-04-2010
--purpose     :  louserrights,aloreportRights adding column in that sp.
---------------
CREATE Proc [dbo].[SpUpdateLOUserRights] @intuserGroupid as int,@intCompanyID as int as
Begin
Declare @intUserID as int
set nocount on
Declare UserCur cursor for
Select userid From lousers where usergroupid= @intuserGroupid and CompanyID=@intCompanyID
open UserCur
fetch next FROM UserCur into @intUserID
while @@Fetch_status = 0
begin
---Deleting From user Rights
Delete From louserrights where userid=@intUserID
--Inserting into user rights
--here adding proper column (UserID,ModuleCode,InterfaceID,FunctionRights,CompanyID)
insert into louserrights (UserID,ModuleCode,InterfaceID,FunctionRights,CompanyID) Select  @intUserID,ModuleCode,InterfaceID,FunctionRights,CompanyID
from loUsergrouprights where usergroupid=@intuserGroupid and companyid=@intCompanyID
--Deleting from Report Rights
delete from aloreportRights  where userid=@intUserID
--Inserting into from Report Rights
	--here adding proper column (userid,reportid,modulecode,Companyid)
insert into aloreportRights(userid,reportid,modulecode,Companyid) select @intUserID, reportid,modulecode,Companyid
from aloGroupreportrights where usergroupid= @intuserGroupid and companyid=@intCompanyID
fetch next FROM UserCur into @intUserID
end
Close UserCur
Deallocate UserCur
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillName]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 30/Sep/2010
--Created by	: Praveen S
--Comments	: For Updating the TillName In Till Header
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateTillName]
@tillid INT,
@tillname VARCHAR(50),
@tilloutletid INT,
@tillcompanyid INT,
@tillremarks varchar(250),
@tillactive BIT
AS BEGIN
	 SET NOCOUNT ON
	 UPDATE TillHeader
	 SET till_th_tillname = @tillname, till_th_remarks = @tillremarks,
	 till_th_active = @tillactive
	 WHERE till_th_tillid = @tillid AND
	 till_th_outletid = @tilloutletid AND
	 till_th_companyid 	= @tillcompanyid
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[vwapartmentrommcheckout]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwapartmentrommcheckout]'))
EXEC dbo.sp_executesql @statement = N'
--created by dheena
---created by date 06082003
CREATE view [dbo].[vwapartmentrommcheckout] as
select sername,serfururevc,mghAgreementno from losapartmentcheckout left outer join
losapartmentdetail on chcompanyid=apdcompanyid and
chApartmentid=apdApartmentid  and chShopid=apdShopid
left outer join losApartmentAgreementHeader
on chcompanyid=mghcompanyid and chAgreementID=mghAgreementID
and chShopid=mghShopid left outer join aservicemaster on
serservicetype=''r'' and mghcompanyid=sercompanyid and mghRateDetailId=serid
left outer join losreservationheader on
mghreservationid=rhreservationid and mghcompanyid=rhcompanyid and
mghshopid =rhshopid left outer join acustomermaster on
rhcustomerid=customerid and rhcompanyid=companyid'
GO
/****** Object:  View [dbo].[vwapartmentcheckdtls]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwapartmentcheckdtls]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  by 	: Dheena
--Created  date 	: 05092003
--purpose 	: apartment check out in details (report)
----------------------------------------------------------------
--Modified By 	: R Harikrishnan
--Modified on	: 26/09/2003
--Comments	: Changed the customer master link
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
----------------------------------------------------------------
CREATE view [dbo].[vwapartmentcheckdtls] as
select
	chid,apdApartmentid,apdApartmentno,chDate,chNo,mghAgreementid,mghAgreementno,
	CustomerID,CustomerName,Address1,Address2,Address3,chRemarks,chAvaliedAmount,chDepositAmount,
	spername,chShopID,chCompanyId,ChDepartmentID,Symbol,chCheckoutTime,chCancelled
from
	losapartmentcheckout
	left outer join aaccountmaster ac
	on chCashAccId=ac.accountid and chCompanyId=ac.companyid
	left outer join acurrencymaster cm
	on  ac.CurrencyID=cm.CurrencyID and cm.CompanyID=ac.CompanyID
	left outer join losapartmentdetail
	on chApartmentId=apdApartmentId and apdcompanyid=chCompanyId and apdShopid=chShopId
	left outer join losapartmentagreementheader
	on mghcompanyid=chCompanyId and mghShopid=chShopId and mghAgreementid=chAgreementid
	left outer join losreservationheader
	on rhreservationid=mghReservationID and rhcompanyid= mghcompanyid and rhshopid= mghcompanyid
	left outer join acustomermaster cu on chcustomerid=cu.customerid
	and chCompanyID=cu.CompanyID
	,aSalesPersonmaster where Sperid=chenteredby'
GO
/****** Object:  View [dbo].[vwArrivalToGodownFromShop]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwArrivalToGodownFromShop]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwarrivaltogodownfromshop    Script Date: 18/01/2003 9:45:35 PM ******/
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified on 	        : 12/12/02
--Modified by		: leo
--Comments		: v3
--------------------------------
-- Modified on          : 19/12/02
-- Modified by          : Kishore
-- Comments             : Added LocationArrangement Column
----------------------------------------------------------
CREATE VIEW [dbo].[vwArrivalToGodownFromShop] AS
SELECT g.godownname, s.shopname, h.ahArrivalno, dh.dghno,
h.ahArrivaldate, h.ahArrivalid,
sh.sshipmentno, h.ahlocalgodownid, h.ahshopid, h.ahtransfinished,
h.ahcancelled, h.ahremarks,
d.asditemid, d.asdDespatchedGoodQty, d.asdReceivedGoodQty,
asdcostprice, asdShipmentID, g.LocationArrangement
FROM loiArrivalHeader h, loiArrivalShipmentDetail d,
mesDespatchToGodownHeader dh, aShops s, aGodown g, aItem a, aShipment sh
WHERE h.ahArrivalid = d.asdArrivalid
and h.ahlocalgodownid = d.asdgodownid
and h.ahdespatchnoteid = dh.dghid
and h.ahshopid = dh.dghshopid
and d.asditemid = a.itemid
and h.ahshopid = s.shopid
and h.ahlocalgodownid = g.godownid
and d.asdshipmentid = sh.sshipmentid'
GO
/****** Object:  View [dbo].[vwAssetTransferHistory]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetTransferHistory]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwAssetTransferHistory]
as
select
	FixedAssetID, FixedAssetDate transdate, PurchaseDate,CostPrice, fa.DepartmentID,
	InsuredAmount,Premium, 0 transid, fa.companyid,'''' RefernceNo, 0 frdepid, 0 todepid, assetname,
	isnull(fat.departmentname, d.departmentname) depf, '''' dept,asttranscancelled
from
	adepartmentmaster d, fixedasset fa left outer join
	(select  asttranscompanyid ,asttransassetid, departmentname,at1.asttranscancelled from  assettransfer at1,
	adepartmentmaster where asttransfromdepid = departmentid and asttransid =
	(select min(asttransid) transid from assettransfer at2 where
	at2.asttransid = at1.asttransid and at2.asttranscompanyid = at1.asttranscompanyid and
	at2.asttransassetid = at1.asttransassetid)) fat on
	fa.FixedAssetID = fat.asttransassetid and fa.CompanyID  = fat.asttranscompanyid
where
	d.departmentid = fa.departmentid  and d.companyid = fa.companyid
union all
select
	FixedAssetID,asttransdate, PurchaseDate,asttransvalue, c.DepartmentID,
	InsuredAmount,Premium,asttransid,asttranscompanyid,asttrransno,
	asttransfromdepid,asttranstodepid,assetname ,
	a.departmentname fromdepartment ,b.departmentname todepartment,
	case when asttranscancelled=0 then 0 else  1 end cancelled
from
	fixedasset c left outer join adepartmentmaster d on d.DepartmentID=c.DepartmentID
	and d.CompanyID=c.companyid , assettransfer
	left outer join adepartmentmaster a on a.DepartmentID=asttransfromdepid
	and a.CompanyID=asttranscompanyid
	left outer join adepartmentmaster b on b.DepartmentID=asttranstodepid
	and a.CompanyID=asttranscompanyid
where
	asttransassetid= FixedAssetID and asttranscompanyid=c.CompanyID
group by
	FixedAssetID,FixedAssetDate,PurchaseDate,
	CostPrice,c.DepartmentID,d.departmentname  ,
	InsuredAmount,Premium,asttransid,
	asttranscompanyid,asttrransno,asttransdate,
	asttransfromdepid,asttranstodepid,asttransvalue ,assetname ,
	a.departmentname  ,b.departmentname,case when asttranscancelled=0 then 0 else  1 end'
GO
/****** Object:  View [dbo].[vwAssetTransfer]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetTransfer]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- last modified by    : Kishore
-- Modified on         : 10/01/2003
--		       : Added the fromaccount and to account(23/02/2004) venki		
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE VIEW [dbo].[vwAssetTransfer] AS
select
	asttransid, asttranscompanyid, asttrransno, asttransdate,
	asttransfromdepid, asttranstodepid, asttransvalue, assetname,
	a.departmentname fromdepartment, b.departmentname todepartment,
	asttranscancelled, UpdateTime, cm.Symbol CurrencySymbol,
	FromAssetAccId,ToAssetAccID ,acc1.accountdesc Fromaccount,acc2.accountdesc Toaccount
from
	fixedasset c, assettransfer
	left outer join aaccountmaster acc1
	on asttranscompanyid = acc1.companyid
	and FromAssetAccId = acc1.accountid
	left outer join aaccountmaster acc2
	on asttranscompanyid = acc2.companyid 	
	and ToAssetAccID = acc2.accountid
	left outer join adepartmentmaster a
	on asttransfromdepid  = a.DepartmentID
	and asttranscompanyid  = a.CompanyID
	Left Outer Join aCurrencyMaster cm on
	a.DepCurrencyId = cm.CurrencyId and
	a.CompanyId = cm.CompanyId
	left outer join adepartmentmaster b
	on asttranstodepid = b.DepartmentID
	and asttranscompanyid = a.CompanyID
where
	asttransassetid = FixedAssetID
	and asttranscompanyid = c.CompanyID'
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateBPWCStock]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateBPWCStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By  : Benzigar S D
-- Date : 23/09/2008
-- Comments : V4
-- TO update stock table when transaction is saved in Warreny Claim/Business Promotion
-- sales transaction
CREATE PROC [dbo].[SpUpdateBPWCStock](@intWCBPID int,
@intShopID int,
@process char(1)) AS
Begin
declare
@cur_wcdID int,
@cur_Shopid int,
@cur_itemid int,
@cur_itemQty numeric(18, 3),
@intCount int
set nocount on
declare cursor_Detail  cursor for
select wcdID, wcdShopID, wcdItemID, wcdQty
from losWarrentyClaimDetail
where wcdID = @intWCBPID and wcdShopID = @intShopID
open cursor_Detail
fetch next from cursor_Detail into
@cur_wcdID, @cur_Shopid, @cur_itemid,
@cur_itemQty
while @@fetch_status = 0
begin
if @process = ''R''
Begin
update mosShopStock set stock = stock + @cur_itemQty
where itemid = @cur_itemid and shopid = @cur_Shopid
End
if @process = ''F''
begin
select @intCount = count(*) from mosShopStock
where itemid = @cur_Itemid and shopid = @intShopid
if @intCount =0
Begin
insert mosShopStock (ShopID, StockDate, ShipmentID, ItemID,
OpeningStock, Stock, OpeningBadStock, BadStock)
Select @intShopid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
End
update mosShopStock set stock = stock - (@cur_itemQty)
where itemid = @cur_itemid and shopid = @cur_Shopid
end
fetch next from cursor_Detail into
@cur_wcdID, @cur_Shopid, @cur_itemid,
@cur_itemQty
end
close cursor_Detail
deallocate cursor_Detail
return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlShopSWO]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopSWO]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------
-- Last Modified on : 17/07/02
-- modified by 	    : leo
--------------------------------------
-- Modified on      : 03/01/2002
-- Modified by      : Kishore
-- Comment          : Added code to insert dep amount and to convert amount
--------------------------------------
-- Last Modified on : 07/06/2003
-- Last Modified by : R Harikrishnan
-- Comments	    : Added the whtype check in where part of the cursor
--------------------------------------
CREATE proc [dbo].[spUlShopSWO]
	@intCompanyId as int, @intShop as int
as
begin
	Declare
	@intJournalId as int,
	@intJournalDetailId as int,
	@intswoId as int,
	@intFinancialId as int,
	@strswoNo as varchar(50),
	@dtswoDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentId as int,
	@numswoAmt as numeric(18,2),
	@intCompanyCurId as int,
	@intinventoryaccId as int,
	@intSwoAccId 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
	
	-- hari included to get the departmentId for the Shop
	select @intSwoAccId = stockWriteoffAccId
		from aShops where ShopId = @intShop
	select @intinventoryaccId = InventoryId,
		@strzerorate = substring(isnull(futurevc,''''),1,1) from apackagesettings
	/* getting the maximum Journal Id FROM journal table */
	select @intJournalId = isnull(max(JournalId),0) from moaJournalHeader
		where CompanyId = @intCompanyId
	set @intJournalId = @intJournalId + 1
	Declare swoCur cursor for
		SELECT whId, whno, whdate,  whremarks, updatetime, whdepartmentId,
		whConExRate, whDepExRate, whExchangeRates
		FROM loswriteoffheader
		WHERE whcancellED =0 and whShopId = @intShop and whposted =0
		and whType=''W''
	open swoCur
	fetch next FROM  swoCur into @intswoId, @strswono,
		@dtswoDate, @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 @dtswoDate between sdate and edate
		-- to check the no of records with item rate =0 or null in both the detail table
		-- and the item master table. If so we cannot do any thing in the posting with out item rate.
		-- so that transaction will be avoIded from posting
		-- hariharan 011211
		set @intFailcount = 0
		select @intFailcount = count(*) from losWriteOffDetail, aitem where
			WdId = @intswoId and wdShopId = @intShop and WdItemId = itemId
			and ( wdcostprice =null or wdcostprice = 0) and (itemrate=0 or itemrate is null)
		-- to allow to proceed if allow zero rate condition given - hari 020905
		if @strzerorate = ''z''
		begin
		 	set @intfailcount=0
		end
		if @intfailcount = 0 -- for item rate = 0 check hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update losWriteOffDetail set wdcostprice = itemrate from
				aitem where ( wdcostprice =null or wdcostprice = 0) and wdId = @intswoId
				and wdShopId = @intShop and WdItemId = itemId
			insert into moaJournalHeader (JournalId, CompanyId, JournalDate,
				referenceno, remarks, financialId, Type, CurrencyId,chequedate, updatetime )
				values (@intJournalId, @intCompanyId, @dtswoDate, @strswono,
				@strRemarks, @intFinancialId, ''sswo'', @intcompanycurId, @dtswoDate, @dtutime )
			set @intJournalDetailId = 1
			-- getting the total amount with qty and item cost price
			select @numswoAmt = isnull(sum(wdwriteoffqty * wdcostprice),0)
				from losWriteOffDetail swod
				where wdShopId = @intShop and wdId = @intswoId
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intSwoAccId
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numSwoAmt,
					@numAaccAmt output
			-- debiting hte stock writeoff accId
			insert into moaJournalDetails (JournalId, journaldetailId, CompanyId,
				JournalCrEDit, AccountId, Amount, actualAmount,
				DepAmount, departmentId)
				values
				(@intJournalId, @intjournalDetailId, @intCompanyId, 0,
				@intSwoAccId,
				@numswoAmt * @numConExRate, @numaAccAmt,
				@numSwoAmt * @numDepExRate, @intdepartmentId)	
			set @intJournalDetailId = @intJournalDetailId + 1
			-- credit the inventory acc Id
			insert into moaJournalDetails (JournalId, journaldetailId, CompanyId,
				JournalCrEDit, accountId, Amount, ActualAmount,
				DepAmount, departmentId)
				values
				(@intJournalId, @intjournalDetailId, @intCompanyId, 1,
				@intinventoryaccId, @numswoAmt * @numConExRate,
				@numSwoAmt, @numSwoAmt * @numDepExRate,
				@intdepartmentId )
			update loswriteoffheader set whposted = 1
				WHERE WhId = @intswoId and whShopId = @intShop
			set @intJournalId = @intJournalId + 1	
		end -- for item rate=0 check hari 011213
		fetch next FROM  swoCur into @intswoId, @strswono, @dtswoDate,
			@strRemarks, @dtutime, @intDepartmentId, @numConExRate,
			@numDepExRate, @strExRates
	end	-- CUR END
	Close swoCur
	Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlShopSv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopSv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** 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
-----------------------------------------
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 = @intShop
		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 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownarrival]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownarrival]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.SpUpdateGodownarrival    Script Date: 18/01/2003 9:45:46 PM ******/
--Created By : Hariharan
--Verififed by : Hariharan
-- Date	: 03/01/2003
CREATE proc [dbo].[SpUpdateGodownarrival]( @Arrivalid int,
@Godownid int,@Type char(1) ) as
declare
@cur_arrivalid int,
@cur_godownid int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_packingtypeid int,
@cur_cost numeric(18,2),
@cur_ShipmentID int,
@recCount as int
set nocount on
if @Type=''h''
	declare cursor_Detail  cursor for
	select adarrivalid, adgodownid, aditemid, adReceivedQty, adpackingtypeid,
	adcostprice, 1 from LoiArrivalDetail
	where adArrivalID = @Arrivalid and adgodownid = @Godownid
else
	declare cursor_Detail  cursor for
	select asdarrivalid, asdgodownid, asditemid, asdReceivedGoodQty, 1,
	asdcostprice, asdshipmentid from LoiArrivalShipmentDetail
	where asdArrivalID = @Arrivalid and asdgodownid = @Godownid
open cursor_Detail
fetch next from cursor_Detail into
@cur_arrivalid, @cur_godownid, @cur_itemid,
@cur_itemgoodqty, @cur_packingtypeid, @cur_cost, @cur_ShipmentID
while @@fetch_status = 0
begin
	if @Type = ''h''
		select @cur_itemgoodqty = @cur_itemgoodqty * quantity * Counts from
		aitem ai, apackingtypecapacitydetail pk, aunit au where
		ai.itemid = @cur_Itemid and ai.unitsid = au.unitid and
		au.unitid = pk.unitsid and pk.packingtypeid = @cur_packingtypeid		
		select @recCount = count(*) from moigodownstock where gsitemid = @cur_itemid
		and gsgodownid = @cur_Godownid
		if @recCount =0
			insert moigodownstock(gsGodownID, gsShipmentID, gsItemID, gsStock,
			gsItemCost, gsstockdate) select @cur_GodownID, 1, @cur_ItemID,
			@cur_itemgoodqty,@cur_Cost, getdate()
		else
			update moigodownstock set gsstock = gsstock + @cur_itemgoodqty
			where gsitemid = @cur_itemid and gsgodownid = @cur_godownid
	fetch next from cursor_Detail into
	@cur_arrivalid, @cur_godownid, @cur_itemid,
	@cur_itemgoodqty, @cur_packingtypeid, @cur_cost,@cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULWarrentyClaim]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULWarrentyClaim]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--exec spULWarrentyClaim  1,2
--Created on   : 10/09/2008
--Created by  : Prasanth Joseph
--Comments  : For Posting add WarrentyClaim Transactions
--RefNo1: Added by MANUNADH.U on 03.06.2011 for the Ticket: ZES-242125
--to post only confirmed BusinessPromotion
---------------------------------------------------------------------
CREATE proc [dbo].[spULWarrentyClaim]
@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,
@intWCAcc   as int,
@intcomdeptid    as int,
@intCurrencyId    as int,
@intCustomerAccID   as int,
@numTotatRecAmount  as NumEric(18,2),
@strReceipteNo    as varchar(50),
@strRemarks    as varchar(250),
@dtReceiptDate    as datetime,
@dtutime    as datetime
,@numWCAmt as numeric(18,2) --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 @intWCAcc =WarrentyClaimAcc ,@intinventoryaccid=InventoryID
from apackagesettings where companyid = @intcompanyid
set @intJournalId = @intJournalId + 1
Declare invcur cursor for
SELECT wchID,wchNo,wchDate,null,wchRemarks,wchFinancialID,wchUpdatedTime,wchAmount
FROM losWarrentyClaimHeader
WHERE wchType=''WC'' 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,''WC'', @intcomCurID,@dtReceiptDate, @dtutime)
--HPSDP=Hire Purchase Shop Down Payment
set @intJournalDetailId = 1
--===========================================================================RefNo1
	-- getting the total amount with qty and item cost price
select @numWCAmt = 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 , @numWCAmt,
@numWCAmt,@intDepartmentID,@numWCAmt, 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, @intWCAcc,
@numWCAmt, @numWCAmt,@intDepartmentID, @numWCAmt, 1)
UPDATE
losWarrentyClaimHeader  set wchPosted=1
WHERE
wchShopID=@intShopId and wchCompanyID=@intCompanyID
and wchType=''WC'' 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
/****** Object:  StoredProcedure [dbo].[spUlShopDespToGodown]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopDespToGodown]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on 	: 17/07/2002
-- Created by	: leo
-----------------------------------------------------------------------
-- Modified on  : 02/01/2003
-- Modified by  : Kishore
-- Comments     : Added code to insert depAmount and to convert amount
--verified by hariharan on 07/01/2003
-----------------------------------------------------------------------
--Last Modified on 	: 06/06/2003
--Last Modified By	: R Harikrishnan
--Comments		: Added if checking totalcostvalue > 0
-----------------------------------------------------------------------
CREATE proc [dbo].[spUlShopDespToGodown]
	@intCompanyId as int, @intShopId as int
as
begin
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dttDate as datetime
	Declare @strtNo as varchar(50)
	Declare @inttid as int
	Declare @strRemarks as varchar(250)
	Declare @numTotalValue as numeric(18,2)
	Declare @intinventoryaccid as int
	declare @intcomcurid as int
	declare @inttodepid as int
	declare @dtutime as datetime
	declare @intFailcount as int
	declare @intStockTransferAccId  as int
	declare @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)
	set @numDepExRate = 0.00
	set @numConExRate = 0.00
	set @intCurrencyId = 0.00
	set @strExRates = 0.00
	set @numAccExRate = 0.00
	set @numTransEr = 0.00
	set @numAaccAmt = 0.00
	/* 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 @intInventoryaccid = inventoryid, @intStockTransferAccId =
		stocktransfercontrolacc, @strzerorate = substring(isnull(futurevc,''''),1,1)
		from apackagesettings where CompanyId = @intCompanyId
	set @intJournalID = @intJournalID + 1
	
	Declare trincur cursor for
		SELECT dgHID, dgHDate, dgHNO, dgHremarks, dghdepartmentid todep,
		updatetime, dghConExRate, dghDepExRate, dghExchangeRates
		FROM mesDespatchToGodownHeader tinh
		WHERE  dgHcancelled = 0 and dgHPosted = 0 and dgHShopId = @intShopId
		and dgHTransFinished = 1
	open trincur
	fetch next FROM trincur into @inttid , @dttdate, @strtno, @strremarks, @inttodepid,
		@dtutime, @numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0
	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 @dttdate 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 mesdespatchtogodowndetail , aitem
			where dgdid= @inttid and dgdShopId = @intShopId and dgditemid = itemid
			and (dgdcostprice=null or dgdcostprice=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 	-- item rate=0 check hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update mesdespatchtogodowndetail set dgdcostprice = itemrate from
				aitem where (dgdcostprice=null or dgdcostprice=0) and dgdid= @inttid
				and dgdShopId = @intShopId and dgditemid = itemid
			SELECT @numTotalValue = sum(dgdDespatchedGoodQty * dgDCostprice)
				FROM mesdespatchtogodowndetail  WHERE dgdShopId  = @intShopId and
				dgdID = @inttid group by dgdShopId, dgdID
			if @numTotalValue<>0
			begin
				insert into moaJournalHeader (JournalID, CompanyId, JournalDate,
					referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
					(@intJournalID, @intCompanyId, @dttDate, @strtNo,
					@strremarks, @intFinancialID,''sdtog'', @intcomCurID,@dttdate, @dtutime)
				set @intJournalDetailID = 1		
				/* debiting the inventory account with the full */
				insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
					JournalCrEDit, AccountID, Amount, actualAmount,
					DepAmount, DepartmentId)
				values (@intJournalID, @intjournalDetailID, @intCompanyId, 1,
					@intInventoryaccid, @numTotalValue * @numConExRate, @numTotalValue,
					@numTotalValue * @numDepExRate, @inttoDepID )		
				set @intJournalDetailID = @intJournalDetailID + 1		
				-- for converting the amount --->
				select @intCurrencyId = CurrencyId
				from aAccountMaster
				where AccountId = @intStockTransferAccId
				exec spReturnExRate @intCurrencyId, @strExRates,
				@numAccExRate output
				exec spConvertCurrency @numTransEr, @numAccExRate,
				@numTotalValue,
				@numAaccAmt output
				/* debiting the inventory account with the full */
				insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
					JournalCrEDit, AccountID, Amount, ActualAmount,
					DepAmount, DepartmentID)
				values (@intJournalID, @intjournalDetailID, @intCompanyId, 0,
					@intStockTransferAccId, @numTotalValue * @numConExRate,
					@numaAccAmt,
					@numTotalValue * @numDepExRate,
					@inttoDepID)			
				set @intJournalID = @intJournalID + 1
			
			end
			/* mark the record as postED */
			update mesDespatchToGodownHeader  set dgHPosted = 1
			WHERE dghShopId = @intShopId and dgHID = @inttid
		end -- item rate=0 check hari 011213
		fetch next FROM trincur into @inttid, @dttdate, @strtno, @strremarks,
			@inttodepid, @dtutime, @numConExRate, @numDepExRate, @strExRates
	end
	Close trincur
	Deallocate trincur	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULInvSplDesp]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvSplDesp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------
-- Modified on    : 07/01/2002
-- Modified by    : Hariharan R
-- Comments       : Added code to insert depamount and to convert amount
-- Verified by Hariharan on 07/01/2003
------------------------------------------------------------------------------------------------
-- Last Modified on  : 07/06/2003
-- Last Modified By : R Harikrishnan
-- Comments  : Removed the cost of goods
------------------------------------------------------------------------------------------------
-- RefNo-3
-- Last Modified on  : 08/04/2010
-- Last Modified By : Regin T.
-- Comments  : Inventory currency was assumed as Trans currecy. But trans figures are in either
-- cash acc curr (cash inv) or customer curr (credit inv). Above assumption will not work
-- if the cash acc curr or customer curr is different from Inventory curr.
-- So trans curr is fetched from special invoice.
------------------------------------------------------------------------------------------------
create  proc [dbo].[spULInvSplDesp]
@intCompanyID as int, @intGodownId as int
as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intsdid as int,
@intFinancialID as int,
@strsdNo as varchar(50),
@dtsdDate as datetime,
@strRemarks as varchar(500),
@intDepartmentId as int,
@numSdAmt as numeric(18,2),
@intCompanyCurID as int,
@intinventoryaccid as int,
@intcogid as int,
@dtutime as datetime,
@intFailcount as int,
@intStockTransferAccId as int,
@intFromDepartmentId as int,
@intfromshop 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),
@numDepAmt Numeric(18,2),
@bitCashInvoice as bit,
-- below variables were declared for RefNo-3
@intInvoiceId as int,
@intShopId as int,
@intCashAccId as int,
@intCustomerId as int,
@strInvExRates as nvarchar(250),
@strCurrIDs as nvarchar(50),
@intExRateFound as int
--get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM aCompanyMaster WHERE CompanyID = @intCompanyID
select @intinventoryaccid = InventoryID, @intcogid = CostofGoodsid, @intStockTransferAccId =
stocktransfercontrolacc, @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 sdcur cursor for
SELECT dhDespatchId, dhdespatchno, dhdespatchdate,
dhRemarks, updatetime, dhDepartmentId, dhShopId,
dhConExRate, dhDepExRate, dhExchangeRates, dhIssueNoteId, dhShopID
FROM meiSpecialDespatchToShopHeader WHERE dhCancelled = 0
and dhGodownId = @intGodownId and dhposted = 0
open sdcur
fetch next FROM  sdcur into @intsdid, @strsdno, @dtsdDate, @strRemarks,
@dtutime, @intDepartmentId, @intfromshop, @numConExRate,
@numDepExRate, @strExRates, @intInvoiceId, @intShopId
while @@Fetch_status = 0
begin -- cur begin
-- RefNo-3 starts here
-- Old code commented below
-- select @intCurrencyId = CurrencyId
-- from aAccountMaster a
-- where a.AccountId = @intInventoryAccId
-- and CompanyId = @intCompanyId
-- In Cash Special Invoice, trans figures are in Cash Account Currency.
-- In Credit Special Invoice, trans figures are in Customer Currency.
-- Below code is to determine the currency of the transaction.
select @bitCashInvoice = ihcashinvoice, @intCashAccId = ihbankcashaccId,
@intCustomerId=IhCustomerID, @strInvExRates=ihexchangerates
from losspecialinvoiceheader where
ihShopId = @intShopId  and IhInvoiceId = @intInvoiceId
-- If Cash Invoice, Cash Account Currency is the trans currency.
if @bitCashInvoice=1
begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCashAccId
end
-- If Credit Invoice, Customer Currency is the trans currency.
else
begin
select @intCurrencyId = CurrencyID
from aCustomerMaster
where CustomerID = @intCustomerId
end  -- end of [ELSE of IF @bitCashInvoice=1]
-- dhexchangerates field of meiSpecialDespatchToShopHeader
-- may not have the exchange rate of customer currency or cash account currency.
-- To check if exchange rate found in Special Despatch table.
-- @intCurrFound will hold 0 if ex rate not found, a nonzero value otherwise.
set @strCurrIDs = '':'' + substring(@strExRates,1, charindex(''-'',@strExRates,1) - 1)
set @intExRateFound = charindex('':''+convert(nvarchar,@intCurrencyId)+'':'', @strCurrIDs, 1)
-- In no exchange rate found in Special Despatch table,
-- exchange rate is fetched from Special Invoice table.
if @intExRateFound <> 0
exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output
else
exec spReturnExRate @intCurrencyId, @strInvExRates, @numTransEr output
-- RefNo-3 ends here
--to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtsdDate 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
select @intFromDepartmentId = DepartmentId from ashops where ShopId = @intfromshop
set @intFailcount = 0
select @intFailcount = count(*) from meiSpecialDespatchToShopDetail, aItem
where ddDespatchid = @intsdid and ddGodownId = @intGodownId and ddItemId = ItemId
and (ddCostedPrice=null or ddCostedPrice=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 check hari 011213
begin
-- to update the item rate to the gadcostprice
update meiSpecialDespatchToShopDetail set ddCostedPrice = itemrate
from aItem
where ( ddCostedPrice =null or ddCostedPrice =0)
and ddDespatchid = @intsdid
and ddGodownId = @intGodownId and ddItemId = ItemId
insert into moaJournalHeader (JournalID, CompanyID,
JournalDate, referenceno, remarks,
financialID, Type, CurrencyID,chequedate,updatetime)
values (@intJournalID, @intCompanyID,
@dtsdDate, @strsdno, @strRemarks, @intFinancialID,
''ispd'', @intCompanyCurId, @dtsdDate, @dtutime)
set @intJournalDetailID = 1
--getting the total amount with qty and item cost price
select @numSdAmt = isnull(sum(ddItemGoodQty * ddCostedPrice),0)
from meiSpecialDespatchToShopDetail
where ddGodownId = @intGodownId and ddDespatchid = @intsdid
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSdAmt,
@numAaccAmt output
-- debiting the stock transfer control account of godown
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID,
Amount, actualAmount, DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID, @intCompanyID,
0, @intStockTransferAccId, @numSdAmt * @numConExRate, @numAaccAmt,
@numSdAmt * @numDepExRate,
@intDepartmentId)
set @intJournalDetailID = @intJournalDetailID +1
-- credit the inventory acc id of godown
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, accountid,
Amount, actualamount, DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intinventoryaccid, @numSdAmt * @numConExRate,
@numSdAmt, @numSdAmt * @numDepExRate, @intDepartmentId )
update meiSpecialDespatchtoshopHeader set dhposted = 1
WHERE dhdespatchid = @intsdID and
dhGodownId = @intGodownId
set @intJournalID = @intJournalID + 1
end -- for item rate check hari 011213
fetch next FROM  sdcur into @intsdiD, @strsdno, @dtsdDate,
@strRemarks, @dtutime,
@intDepartmentId, @intfromshop, @numConExRate,
@numDepExRate, @strExRates, @intInvoiceId, @intShopId
end -- CUR END
Close sdcur
Deallocate sdcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULBusinessPromotion]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULBusinessPromotion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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-1
--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
---------------------------------------------------------------------
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,2),
@strReceipteNo    as varchar(50),
@strRemarks    as varchar(250),
@dtReceiptDate    as datetime,
@dtutime    as datetime
,@numBPAmt as numeric(18,2) --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-1   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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULshopPayments]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopPayments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on		: 18/07/2002
-- Modified by		: leo
--------------------------------------------------------------------
-- Last Modified on	: 05/06/2003
-- Modified by		: R Harikrishnan
-------------------------------------------------------------------
CREATE proc [dbo].[spULshopPayments]
	 @intCompanyID as int, @intshop as int
as
begin
Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intpaymentid as int,
	@intFinancialID as int,
	@strPaymentNo as varchar(50),
	@dtPaymentDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentID as int,
	@numPaymentAmt as numeric(18,2),
	@intDebitAccID as int,
	@intCompanyCurID as int,
	@intbankcashid as int,
	@dtutime as datetime,
	@strExRates as varchar(250),
	@numDepExRate as numeric(18,5),
	@numConExRate as numeric(18,5),
	@numAaccAmt as numeric(18,2)
	--get the companyCurrencyID
	SELECT @intCompanyCurID = CurrencyID FROM acompanymaster WHERE CompanyID = @intCompanyID
	
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
	WHERE CompanyID = @intCompanyID
	set @intJournalID = @intJournalID + 1
	Declare PayCur cursor for
	SELECT phPaymentID, phpaymentno, phpaymentdate,  phremarks ,phAmount, phfinancialID, phDebitAccountID,
	phbankcashid,updatetime, phDepartmentID,phExchangeRate,phdepexrate,phexchangerates FROM LOsPaymentVoucherHeader WHERE
	phpostED =0 and phCompanyID = @intCompanyID and phcancellED =0 and
	phshopid = @intshop
	open paycur
	fetch next FROM  PayCur into @intPaymentID, @strPaymentno, @dtPaymentDate, @strRemarks,
	@numPaymentAmt, @intFinancialID, @intdebitaccid, @intbankcashid, @dtutime, @intDepartmentID,
	@numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0	
	begin	-- paycur begin
			insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
			referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
			values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
			@strRemarks, @intFinancialID, ''spmt'', @intcompanycurID,@dtpaymentdate, @dtutime )
			set @intJournalDetailID = 1
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID) values
			(@intJournalID,
			@intjournalDetailID, @intCompanyID, 1, @intBankCashID,
			@numpaymentamt * @numConExRate, @numPaymentAmt ,
			@numPaymentAmt* @numDepExRate, @intdepartmentid )	
			set @intJournalDetailID = @intJournalDetailID +1
			exec spConvertequiamount  @intBankCashID, ''a'', @intdebitaccid, ''a'',
			@strExRates, @numPaymentAmt, @numAaccAmt output, ''''		
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
			JournalCrEDit, accountid, Amount, actualamount,DepAmount, departmentid) values
			(@intJournalID, @intjournalDetailID,
			@intCompanyID, 0, @intdebitaccid, @numPaymentAmt * @numConExRate,
			@numAaccAmt, @numPaymentAmt * @numDepExRate ,@intdepartmentid )
		update losPaymentVoucherHeader set phpostED =1 WHERE phPaymentID =
		@intPaymentID and phCompanyID = @intCompanyID and phshopid=@intShop
		set @intJournalID = @intJournalID + 1	
		fetch next FROM  PayCur into @intPaymentID, @strPaymentno, @dtPaymentDate, @strRemarks,
		@numPaymentAmt, @intFinancialID, @intdebitaccid, @intbankcashid, @dtutime, @intDepartmentID,
		@numConExRate,@numDepExRate,@strExRates
	end	-- PAYCUR END
	Close payCur
	Deallocate payCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULSaleInv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSaleInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified on   : 29/03/2004
--Modified by  : Hariharan R
--Comments  : Other charges changes
--   : Added customs duty Posting option
--   : ReInitialised other charges variable
--   : @chrShopType=''B'' included in custom duty posting condition
--   : as in transaction level the custom duty figure is saved
------------------------------------------------------------------------------
--RefNo-2
-- Modified on      : 2-12-2010 , 24/09/2011,04/10/11,19/11/11,22/11/11 ,07/01/2012
-- Modified by      : Nidheesh P V   ,Jyothish
-- Comments         : Added the part of GST
--,Comments          : post group id added
--commets            : tax amount set 0 RefNo-5
------------------------------------------------------------------------------
--RefNo-3
--Modified on  : 25/01/2012
--Modified by  : Bijesh.B
--Ticket Id    : CYI-281165
--Comments     : Null Handled  (Other charges is not tallying)
------------------------------------------------------------------------------
--RefNo-4
--Modified on  : 19/04/2012
--Modified by  : MANUNADH. U
--Comments     : Change the precision of numeric variables from 2 to 9 for the
--				 Task No: M_111 and M_112 specified in the Magnolia Issue Tracking System
------------------------------------------------------------------------------
CREATE proc [dbo].[spULSaleInv]
@intCompanyID as int,
@intShopId as int
as
begin
Declare @intSalesAccountID as int,@intCashAccountID as int,@intJournalId as int,@intJournalDetailId as int,
@intFinancialID   as int,@intInvoiceId    as int,@intCustomerId    as int,@intDiscountAccountID   as int,
@intOtherChargesAccountID  as int,@intDepartmentID   as int,@intComCurID    as int,@intinventoryaccid   as int,
@intCostOfGoodsAccId   as int,@intPlTransAccId   as int,@intcomdeptid    as int,@intCurrencyId    as int,
@intcomprofitaccid   as int,@intCustomsDutyID   as int,--R Harikrishnan for Customs Duty Posting
@numtotalinvValue as NumEric(18,2),@numTotalDiscountValue as NumEric(18,2),@numTotalCostValue as NumEric(18,2),
@numTotalOCValue   as NumEric(18,2),@depsalesval    as NumEric(18,2),@depcostval    as NumEric(18,2),
@numTransEr as NumEric(18,2),@numAccEr as NumEric(18,2),
@numAaccAmt as NumEric(18,9),--<<RefNo-4>>
@NumDepAmt as NumEric(18,2),@numCustomsDutyAmt   as NumEric(18,2),--R Harikrishnan for Customs Duty Posting
@numSalesValue as NumEric(18,2),@depExRate as NumEric(28,8),@NumEr as NumEric(28,8),
@numProfitTrans as NumEric( 7,5),@strExRates    as varchar(250),@strinvoiceNo    as varchar(50),
@strRemarks    as varchar(250),@chrCustomsDutyPaidType  as char(1),--R Harikrishnan for Customs Duty Posting
@chrShopType   as char(1),--R Harikrishnan for Customs Duty Posting
@dtinvoiceDate    as datetime,@dtutime    as datetime
--RefNo-2-added for gst--
--<<RefNo-4>>--START
declare @IntCount as int,@TaxCurrId as int,@numTaxEr as numeric(18,9),@TaxAcntId as int,@TaxCatId as int,
@TaxAmount as numeric(18,9),@CTaxAmount as numeric(18,9),@DTaxAmount as numeric(18,9),
@TaxAccAmount as numeric(18,9),@CTotalTaxAmount as numeric(18,9),@DTotalTaxAmount as numeric(18,9),
@TotalTaxAmnt as numeric(18,9),@TotalAccTax as numeric(18,9),@IntServTaxAccnt as integer,
@IntServTaxAccntCurrID as integer,@numOCTaxAmount as numeric(18,9)
-----------------------------
declare  @Taxtable table (
taxTransId int,
taxShopId int,
taxAccntId int,
taxAmount numeric(18,9),
CtaxAmount numeric(18,9),
DtaxAmount numeric(18,9)
)
--<<RefNo-4>>---END
--RefNo-2-added for gst--
SET NOCOUNT ON
--RefNo-2---to insert tax cateid,tax A/C & tax amount in the table variable---
insert into @Taxtable
select ihInvoiceId,ihShopID,TaxAccountId,isnull(sum(idItemTaxAmount),0)as TaxAmount,
sum(isnull(idItemTaxAmount,0)* ihexchangerate) as ComTaxAmount,
sum(isnull(idItemTaxAmount,0)* ihdepExRate) as DepTaxAmount
FROM losinvoiceheader ih
inner join losinvoicedetail id on ih.ihInvoiceId = id.idInvoiceId and ih.ihShopID = id.idShopID
inner join ataxcategorymaster tc on TaxCompanyId=ih.ihCompanyId and idItemTaxCategory=TaxId
and TaxCancelled=0 and TaxAccountable=1
WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 AND ihcashinvoice =0 and ihtype =''i''
and isnull(idItemTaxCategory,0)<>0 and isnull(TaxPercentage,0)<>0 and ih.ihCompanyId = @intCompanyID
and ih.ihShopID = @intshopid
group by  TaxAccountId,ihInvoiceId,ihShopID
---RefNo-2----
/* getting the defaults into the variables */
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalId = isnull(max(JournalId),0) FROM moaJournalHeader WHERE CompanyID = @intCompanyID
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
set @numTotalDiscountValue = 0.0
set @numTotalOCValue = 0.0
set @numCustomsDutyAmt = 0.0 --R Harikrishnan for Customs Duty Posting
select @intcomcurid = CurrencyId from acompanymaster where companyid = @intcompanyid
--R Harikrishnan for Customs Duty Posting
select @intDiscountAccountID = discountaccountid,@intOtherChargesAccountID = shopOtherChargesAccID,
@numProfitTrans = isnull(RevisedCostPricePercent,0),@chrShopType = upper(left(futureVarchar,1))
from ashops where ShopId = @intShopId
select @intCostOfGoodsAccId =CostofGoodsid, @intInventoryaccid =inventoryid,
@intPlTransAccId =profittransfercontrolacc, @intcomdeptid  =companydepartment,
@intcomprofitaccid =compprofitshareacc
from apackagesettings where companyid = @intcompanyid
--To return if the corresponding accounts are not selected
--R Harikrishnan 08/08/2003
if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0
return 0
--To return if the corresponding accounts are not selected
--R Harikrishnan 08/08/2003
if @numProfitTrans>0 and (isnull(@intPlTransAccId,0)=0 or isnull(@intPlTransAccId,0)=0)
return 0
set @intJournalId = @intJournalId + 1
--R Harikrishnan for Customs Duty Posting
Declare invcur cursor for
SELECT ihInvoiceId, ihinvoiceno, ihinvoicedate, ihCustomerId,ihremarks,ihdepartmentid,ihfinancialid,ihsalesaccid,
ihexchangerate, updatetime,ihdepExRate, ihexchangerates, ihCustomsDutyAccID, ihdutypaidby
FROM losinvoiceheader
WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 and ihCompanyID = @intCompanyID and ihShopId = @intShopId
and ihcashinvoice =0 and ihtype =''i''
open invcur
--R Harikrishnan for Customs Duty Posting
fetch next FROM invcur into
@intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,@intdepartmentid, @intfinancialid,
@intsalesaccountid, @NumEr, @dtutime,@depExRate, @strExRates, @intCustomsDutyID, @chrCustomsDutyPaidType
while @@Fetch_status = 0
begin
set @numTotalinvValue  = 0.0
set @numTotalCostValue = 0.0
set @numTotalDiscountValue = 0.0
set @numTotalOCValue = 0.0
set @numCustomsDutyAmt = 0.0
--FOR GETTING TRANS EXCHANGE RATE
select @intCurrencyId = CurrencyId from aCustomerMaster where CustomerId = @intCustomerId
exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output
--R Harikrishnan for Customs Duty Posting
--FOR GETTING TRANS EXCHANGE RATE
SELECT @numTotalinvValue = sum(idactualunitprice),@numTotalDiscountValue = sum(idunitprice),
@numCustomsDutyAmt = isnull(sum(isnull(idcdcustcur,0.00)),0.00),
@numTotalCostValue = isnull(sum(idquantity * idcostprice),0)
FROM losinvoicedetail WHERE idShopId = @intShopId and idInvoiceId  = @intInvoiceId
group by idShopId, idInvoiceId
--R Harikrishnan for Customs Duty Posting
--Checking whether the AccountID is saved in the transaction
if (@chrShopType=''B'' and @chrCustomsDutyPaidType<>''C'' and isnull(@intCustomsDutyID,0) = 0
AND @numCustomsDutyAmt>0)
Begin
Close invcur
Deallocate invcur
Return 0
End
-----------------------------------------------
SELECT @numTotalOCValue = sum(ioAmount),@numOCTaxAmount = sum(isnull(ioServTaxAmount,0)) --RefNo-3 Null handled
FROM losInvoiceOC WHERE ioShopId = @intShopId and ioInvoiceId = @intInvoiceId group by ioShopId,ioInvoiceId
--To return if the corresponding accounts are not selected
--R Harikrishnan 08/08/2003
if isnull(@intOtherChargesAccountID,0)=0 and @numTotalOCValue<>0
begin
Close invcur
Deallocate invcur
return 0
end
Set @numSalesValue = @numTotalDiscountValue
--R Harikrishnan for Customs Duty Posting
/*if (@chrShopType=''B'' and @chrCustomsDutyPaidType<>''C'')
begin
set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue + @numCustomsDutyAmt
end
else
begin
set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue
set @numCustomsDutyAmt = 0.00
end */
insert into moaJournalHeader(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
Type, CurrencyId, chequedate, updatetime)
values (@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,
@strRemarks, @intFinancialID,''SCI'', @intcomCurID,@dtinvoicedate, @dtutime)
set @intJournalDetailId = 1
---  RefNo-5
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
--RefNo-2--------------------------------------
select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),
@DTotalTaxAmount=sum(isnull(DtaxAmount,0))
from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId group by taxTransId,taxShopId
if @TotalTaxAmnt is null
begin
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
end
--TO CONVERT INTO SALE A/C CURRENCY---
select @intCurrencyId = CurrencyId from  aAccountMaster  where accountid = @intSalesAccountID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @TotalTaxAmnt,@TotalAccTax output
--TO CONVERT INTO SALE A/C CURRENCY---
--RefNo-2----------------------------------------
--FOR CONVERTING AMOUNT--->
select @intCurrencyId = CurrencyId from  aAccountMaster  where accountid = @intSalesAccountID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr, @numSalesValue ,@numAaccAmt output
--FOR CONVERTING AMOUNT <---
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intSalesAccountID,
(@numSalesValue * @NumEr)-(@CTotalTaxAmount),(@numAaccAmt-@TotalAccTax),@intDepartmentID,
(@numSalesValue * @depExRate)-(@DTotalTaxAmount), 1)  --RefNo-2---tax amount is deducted
set @intJournalDetailId = @intJournalDetailId +1
if @numTotalOCValue >0
begin
-- DEBITING customer with other charges
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,
@numTotalOCValue * @NumEr, @numTotalOCValue,@intDepartmentID, @numTotalOCValue * @depExRate, 2)
set @intJournalDetailId = @intJournalDetailId + 1
set @numTotalOCValue=@numTotalOCValue-@numOCTaxAmount    -------
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intOtherChargesAccountID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numTotalOCValue,@numAaccAmt output
--FOR CONVERTING AMOUNT <---
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intOtherChargesAccountID,
@numTotalOCValue* @NumEr,@numAaccAmt, @intDepartmentID, @numTotalOCValue * @depExRate, 2)
set @intJournalDetailId = @intJournalDetailId + 1
-----------------------------------------------------------------------------------------------------
/* crediing the other charge amount to service tax account  */
select @IntServTaxAccnt=t.TaxAccountId ,@IntServTaxAccntCurrID=a.CurrencyID
from ashops s inner join aTaxCategoryMaster t on s.ServiceTaxCategoryId=t.TaxId
inner join aAccountMaster a on a.AccountID=t.TaxAccountId
exec spReturnExRate @IntServTaxAccntCurrID, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numOCTaxAmount,@numAaccAmt output
--FOR CONVERTING AMOUNT <---
insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@IntServTaxAccnt,@numOCTaxAmount* @NumEr,
@numAaccAmt, @intDepartmentID, @numOCTaxAmount * @depExRate, 2)
set @intJournalDetailId = @intJournalDetailId + 1
--------------------------------------------------------------------------------------------------------
end
--R Harikrishnan for Customs Duty Posting
if @numCustomsDutyAmt >0 and @chrCustomsDutyPaidType<>''C'' and @chrShopType=''B''
Begin
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intCustomsDutyID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr,@numCustomsDutyAmt, @numAaccAmt output
-- crediing the Customs Duty account
insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intCustomsDutyID,
@numCustomsDutyAmt * @NumEr,@numAaccAmt, @intDepartmentID,@numCustomsDutyAmt * @depExRate, 3)
set @intJournalDetailId = @intJournalDetailId + 1
-- DEBITING customer Custom Duty amount
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId,@intCompanyID,0,@intCustomerId,@numCustomsDutyAmt * @NumEr,
@numCustomsDutyAmt,@intDepartmentID, @numCustomsDutyAmt * @depExRate, 3)
set @intJournalDetailId = @intJournalDetailId + 1
End
-- DEBITING customer Invoice amount
insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID,0,@intCustomerId,@numTotalDiscountValue * @NumEr,
@numTotalDiscountValue,@intDepartmentID, @numTotalDiscountValue * @depExRate, 1)
set @intJournalDetailId = @intJournalDetailId + 1
-- FOR CONVERTING AMOUNT --->
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intINVentoryAccID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,@numAaccAmt output
if @numTotalCostValue<>0
begin
--FOR CONVERTING AMOUNT <---
/* crediing the INVENTORY with the full cost Amount */
insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount, departmentID, depamount, PostGroup)
values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intINVentoryAccID,
@numTotalCostValue * @NumEr, @numAaccAmt,@intDepartmentID, @numTotalCostValue * @DepExRate , 4)
set @intJournalDetailId = @intJournalDetailId +1
--FOR CONVERTING AMOUNT--->
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intCostOfGoodsAccId
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,@numAaccAmt output
--FOR CONVERTING AMOUNT <---
-- DEBITING THE COST OF GOODS ACCOUNT
insert into moaJournalDetails(JournalId, JournalDetailId,CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intCostOfGoodsAccId,
@numTotalCostValue * @NumEr, @numAaccAmt,@intDepartmentID, @numTotalCostValue * @depExRate, 4)
end
-- transfering the profit to company department
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
--RefNo-2-----------------------------------
select @IntCount=count(*) from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId
while (@IntCount>0)
begin
select top 1 @TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId order by taxAccntId
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strExRates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
/* crediting TO TAX ACCOUNT   */
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@TaxAcntId, @CTaxAmount,
@TaxAccAmount,@intDepartmentID, @DTaxAmount, 1)
delete from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId and taxAccntId=@TaxAcntId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
if @numProfitTrans <> 0
begin
-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intPlTransAccId
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@numAaccAmt output
select @intCurrencyId = depCurrencyId from adepartmentmaster where departmentid = @intcomdeptid
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@NumDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
set @intJournalDetailId = @intJournalDetailId + 1
-- credit transfer control account with shop department
insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,departmentID, depamount, PostGroup)
values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intPlTransAccId ,
@numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,
@intDepartmentID,@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )
set @intJournalDetailId = @intJournalDetailId +1
-- credit transfer control account with comp department
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,departmentID, depamount, PostGroup)
values (@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intPlTransAccId ,
@numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,
@intcomdeptid,@numDepAmt * @numProfitTrans * 0.01, null)
-- FOR CONVERTING TO ACCOUNT AMOUNT ---------->
select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intcomprofitaccid
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@numAaccAmt output
select @intCurrencyId = depCurrencyId from adepartmentmaster where departmentid = @intcomdeptid
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@NumDepAmt output
-- FOR CONVERTING TO ACCOUNT AMOUNT< ----------
set @intJournalDetailId = @intJournalDetailId +1
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intcomprofitaccid ,
@numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,
@intcomdeptid,@numDepAmt * @numProfitTrans * 0.01, null )
-- debit company profit account with shop department
set @intJournalDetailId = @intJournalDetailId +1
insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,departmentID, depamount, PostGroup)
values(@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intcomprofitaccid ,
@numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,
@intDepartmentID,@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )
end
/* mark the record as postED */
update losinvoiceheader set ihpostED =1 WHERE ihCompanyID = @intCompanyID
and ihShopId = @intShopId and ihInvoiceId = @intInvoiceId
set @intJournalId = @intJournalId + 1
--R Harikrishnan for Customs Duty Posting
fetch next FROM invcur into @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId,@strremarks,
@intdepartmentid, @intfinancialid, @intsalesaccountid,@NumEr, @dtutime,@depExRate, @strExRates,
@intCustomsDutyID,@chrCustomsDutyPaidType
end
Close invcur
Deallocate invcur
SET NOCOUNT OFF
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULReexport]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULReexport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified on 		: 07/03/2003
--Modified by		: Hariharan R
--Comments		: Referred invoice posting and did in same way
--			: Including Other Charges
---------------------------------------------------------------------
CREATE proc [dbo].[spULReexport]
	@intCompanyID as int,
	@intShopId as int
as
begin
	Declare @intSalesAccountID 		as int,
		@intCashAccountID 		as int,
		@intJournalId 			as int,
		@intJournalDetailId 		as int,
		@intFinancialID 		as int,
		@intInvoiceId 			as int,
		@intCustomerId 			as int,
		@intDiscountAccountID 		as int,
		@intOtherChargesAccountID 	as int,
		@intDepartmentID 		as int,
		@intComCurID 			as int,
		@intinventoryaccid 		as int,
		@intCostOfGoodsAccId 		as int,
		@intPlTransAccId 		as int,
		@intcomdeptid 			as int,
		@intCurrencyId 			as int,
		@intcomprofitaccid 		as int,
		@intCustomsDutyID	 	as int,--R Harikrishnan for Customs Duty Posting
		@numtotalinvValue 		as NumEric(18,2),
		@numTotalDiscountValue 		as NumEric(18,2),
		@numTotalCostValue 		as NumEric(18,2),
		@numTotalOCValue 		as NumEric(18,2),
		@depsalesval 			as NumEric(18,2),
		@depcostval 			as NumEric(18,2),
		@numTransEr 			as NumEric(18,2),
		@numAccEr 			as NumEric(18,2),
		@numAaccAmt 			as NumEric(18,2),
		@NumDepAmt 			as NumEric(18,2),
		@numCustomsDutyAmt	 	as NumEric(18,2),--R Harikrishnan for Customs Duty Posting
		@numSalesValue			as NumEric(18,2),
		@depExRate 			as NumEric(28,8),
		@NumEr 				as NumEric(28,8),
		@numProfitTrans 		as NumEric( 7,5),
		@strExRates 			as varchar(250),
		@strinvoiceNo 			as varchar(50),
		@strRemarks 			as varchar(250),
		@chrCustomsDutyPaidType		as char(1),--R Harikrishnan for Customs Duty Posting
		@chrShopType			as char(1),--R Harikrishnan for Customs Duty Posting
		@dtinvoiceDate 			as datetime,
		@dtutime 			as datetime,
		@intVendorId			as int
	/* getting the defaults into the variables */
	/* getting the maximum Journal ID FROM journal table */
	SELECT
		@intJournalId = isnull(max(JournalId),0)
	FROM
		moaJournalHeader
	WHERE
		CompanyID = @intCompanyID
	
	set @numTotalinvValue  = 0.0
	set @numTotalCostValue = 0.0
	set @numTotalDiscountValue = 0.0
	set @numTotalOCValue = 0.0
	set @numCustomsDutyAmt = 0.0 --R Harikrishnan for Customs Duty Posting
	
	select
		@intcomcurid = CurrencyId
	from
		acompanymaster
	where
		companyid = @intcompanyid
	--R Harikrishnan for Customs Duty Posting
	select
		@intDiscountAccountID = discountaccountid,
		@intOtherChargesAccountID = shopOtherChargesAccID,
		@numProfitTrans = isnull(RevisedCostPricePercent,0) ,
		@chrShopType = upper(left(futureVarchar,1))
	from
		ashops
	where
		ShopId = @intShopId
	select
		@intCostOfGoodsAccId =CostofGoodsid, @intInventoryaccid =inventoryid,
		@intPlTransAccId =profittransfercontrolacc, @intcomdeptid  =companydepartment,
		@intcomprofitaccid =compprofitshareacc
	from
		apackagesettings
	where 	
		companyid = @intcompanyid
	--To return if the corresponding accounts are not selected
	--R Harikrishnan 08/08/2003
	if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0
		return 0
	--To return if the corresponding accounts are not selected
	--R Harikrishnan 08/08/2003
	if @numProfitTrans>0 and (isnull(@intPlTransAccId,0)=0 or isnull(@intPlTransAccId,0)=0)
		return 0
	set @intJournalId = @intJournalId + 1
	--R Harikrishnan for Customs Duty Posting
	Declare invcur cursor for
		SELECT
			rehExportId, rehExportNo, rehExportDate, rehCustomerId,  rehremarks,
			rehdepartmentid, rehfinancialid, rehsalesaccid, rehexchangerate, updatetime,
			rehdepExRate, rehexchangerates, rehVendorId
		FROM
			losExportHeader
		WHERE
			rehcancelled =0 and rehposted =0 and
			rehCompanyID = @intCompanyID and rehShopId = @intShopId and
			rehcashinvoice =0 and rehtype =''i''
			
	open invcur
	--R Harikrishnan for Customs Duty Posting
	fetch next FROM invcur into
		@intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,
		@intdepartmentid, @intfinancialid, @intsalesaccountid, @NumEr, @dtutime,
		@depExRate, @strExRates, @intVendorId
	while @@Fetch_status = 0
	begin
		set @numTotalinvValue  = 0.0
		set @numTotalCostValue = 0.0
		set @numTotalDiscountValue = 0.0
		set @numTotalOCValue = 0.0
		set @numCustomsDutyAmt = 0.0
	
		if @intVendorId is null
		Begin
		--FOR GETTING TRANS EXCHANGE RATE
			select
				@intCurrencyId = CurrencyId
			from
				aCustomerMaster
			where
				CustomerId = @intCustomerId
			exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output
		End
		Else
		Begin
			select
				@intCurrencyId = CurrencyId
			from
				aVendorMaster
			where
			vendorid = @intVendorId
			exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output
		End
		--R Harikrishnan for Customs Duty Posting
		--FOR GETTING TRANS EXCHANGE RATE
		SELECT
			@numTotalinvValue = sum(redactualunitprice),
			@numTotalDiscountValue = sum(redunitprice),
			@numTotalCostValue = isnull(sum(redquantity * redcostprice),0)
		FROM
			losExportDetail
		WHERE
			redShopId = @intShopId and redExportId  = @intInvoiceId
		group by
			redShopId, redExportId
		SELECT
			@numTotalOCValue = sum(ioAmount)
		FROM
			losExportOC
		WHERE
			ioShopId = @intShopId and ioInvoiceId  = @intInvoiceId
		group by
			ioShopId, ioInvoiceId
		--To return if the corresponding accounts are not selected
		--R Harikrishnan 08/08/2003
		if isnull(@intOtherChargesAccountID,0)=0 and @numTotalOCValue<>0
		begin
			Close invcur
			Deallocate invcur
			return 0
		end
		Set @numSalesValue = @numTotalDiscountValue
		set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue
		insert into moaJournalHeader
			(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,
			Type, CurrencyId, chequedate, updatetime)
		values
			(@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,
			@strRemarks, @intFinancialID,''RE'', @intcomCurID,@dtinvoicedate, @dtutime)
		set @intJournalDetailId = 1
		
		--FOR CONVERTING AMOUNT--->
		select
			@intCurrencyId = CurrencyId
		from
			aAccountMaster
		where
			accountid = @intSalesAccountID
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr , @numAccEr, @numSalesValue ,
							@numAaccAmt output
		--FOR CONVERTING AMOUNT <---
		/* crediing the sales account with the full invoice Amount */
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
			Amount, actualAmount, departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
			@intSalesAccountID, @numSalesValue * @NumEr,
			@numAaccAmt,@intDepartmentID, @numSalesValue * @depExRate)
		set @intJournalDetailId = @intJournalDetailId +1
		if @numTotalOCValue>0
		begin
			select
				@intCurrencyId = CurrencyId
			from
				aAccountMaster
			where
				accountid = @intOtherChargesAccountID
			exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
			exec spConvertCurrency @numTransEr , @numAccEr , @numTotalOCValue,
							@numAaccAmt output
			--FOR CONVERTING AMOUNT <---
			/* crediing the sales account with the full invoice Amount */
			insert into moaJournalDetails
				(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
				Amount, actualAmount, departmentID, depamount)
			values
				(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
				@intOtherChargesAccountID, @numTotalOCValue* @NumEr,
				@numAaccAmt, @intDepartmentID, @numTotalOCValue * @depExRate)
			set @intJournalDetailId = @intJournalDetailId + 1
		end	
		if @intVendorId is null
		Begin
		-- DEBITING customer
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,
			Amount, actualAmount, departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,
			@numTotalDiscountValue * @NumEr, @numTotalDiscountValue,
			@intDepartmentID, @numTotalDiscountValue * @depExRate)
		end
		else
		Begin
			-- DEBITING vendor
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID, JournalCrEDit, vendorid,
			Amount, actualAmount, departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intVendorid,
			@numTotalDiscountValue * @NumEr, @numTotalDiscountValue,
			@intDepartmentID, @numTotalDiscountValue * @depExRate)
		End
		set @intJournalDetailId = @intJournalDetailId + 1				
		-- FOR CONVERTING AMOUNT --->
		select
			@intCurrencyId = CurrencyId
		from
			aAccountMaster
		where 	
			accountid = @intINVentoryAccID
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,
								@numAaccAmt output
	if @numTotalCostValue<>0
	begin
		--FOR CONVERTING AMOUNT <---
		/* crediing the INVENTORY with the full cost Amount */
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
			@intINVentoryAccID, @numTotalCostValue * @NumEr, @numAaccAmt,
			@intDepartmentID, @numTotalCostValue * @DepExRate )
			
		set @intJournalDetailId = @intJournalDetailId +1
		--FOR CONVERTING AMOUNT--->
		select
			@intCurrencyId = CurrencyId
		from 	
			aAccountMaster
		where 	
			accountid = @intCostOfGoodsAccId		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,
							@numAaccAmt output
		--FOR CONVERTING AMOUNT <---
		-- DEBITING THE COST OF GOODS ACCOUNT
		insert into moaJournalDetails
			(JournalId, JournalDetailId,CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
			@intCostOfGoodsAccId, @numTotalCostValue * @NumEr, @numAaccAmt,
			@intDepartmentID, @numTotalCostValue * @depExRate)
	end
		-- transfering the profit to company department
		-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
	if @numProfitTrans <> 0
	begin
		-- FOR CONVERTING TO ACCOUNT AMOUNT---------->
			
		select
			@intCurrencyId = CurrencyId
		from
			aAccountMaster
		where
			accountid = @intPlTransAccId
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,
		@numAaccAmt output
		select
			@intCurrencyId = depCurrencyId
		from
			adepartmentmaster
		where
			departmentid = @intcomdeptid
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,
						@NumDepAmt output
		-- FOR CONVERTING TO ACCOUNT AMOUNT<------------------
		set @intJournalDetailId = @intJournalDetailId + 1	
			
		-- credit transfer control account with shop department
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
			@intPlTransAccId , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,
			@numAaccAmt * @numProfitTrans * 0.01, @intDepartmentID,
			@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate )
		set @intJournalDetailId = @intJournalDetailId +1	
			
		-- credit transfer control account with comp department
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
			@intPlTransAccId , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,
			@numAaccAmt * @numProfitTrans * 0.01, @intcomdeptid,
			@numDepAmt * @numProfitTrans * 0.01)
		
		-- FOR CONVERTING TO ACCOUNT AMOUNT ---------->
		select
			@intCurrencyId = CurrencyId
		from 	
			aAccountMaster
		where
			accountid = @intcomprofitaccid
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,
		@numAaccAmt output
		select
			@intCurrencyId = depCurrencyId
		from
			adepartmentmaster
		where
			departmentid = @intcomdeptid
		
		exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output	
		exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,
						@NumDepAmt output
		-- FOR CONVERTING TO ACCOUNT AMOUNT< ----------
		set @intJournalDetailId = @intJournalDetailId +1
		
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 1,
			@intcomprofitaccid , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,
			@numAaccAmt * @numProfitTrans * 0.01, @intcomdeptid,
			@numDepAmt * @numProfitTrans * 0.01)
		-- debit company profit account with shop department	
		set @intJournalDetailId = @intJournalDetailId +1
		insert into moaJournalDetails
			(JournalId, JournalDetailId, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
		values
			(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
			@intcomprofitaccid , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,
			@numAaccAmt * @numProfitTrans * 0.01, @intDepartmentID,
			@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate )	
	end
		/* mark the record as postED */
		update losExportHeader set
			rehposted =1
		WHERE
			rehCompanyID = @intCompanyID
			and rehShopId = @intShopId and rehExportId = @intInvoiceId
		set @intJournalId = @intJournalId + 1
		--R Harikrishnan for Customs Duty Posting
		fetch next FROM invcur into
			@intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId,	
			@strremarks, @intdepartmentid, @intfinancialid, @intsalesaccountid,
			@NumEr, @dtutime,@depExRate, @strExRates, @intVendorId
	end
	Close invcur
	Deallocate invcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULMASRoomBilling]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASRoomBilling]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created  ON 	: 21/08/2003
-- Created  by   : R Harikrishnan
-- Comment     	: FOR Posting the manaam Agreement depositAmt
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--spULMASRoomBilling 1,24
--------------------------------------
CREATE procEDURE [dbo].[spULMASRoomBilling]
	@intCompanyID 	AS INT,
	@intshopid 	AS INT
AS
BEGIN
--	FOR testing by R Harikrishnan
--	BEGIN Tran
--	SET @intCompanyID=1
--	SET @intShopID =24
	DECLARE @intJournalID 		AS INT,
		@intJournalDetailID 	AS INT,
		@intFinancialID 	AS INT,
		@intCAShAccId 		AS INT,
		@intCustomerId 		AS INT,
		@intSalesAccId		AS INT,
		@intOCAccId		AS INT,
		@intAgmntID		AS INT,
		@intRoomBillID 		AS INT,
		@intDeptID 		AS INT,
		@intComCurID		AS INT,
		@intAdvanceAccId 	AS INT,
		@dtRoomBillDate 	AS DATETIME,
		@dtUpdTime		AS DATETIME,
		@strRoomBillNo 		AS varchar(50),
		@strRemarks 		AS varchar(250),
		@strExRates 		AS varChar(250),	
		@numDepExRate 		AS NUMERIC(18,8),
		@numCONExRate 		AS NUMERIC(18,8),
		@numAmt 		AS NUMERIC(18,2),
		@numOCAmt 		AS NUMERIC(18,2),
		@numDepRetAmt 		AS NUMERIC(18,2),
		@numResAmt		AS NUMERIC(18,2),
		@numTotBillAmt		AS NUMERIC(18,2)
--		@numResAmt		AS NUMERIC(18,2)
	SET @numDepExRate 	= 0.00
	SET @numCONExRate 	= 0.00
	SET @numDepRetAmt 	= 0.00
	SET @intCAShAccId	= 0
	SET @intAdvanceAccId	= 0
	SET @intRoomBillID		= 0
	SET @intDeptID		= 0
	SET @numResAmt		= 0.00
	SELECT
		@intJournalID = ISNULL(MAX(JournalID),0)
	FROM
		moaJournalHeader
	WHERE
		CompanyID = @intCompanyID
	SET @intJournalID = @intJournalID + 1
	
	SELECT
		@intComCurid = CurrencyId
	FROM
		acompanymASter
	WHERE
		companyid = @intcompanyid
	DECLARE RoomBillCur CURSOR FOR
		SELECT
			abhBillId , abhBillDate, abhBillNo, abhRemarks, abhDepartmentid,
			abhUPDATETIME, abhExRate, abhDepExRate, abhExRates,
			abhSalesAccID, abhOCAccID, abhCustomerId, abhCAShAccId, abhAmount,
			abhOtherCharges, abdDepositReturn, abhAgreementId
		FROM
			losApartmentBillHeader
		WHERE
			abhSHopID =@intshopid and abhCompanyid =@intCompanyID and
			abhPosted=0 and abhCancelled=0
	OPEN RoomBillCur
	FETCH NEXT FROM
		RoomBillCur
	INTO
		@intRoomBillID, @dtRoomBillDate, @strRoomBillNo, @strRemarks, @intDeptID,
		@dtUpdTime, @numCONExRate, @numDepExRate, @strExRates, @intSalesAccId,
		@intOCAccId, @intCustomerId, @intCAShAccId, @numAmt, @numOCAmt,
		@numDepRetAmt, @intAgmntID
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
--		select 	@numCONExRate exRate, @numDepExRate DepRate , @strExRates exRates,
--			@intOCAccId OC, @intCustomerId Cust, @intCAShAccId Cash,
--			@numAmt amt, @numOCAmt ocAmt, @numDepRetAmt depAmt, @intAgmntID agmntID
		-- SELECTing the Advance Account ID FROM Agreement Header Table
		SELECT
			@intAdvanceAccId = mghAdavanceAccID
		FROM
			losApartmentAgreementHeader ah
		WHERE
			mghCancelled = 0 and mghPosted = 0 and 	mghShopid = @intshopid
			and mghCompanyID=@intCompanyID and mghAgreementID = @intAgmntID
		-- to take financialid FROM afinancialyear table with curfinancialyear=1 -- hari011211
		SELECT
			@intFinancialID = financialid
		FROM
			vwfinyearperiod
		WHERE
			@dtRoomBillDate between sdate and edate		
		-- Getting the total amount to the variable
		SET @numTotBillAmt = @numAmt + @numOCAmt - @numDepRetAmt
		--Inserting new record INTO header
		INSERT INTO moaJournalHeader
			(JournalID, CompanyID, JournalDate, referenceno, remarks,
			financialID, Type, CurrencyID, chequedate, UPDATETIME)
		VALUES
			(@intJournalID, @intCompanyID, @dtRoomBillDate, @strRoomBillNo,
			@strRemarks, @intFinancialID, ''RBI'', @intComCurid,
			@dtRoomBillDate, @dtUpdTime)
		SET @intJournalDetailID = 1
		IF @numTotBillAmt>0 --The total amount is greater than zero
		BEGIN
			--IF the transactiON type is CASh Debiting the CASh
			IF @intCAShAccId is not null
			BEGIN
				-- debiting the CASh oAccount with  account with the full
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intCAShAccId, @numTotBillAmt * @numCONExRate,
					@numTotBillAmt, @numTotBillAmt * @numDepExRate,
					@intDeptID)
			END
			ELSE -- IF the transactiON type is credit
			BEGIN
				-- Debiting the Customer
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					CustomerID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intCustomerId, @numTotBillAmt * @numCONExRate,
					@numTotBillAmt, @numTotBillAmt * @numDepExRate,
					@intDeptID)
			END
			SET @intJournalDetailID = @intJournalDetailID + 1
		END
		ELSE IF @numTotBillAmt<0 -- IF the total amount is negative
		BEGIN
			SET @numTotBillAmt=ABS(@numTotBillAmt)
			--IF the transactiON type is CASh Debiting the CASh
			IF @intCAShAccId is not null
			BEGIN
				-- debiting the CASh oAccount with  account with the full
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intCAShAccId, @numTotBillAmt * @numCONExRate,
					@numTotBillAmt, @numTotBillAmt * @numDepExRate,
					@intDeptID)
			END
			ELSE -- IF the transactiON type is credit
			BEGIN
				-- Debiting the Customer
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					CustomerID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intCustomerId, @numTotBillAmt * @numCONExRate,
					@numTotBillAmt, @numTotBillAmt * @numDepExRate,
					@intDeptID)
			END
			SET @intJournalDetailID = @intJournalDetailID + 1
		END
				
		IF @numDepRetAmt>0 -- Deposit return amount is greater than zero
		BEGIN
			-- FOR cONverting the amount --->
			IF @intCAShAccId is not null
			BEGIN
				EXEC spCONvertequiamount @intCAShAccId, ''a'', @intAdvanceAccId,
					''a'', @strExRates, @numDepRetAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intAdvanceAccId, @numDepRetAmt * @numCONExRate,
					@numResAmt, @numDepRetAmt * @numDepExRate, @intDeptID  )
			END
			ELSE
			BEGIN
				EXEC spCONvertequiamount @intCustomerID, ''c'', @intAdvanceAccId,
					''a'', @strExRates, @numDepRetAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intAdvanceAccId, @numDepRetAmt * @numCONExRate,
					@numResAmt, @numDepRetAmt * @numDepExRate, @intDeptID  )
			END
			SET @intJournalDetailID = @intJournalDetailID + 1
		END
				
		IF @numOCAmt>0 -- Other Charges Amount is greater than zero
		BEGIN
			-- FOR cONverting the amount --->
			IF @intCAShAccId is not null
			BEGIN
				EXEC spCONvertequiamount @intCAShAccId, ''a'', @intOCAccId,
					''a'', @strExRates, @numOCAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intOCAccId, @numOCAmt * @numCONExRate,
					@numResAmt, @numOCAmt * @numDepExRate, @intDeptID  )
			END
			ELSE
			BEGIN
				EXEC spCONvertequiamount @intCustomerID, ''c'', @intOCAccId,
					''a'', @strExRates, @numOCAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intOCAccId, @numOCAmt * @numCONExRate,
					@numResAmt, @numOCAmt * @numDepExRate, @intDeptID  )
			END
			SET @intJournalDetailID = @intJournalDetailID + 1
		END
		IF @numAmt>0 -- Posting Rent Amount if greater than zero
		BEGIN
			-- FOR cONverting the amount --->
			IF @intCAShAccId is not null
			BEGIN
				EXEC spCONvertequiamount @intCAShAccId, ''a'', @intSalesAccId,
					''a'', @strExRates, @numAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intSalesAccId, @numAmt * @numCONExRate,
					@numResAmt, @numAmt * @numDepExRate, @intDeptID  )
			END
			ELSE
			BEGIN
				EXEC spCONvertequiamount @intCustomerID, ''c'', @intSalesAccId,
					''a'', @strExRates, @numAmt, @numResAmt output,''''	
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intSalesAccId, @numAmt * @numCONExRate,
					@numResAmt, @numAmt * @numDepExRate, @intDeptID  )
			END
			SET @intJournalDetailID = @intJournalDetailID + 1
		END		
		-- mark the record AS postED
		UPDATE
			losApartmentBillHeader
		SET
			abhPosted  = 1
		WHERE
			abhShopid = @intShopID and abhBillID = @intRoomBillID and
			abhCompanyID= @intCompanyID				
		SET @intJournalID = @intJournalID + 1
		FETCH NEXT FROM
			RoomBillCur
		INTO
			@intRoomBillID, @dtRoomBillDate, @strRoomBillNo, @strRemarks, @intDeptID,
			@dtUpdTime, @numCONExRate, @numDepExRate, @strExRates, @intSalesAccId,
			@intOCAccId, @intCustomerId, @intCAShAccId, @numAmt, @numOCAmt,
			@numDepRetAmt, @intAgmntID
	END
	CLOSE RoomBillCur -- Closing the cursor
	DEALLOCATE RoomBillCur
--	rollback tran
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULMASCheckOut]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULMASCheckOut]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------
-- Created on 	: 04/09/2003
-- Created by   : R Harikrishnan
-- Comment     	: FOR Posting the Deposit return from the Checkout table
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spULMASCheckOut]
	@intCompanyID 	AS INT,
	@intshopid 	AS INT
AS
BEGIN
--	FOR testing by R Harikrishnan
--	BEGIN Tran
--	SET @intCompanyID=1
--	SET @intShopID =24
	DECLARE @intJournalID 		AS INT,
		@intJournalDetailID 	AS INT,
		@intFinancialID 	AS INT,
		@intCAShAccId 		AS INT,
		@intAdvanceAccId 	AS INT,
		@intWriteOffAccId 	AS INT,
		@intCheckOutID 		AS INT,
		@intAgmntID 		AS INT,
		@intDeptID 		AS INT,
		@intComCurID		AS INT,
		@dtCheckOutDate 	AS DATETIME,
		@dtUpdTime		AS DATETIME,
		@strCheckOutNo 		AS VARCHAR(50),
		@strRemarks 		AS VARCHAR(250),
		@strExRates 		AS VARCHAR(250),	
		@numDepExRate 		AS NUMERIC(18,8),
		@numConExRate 		AS NUMERIC(18,8),
		@numDepositAmt 		AS NUMERIC(18,2),
		@numAvailedAmt 		AS NUMERIC(18,2),
		@numResAmt		AS NUMERIC(18,2)
	SET @numDepExRate 	= 0.00
	SET @numConExRate 	= 0.00
	SET @numDepositAmt 	= 0.00
	SET @intCAShAccId	= 0
	SET @intAdvanceAccId	= 0
	SET @intCheckOutID	= 0
	SET @intDeptID		= 0
	SET @numResAmt		= 0.00
	SELECT
		@intJournalID = ISNULL(MAX(JournalID),0)
	FROM
		moaJournalHeader
	WHERE
		CompanyID = @intCompanyID
	SET @intJournalID = @intJournalID + 1
	
	SELECT
		@intComCurid = CurrencyId
	FROM
		acompanymASter
	WHERE
		companyid = @intcompanyid
	
	DECLARE CheckOutCur CURSOR FOR
		SELECT
			chID, chDate, chNo, chRemarks, ChDepartmentID,
			chUPDATETime, chExRate, chDepExRate, chExRates, chWriteOffAccID,
			chCAShAccId, chDepositAmount, chAvaliedAmount, chAgreementID
		FROM
			losApartmentCheckOut
		WHERE
			chCancelled = 0 and chPosted = 0 and chShopID = @intshopid and
			chCompanyID=@intCompanyID and (chDepositAmount>0 or chAvaliedAmount>0)
	OPEN CheckOutCur
	FETCH NEXT FROM
		CheckOutCur
	INTO
		@intCheckOutID, @dtCheckOutDate, @strCheckOutNo, @strRemarks, @intDeptID,
		@dtUpdTime, @numConExRate, @numDepExRate, @strExRates, @intWriteOffAccId,
		@intCAShAccId, @numDepositAmt, @numAvailedAmt, @intAgmntID
	WHILE @@FETCH_STATUS = 0
	BEGIN
			-- To get the advance account ID FROM the Agreement
			SELECT
				@intAdvanceAccId=mghAdavanceAccID
			FROM
				losApartmentAgreementHeader
			WHERE
				mghCompanyID=@intCompanyID and mghShopID = @intShopID and
				mghAgreementID = @intAgmntID
			-- to take financialid FROM afinancialyear table with curfinancialyear=1 -- hari011211
			SELECT
				@intFinancialID = financialid
			FROM
				vwfinyearperiod
			WHERE
				@dtCheckOutDate between sdate and edate		
	
			INSERT INTO moaJournalHeader
				(JournalID, CompanyID, JournalDate, referenceno, remarks,
				financialID, Type, CurrencyID, chequedate, UPDATEtime)
			VALUES
				(@intJournalID, @intCompanyID, @dtCheckOutDate, @strCheckOutNo,
				@strRemarks, @intFinancialID, ''CHOR'', @intComCurid,
				@dtCheckOutDate, @dtUpdTime)
			SET @intJournalDetailID = 1		
			IF @numDepositAmt-@numAvailedAmt>0
			BEGIN
				--Crediting the Cash Account if the value is positive
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intCAShAccId, (@numDepositAmt-@numAvailedAmt) * @numConExRate,
					(@numDepositAmt-@numAvailedAmt), (@numDepositAmt-@numAvailedAmt) * @numDepExRate,
					@intDeptID)		
		
				SET @intJournalDetailID = @intJournalDetailID + 1		
			END
			ELSE IF @numDepositAmt-@numAvailedAmt<0
			BEGIN
				--Debiting the Cash Account if the value is negative
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intCAShAccId, ABS(@numDepositAmt-@numAvailedAmt) * @numConExRate,
					ABS(@numDepositAmt-@numAvailedAmt), ABS(@numDepositAmt-@numAvailedAmt) * @numDepExRate,
					@intDeptID)		
		
				SET @intJournalDetailID = @intJournalDetailID + 1	
			END			
			IF @numDepositAmt>0
			BEGIN
				-- FOR converting the amount --->
				EXEC spConvertequiamount @intCAShAccId, ''a'', @intAdvanceAccId,
					''a'', @strExRates, @numDepositAmt, @numResAmt output,''''	
				-- debiting the Advance account
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
					@intAdvanceAccId, @numDepositAmt * @numConExRate,
					@numResAmt, @numDepositAmt * @numDepExRate, @intDeptID  )
	
				SET @intJournalDetailID = @intJournalDetailID + 1
			END
			IF @numAvailedAmt>0
			BEGIN
				-- FOR converting the amount --->
				EXEC spConvertequiamount @intCAShAccId, ''a'', @intWriteOffAccId,
					''a'', @strExRates, @numAvailedAmt, @numResAmt output,''''	
	
				-- Crediting the Write Off Account
				INSERT INTO moaJournalDetails
					(JournalID, journaldetailID, CompanyID, JournalCrEDit,
					AccountID, Amount, actualAmount, DepAmount, departmentID)
				VALUES
					(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
					@intWriteOffAccId, @numAvailedAmt * @numConExRate,
					@numResAmt, @numAvailedAmt * @numDepExRate, @intDeptID)
			END
			/* mark the record AS postED */
			UPDATE
				losApartmentCheckOut
			SET
				chPosted  = 1
			WHERE
				chShopid = @intShopID and chID = @intCheckOutID and
				chCompanyID= @intCompanyID				
			SET @intJournalID = @intJournalID + 1
		FETCH NEXT FROM
			CheckOutCur
		INTO
			@intCheckOutID, @dtCheckOutDate, @strCheckOutNo, @strRemarks, @intDeptID,
			@dtUpdTime, @numConExRate, @numDepExRate, @strExRates, @intWriteOffAccId,
			@intCAShAccId, @numDepositAmt, @numAvailedAmt, @intAgmntID
		END
	CLOSE CheckOutCur
	DEALLOCATE CheckOutCur
--	rollback tran
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spulShopConsumption]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopConsumption]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-- spulShopConsumption 1,2,344
------------------------------------------------------------
-- Modified on   : 07/01/2003
-- Modified by   : Hariharan
-- Comment       : added the code to insert DepAmount
--                   and to convert amount
--Verified by hariharan on 07/01/2003
------------------------------------------------------------
-- Last Modified on : 07/06/2003
-- Last Modifued by : R Harikrishnan
-- Comment   : Added the type in the where part          ss
------------------------------------------------------------
-- Last Modified on : 07/08/2010
-- Last Modifued by : Nidheesh P V
-- Comment   : Added the option to post transactions saved wtih Itemwise Account
--@TransId is included to control both shop & HQ posting through front end.
-----------------------------------------------------------------------
-- Last Modified on :30/09/2010
-- Last Modifued by : jyothish
-- Comment   : ref-1    round the amount
CREATE  proc [dbo].[spulShopConsumption]
@intCompanyID as int, @intshop as int ,@TransId as int =0
as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intswoid as int,
@intFinancialID as int,
@strswoNo as varchar(50),
@dtswoDate as datetime,
@strRemarks as varchar(500),
@intDepartmentID as int,
@numSwoAmt as numeric(18,2),
@intCompanyCurID as int,
@intinventoryaccid as int,
@dtutime as datetime,
@intfailcount as int,
@strzerorate as varchar(1),
@intExpenseAcid as int,
@numDepExRate as numeric(18, 8),
@numConExRate as numeric(18, 8),
@intCurrencyId as int,
@strExRates VarChar(250),
@numAccExRate Numeric(18, 2),
@numTransEr Numeric(18, 2),
@numAaccAmt Numeric(18, 2),
@numTemp Numeric (18, 2),
@numToDepExRate as numeric(18, 8),
@intToDepId as int,
@ItemwiseAccounting as int ,
@WriteoffQty as numeric(18,2) ,
@costprice as numeric(18,2),
@InhouseAccnt as numeric(18,2) ,
@ItemAmount as numeric(18,2)
set @numAccExRate = 0.0
set @numTransEr = 0.0
set @numAaccAmt = 0.0
set @numTemp = 0.0
-- get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster WHERE CompanyID = @intCompanyID
select @intinventoryaccid = InventoryID, @strzerorate = substring(isnull(futurevc, ''''), 1, 1) from apackagesettings
select @ItemwiseAccounting=isnull(ItemwiseAccountinginInHousecon,0) from apackagesettings --to check wheather Itemwise accounting is enabled or not
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare swoCur cursor for
SELECT whID, whno, whdate,  whremarks, updatetime, whdepartmentid,
isnull(whExpenseAccId,0)  whExpenseAccId,
whConExRate,
whDepExRate, whExchangeRates,whotherdepid,whtodepexrate
FROM loswriteoffheader WHERE
whcancellED =0 and whshopid = @intshop and whposted =0 and (whID=@TransId or @TransId=0)
and whtype=''I'' and whVerified=1
open SwoCur
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
while @@Fetch_status = 0              begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
-- and the item master table. If so we cannot do any thing in the posting with out item rate.
-- so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
select @intFailcount = count(*) from loswriteoffdetail, aitem where
WdID = @intswoiD and wdShopID = @intshop and WdItemID = itemid
and ( wdcostprice =null or wdcostprice = 0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
begin
set @intfailcount=0
end
if @intfailcount = 0 -- for item rate=0 check hari 011213
begin
-- to update the item rate to the gadcostprice
update loswriteoffdetail set wdcostprice = itemrate from
aitem where ( wdcostprice =null or wdcostprice = 0) and wdid = @intswoiD
and wdShopID = @intshop and WdItemID = itemid
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,
@strRemarks, @intFinancialID, ''scon'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
-- getting the total amount with qty and item cost price --ref-1
select @numSwoAmt = isnull(sum(round(wdwriteoffqty * wdcostprice,2)),0) from
loswriteoffdetail swod
where wdshopid = @intshop and wdid = @intswoid
if @ItemwiseAccounting<> 0 --if itemwise accounting is enabled item amount is posted to corresponding account
begin
declare acntcurs cursor for select WdWriteoffQty,wdcostprice,WdInhouseConsAccnt
FROM loswriteoffdetail where wdshopid = @intshop and wdid = @intswoid
open acntcurs
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt
if @InhouseAccnt is not null --to check wheather there is unposted transaction done bofore setting the itemwise accounting
begin
while @@fetch_status=0
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @InhouseAccnt
---ref-1
set @ItemAmount=round(isnull(sum(@WriteoffQty * @costprice),0) ,2)
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@ItemAmount,
@numAaccAmt output
-- debiting the stock consumption accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@InhouseAccnt ,
round(@ItemAmount * @numConExRate,2), round(@numAaccAmt,2),
round(@ItemAmount * @numDepExRate,2), @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt
end
if @intDepartmentID<> @intToDepId --to post to control acc in the case of Itemwise is enabled and different departmnts
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- crediting the control accid  for the current department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- debiting the stock consumption accid for todept
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
end
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- debiting the stock consumption accid   -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), round(@numAaccAmt,2),
round(@numSwoAmt * @numDepExRate,2), @intDepartmentId)
set @intJournalDetailID = @intJournalDetailID + 1
end
close acntcurs
deallocate acntcurs
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- debiting the stock consumption accid    -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), round(@numAaccAmt,2),
round(@numSwoAmt * @numDepExRate,2), @intDepartmentId)
set @intJournalDetailID = @intJournalDetailID + 1
end
-- credit the inventory acc id
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount,
actualamount, DepAmount,
departmentid) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intinventoryaccid, round(@numSwoAmt * @numConExRate,2), round(@numSwoAmt,2),
round(@numSwoAmt * @numDepExRate,2), @intdepartmentid )
update loswriteoffheader set whposted = 1
WHERE WhID = @intswoID and whshopid = @intShop
set @intJournalID = @intJournalID + 1
end -- for item rate=0 check hari 011213
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
end -- CUR END
Close swoCur
Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalanceDept]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalanceDept]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===========================================================
-- Author  : MANUNADH. U
-- Create date : 02/05/2011
-- Description : To fetch BankCashBalance details in department
-- spBankCashBalanceDept 1,''20110101'',
-- ===========================================================
CREATE proc [dbo].[spBankCashBalanceDept] @intCompanyID as int, @strCurdate as varchar(10), @intdepid as int as
begin
set nocount on
Declare
@intSlNo as int,
@intAccountID as int,
@strAccountDesc as varchar(250),
@intComCurrencyID as int,
@intAccCurrencyID as int,
@numFacility as numeric(18,2),
@strCurrency as varchar(100),
@numDebitBal as numeric(18,2),
@numCreditBal as numeric(18,2),
@numBalance as numeric(18,2),
@numPostdatedPayments as numeric(18,2),
@numPostdatedreceipts as numeric(18,2),
@numopening as numeric(18,2),
@dtcurdate as datetime
set @dtcurdate = convert(datetime,@strcurdate)
Create table #BankCashBalance(
Slno int,
currencyid int,
accountid int,
AccDesc varchar(250),
Opening numeric(18,2),
Facility numeric(18,2),
Balance numeric(18,2),
postdatedpayments numeric(18,2),
postdatedreceipts numeric(18,2),
netbalance numeric(18,2),
Currency varchar(100)
)
select top 1 @intComCurrencyID = CurrencyID from acompanymaster where companyid = @intCompanyID
declare AccountCur cursor for
select AccountID, AccountDesc, BudgetAmount,CurrencyID from aaccountmaster a, adeptaccounts da
where a.companyid = da.dacompanyid and a.accountid = da.daaccountid and  a.groupid =
(select bankgroupid from asettings where companyid = @intCompanyID)
and a.companyid = @intcompanyid and da.dadepartmentid = @intdepid
order by groupid,CurrencyID,AccountDesc
open AccountCur
set @intSlno = 1
fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,@intAccCurrencyID
while @@fetch_status <> -1
begin
select @strCurrency = CurrencyName from aCurrencyMaster
where CurrencyID = @intAccCurrencyID and companyid = @intCompanyID
if (@intAccCurrencyID = @intComCurrencyID)
begin
set @numopening = 0.0
exec spopeningbalance @strCurdate, @intAccountID, @intcompanyid,''C'', @numopening output, @intdepid
select @numDebitBal = isnull(sum(amount),0)
from vwjournaldetails JD,moajournalheader JH, acompanymaster c
where  c.companyid = jh.companyid and JD.journalid = JH.journalid and JH.cancel = 0 and
JH.companyid = JD.companyid and JH.companyid = @intcompanyid and JD.journalcredit = 0
and JD.AccountID = @intAccountID and jh.financialid <> 0 and journaldate>=@strCurDate
AND JD.departmentid=@intdepid
select @numCreditBal = isnull(sum(amount),0)
from vwjournaldetails JD, moajournalheader JH, acompanymaster c
where  c.companyid = jh.companyid and JD.journalid = JH.journalid and JH.cancel = 0 and
JH.companyid = JD.companyid and JH.companyid = @intcompanyid and JD.journalcredit = 1
and JD.AccountID = @intAccountID and jh.financialid <> 0 and journaldate>=@strCurDate
AND JD.departmentid=@intdepid
select @numpostdatedpayments = isnull(sum(creditamt),0)
from vwpostdatedpayments
where companyid = @intcompanyid and accountid = @intAccountID and chequedate > @dtcurdate
select @numpostdatedreceipts = isnull(sum(debitamt),0)
from vwpostdatedreceipts
where companyid = @intcompanyid and accountid = @intAccountID and chequedate > @dtcurdate
end
else
begin
set @numopening = 0.0
exec spopeningbalance @strCurdate, @intAccountID, @intcompanyid,''B'', @numopening output,@intdepid
select @numDebitBal = isnull(sum(actualamount),0)
from vwjournaldetails JD, moajournalheader JH, acompanymaster c
where  c.companyid = jh.companyid and JD.journalid = JH.journalid and JH.cancel = 0 and
JH.companyid = JD.companyid and JH.companyid = @intcompanyid and JD.journalcredit = 0 and
JD.AccountID = @intAccountID and jh.financialid <> 0 and journaldate>=@strCurDate
AND JD.departmentid=@intdepid
select @numCreditBal = isnull(sum(actualamount),0)
from vwjournaldetails JD, moajournalheader JH, acompanymaster c
where  c.companyid = jh.companyid and JD.journalid = JH.journalid and JH.cancel = 0 and
JH.companyid = JD.companyid and JH.companyid = @intcompanyid and JD.journalcredit = 1 and
JD.AccountID = @intAccountID and jh.financialid <> 0 and journaldate>=@strCurDate
AND JD.departmentid=@intdepid
select @numpostdatedpayments = isnull(sum(creditactualamt),0)
from vwpostdatedpayments
where companyid = @intcompanyid and accountid = @intAccountID and chequedate > @dtcurdate
select @numpostdatedreceipts = isnull(sum(debitactualamt),0)
from vwpostdatedreceipts
where companyid = @intcompanyid and accountid =@intAccountID and chequedate > @dtcurdate
end
set @numBalance = isnull(@numopening,0) + @numDebitBal  - @numCreditBal
insert into #BankCashBalance
values (@intSlno, @intAccCurrencyID, @intaccountid,  @strAccountDesc,isnull(@numopening,0), @numFacility,
isnull(@numBalance,0),@numpostdatedpayments,  @numpostdatedreceipts,
isnull(@numBalance,0)+ @numpostdatedpayments - @numpostdatedreceipts, @strCurrency)
set @intSlNo = @intSlNo + 1
set @numDebitBal = 0
set @numCreditBal = 0
set @numBalance = 0
set @strCurrency = '' ''
set @numpostdatedpayments =0
set @numpostdatedreceipts = 0
set @numopening = 0.0
fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,@intAccCurrencyID
end
end
select * from #BankCashBalance
drop table #BankCashBalance
close AccountCur
Deallocate AccountCur
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankCashBalance]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankCashBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- last modified : 25/01/2003
-- Modified by	 : leo
-- filter of deptaccounts given
CREATE proc [dbo].[spBankCashBalance] @intCompanyID as int, @strCurdate as varchar(10), @intdepid as int =0 as
begin
set nocount on
Declare
	@intSlNo as int,
	@intAccountID as int,
	@strAccountDesc as varchar(250),
	@intComCurrencyID as int,
	@intAccCurrencyID as int,
	@numFacility as numeric(18,2),
	@strCurrency as varchar(100),
	@numDebitBal as numeric(18,2),
	@numCreditBal as numeric(18,2),
	@numBalance as numeric(18,2),
	@numPostdatedPayments as numeric(18,2),
	@numPostdatedreceipts as numeric(18,2),
	@numopening as numeric(18,2),
	@dtcurdate as datetime
	set @dtcurdate = convert(datetime,@strcurdate)
Create table #BankCashBalance(
	Slno int,
	currencyid int,
	accountid int,
	AccDesc varchar(250),
	Opening numeric(18,2),
	Facility numeric(18,2),
	Balance numeric(18,2),
	postdatedpayments numeric(18,2),
	postdatedreceipts numeric(18,2),
	netbalance numeric(18,2),
	Currency varchar(100)
	)
	select top 1 @intComCurrencyID = CurrencyID from acompanymaster where companyid =
	@intCompanyID
	
if @intdepid =0
	declare AccountCur cursor for
	select AccountID, AccountDesc, BudgetAmount,
	CurrencyID from aaccountmaster
	where groupid = (select bankgroupid from asettings where companyid = @intCompanyID)
	and companyid = @intcompanyid  order by groupid,CurrencyID,AccountDesc
else
	declare AccountCur cursor for
	select AccountID, AccountDesc, BudgetAmount,
	CurrencyID from aaccountmaster a, adeptaccounts da
	where a.companyid = da.dacompanyid and a.accountid = da.daaccountid and  a.groupid =
		(select bankgroupid from asettings where companyid = @intCompanyID)
	and a.companyid = @intcompanyid and da.dadepartmentid = @intdepid order by groupid,CurrencyID,AccountDesc
	
	open AccountCur
	set @intSlno = 1
	fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,
	@intAccCurrencyID
	while @@fetch_status <> -1
	begin
		select @strCurrency = CurrencyName from aCurrencyMaster where
		CurrencyID = @intAccCurrencyID	and companyid = @intCompanyID
		if (@intAccCurrencyID = @intComCurrencyID)
		begin			
			set @numopening = 0.0 			
			exec spopeningbalance @strCurdate, @intAccountID, @intcompanyid,
			''C'', @numopening output
			select @numDebitBal = isnull(sum(amount),0) from vwjournaldetails JD,
			moajournalheader JH, acompanymaster c
			where  c.companyid = jh.companyid and JD.journalid = JH.journalid and JH.cancel = 0 and
			JH.companyid = JD.companyid and JH.companyid = @intcompanyid and
			JD.journalcredit = 0 and JD.AccountID = @intAccountID and
			jh.financialid <> 0 and journaldate=@strCurDate
			select @numCreditBal = isnull(sum(amount),0) from vwjournaldetails JD, moajournalheader JH, acompanymaster c
			where  c.companyid = jh.companyid and
			JD.journalid = JH.journalid and JH.cancel = 0 and JH.companyid = JD.companyid and
			JH.companyid = @intcompanyid and JD.journalcredit = 1 and JD.AccountID = @intAccountID	and
			jh.financialid <> 0 and journaldate=@strCurDate
									
			select @numpostdatedpayments = isnull(sum(creditamt),0) from
			vwpostdatedpayments where companyid = @intcompanyid and accountid =
			@intAccountID and chequedate > @dtcurdate
			select @numpostdatedreceipts = isnull(sum(debitamt),0) from
			vwpostdatedreceipts where companyid = @intcompanyid and accountid =
			@intAccountID and chequedate > @dtcurdate			
		end
		else
		begin
			
			set @numopening = 0.0
			exec spopeningbalance @strCurdate, @intAccountID, @intcompanyid,
			''B'', @numopening output
			select @numDebitBal = isnull(sum(actualamount),0) from vwjournaldetails JD, moajournalheader JH, acompanymaster c
			where  c.companyid = jh.companyid and
			JD.journalid = JH.journalid and JH.cancel = 0 and JH.companyid = JD.companyid and
			JH.companyid = @intcompanyid and JD.journalcredit = 0 and JD.AccountID = @intAccountID and
			jh.financialid <> 0 and journaldate=@strCurDate
	
			select @numCreditBal = isnull(sum(actualamount),0) from vwjournaldetails JD, moajournalheader JH, acompanymaster c
			where  c.companyid = jh.companyid and
			JD.journalid = JH.journalid and JH.cancel = 0 and JH.companyid = JD.companyid and
			JH.companyid = @intcompanyid and JD.journalcredit = 1 and JD.AccountID = @intAccountID and
			jh.financialid <> 0 and journaldate=@strCurDate
			select @numpostdatedpayments = isnull(sum(creditactualamt),0) from
			vwpostdatedpayments where companyid = @intcompanyid and accountid =
			@intAccountID and chequedate > @dtcurdate
			select @numpostdatedreceipts = isnull(sum(debitactualamt),0) from
			vwpostdatedreceipts where companyid = @intcompanyid and accountid =
			@intAccountID and chequedate > @dtcurdate			
		end
		
		set @numBalance = isnull(@numopening,0) + @numDebitBal  - @numCreditBal
		insert into #BankCashBalance values (@intSlno, @intAccCurrencyID, @intaccountid,  @strAccountDesc,
		isnull(@numopening,0), @numFacility, isnull(@numBalance,0),@numpostdatedpayments,
		@numpostdatedreceipts,isnull(@numBalance,0)+ @numpostdatedpayments -
		@numpostdatedreceipts, @strCurrency)
		
		set @intSlNo = @intSlNo + 1
		set @numDebitBal = 0
		set @numCreditBal = 0
		set @numBalance = 0	
		set @strCurrency = '' ''
		set @numpostdatedpayments =0
		set @numpostdatedreceipts = 0	
		set @numopening = 0.0
		fetch next from AccountCur into @intAccountID, @strAccountDesc, @numFacility,
		@intAccCurrencyID
	end
end
select * from #BankCashBalance
drop table #BankCashBalance
close AccountCur
Deallocate AccountCur
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankBalance]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Object:  Stored Procedure dbo.spBankBalance    Script Date: 18/01/2003 9:45:45 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
--Last Modified on 	: 14/07/03
--Modified by 		: Venki
--Comments 		: adding dept filteration
--Last Modified on 	: 16/07/03
--Modified by 		: Venki
--Comments 		: adding additional 1 day for gettig correct cash balance
CREATE proc [dbo].[spBankBalance] @intCompanyID as int, @intAccID as int ,@strToDate as varchar(10),
@intdepid as int =0
as
set nocount on
begin
Declare @numopeningamt as numeric(18,2)	,
@dtdate as datetime
	set @dtdate = dateadd(day,1,convert(datetime,@strToDate,101))
	set @strToDate = convert(varchar(12),@dtdate,111 )
	exec spopeningbalance @strToDate, @intaccid, @intcompanyid, ''a'', @numopeningamt output ,@intdepid
	if isnull(@numopeningamt,0) > 0
		select @intaccid AS AccountID, 0.00 AS OpeningCredit, @numopeningamt AS OpeningDebit
	else	
		select @intaccid AS AccountID, abs(@numopeningamt) AS OpeningCredit, 0.00 AS OpeningDebit
end
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBoatNote]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBoatNote]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By 	: R Harikrishnan
--Created on	: 09/07/2003
--Comments	: For Handling Debit note report
--Modifed by    : dheena
--Purpose       : add two fields boatname and no
-----------------------------------------------------------------------
CREATE Proc [dbo].[spBoatNote]
	(	
		@intShopID 	as int,
		@intBoatNoteID 	as int
	)
as
select
	bnh.bnhboateNoteNo,bnh.bnhboatenotedate,bnh.bnhboatenotedate,bnh.bnhRemark,
	bnh.bnhsentBy,bnd.bndPacking,bnd.bndqty,bnd.bndunit,bnd.bndnoofpackage,
	bnd.bndremarks,case when bndStatus=''D'' then ''Processed''
			    when bndStatus=''P'' then ''Pending''
			    when bndStatus=''N'' then ''Not Available''
			    when bndStatus=''M'' then ''Returned''
			    else ''Others'' end Status,
	cm.CustomerName,lh.lpdItemDesc,lh.LPClrReqPONo,lh.LPVendorName,
	itmd.clrItemDesc,itmd.ClrReqPONo,itmd.clrVendorName,
	bnh.bnhboatname,bnhattento
from
	losShipmentBNHeader bnh,aCustomerMaster cm,losShipmentBNDetail bnd
	left Outer Join (select
		lph.shopID,lph.POID,lph.PONo,lpd.DetailID,lpd.ItemDescription lpdItemDesc,
		crh.ClearenceReqNo,crh.PONo LPClrReqPONo,lph.VendorName LPVendorName
	From
		LosLPHeader lph, LosLPDetail lpd, losLocalClearenceRequestHeader crh
	Where
		lph.ShopID=lpd.ShopID and lph.POID=lpd.POID and lph.ShopID=crh.ShopID and
		lph.ClearenceReqID=crh.ClearenceReqID )lh
	on bnd.bndShopID=lh.ShopID and bnd.bndLPPOID=lh.POID and bnd.bndlpdetailid=lh.DetailID
	Left Outer Join (select
		itd.shopID,itd.ClearenceID,itd.DetailID,itd.ItemDescription clrItemDesc,
		ch.ClearenceNo,rh.ClearenceReqNo,rh.PONo ClrReqPONo,rh.VendorName clrVendorName
	From
		ShipmentClearenceItemDetails itd, ShipmentClearenceHeader ch,
		ClearenceRequestHeader rh
	Where
		itd.ShopID=ch.ShopID and itd.ClearenceID=ch.ClearenceID and
		itd.ShopID=rh.ShopID and itd.ClearenceReqID=rh.ClearenceReqID) itmd
	on bnd.bndShopID=itmd.ShopID and bnd.bndClearanceID=itmd.ClearenceID and
	bnd.bndclearanceDetailId = itmd.DetailID
where
	bnh.bnhCustomerId=cm.customerID and bnh.bnhShopID = bnd.bndShopID and
	bnh.bnhBoatNoteID=bnd.bndBoatNoteID and bnh.bnhShopID =@intShopID and
	bnh.bnhBoatNoteID=@intBoatNoteID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spbsuserformat]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spbsuserformat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--spbsuserformat ''20100222'', 1,8,2,0
--spbsuserformat ''20100606'',1,4,2,0
/****** Object:  Stored Procedure dbo.spbsuserformat    Script Date: 18/01/2003 9:45:45 PM ******/
-- Last Modified on : 07/12/2002
-- Modified by      : leo
--
-- Last Modified on : 13/05/2004
-- Modified by      : venkitesh
-- Desc      : Modified for acccountid took from the table named aRepFormatAccounts
---------------------------------------------------------------------------------
-- Modified By : Nidheesh P V
-- Modified on : 03/06/2010
-- Commentes : changed the the way to calculate the amount in a particular account
--:first find the opening balance for an account(''A'' or ''L'') and find the total amount
--:for ''A'' account total amount-->@dbldebit - @dblcredit + @AccountOBamount
--:for ''L'' account total amount-->@dblcredit - @dbldebit - @AccountOBamount
---------------------------------------------------------------------------------
CREATE  proc [dbo].[spbsuserformat] (@strToDate as varchar(10), @intCompanyID as integer,
@intformatid as int, @intdep as int =0, @bitcons as bit)
as
set nocount on
Declare @AcCode as varchar(50),
@AcID as integer,
@AccDesc as varchar(100),
@AcType as varchar(1),
@dblDebit as numeric(18,2),
@dblCrEDit as numeric(18,2),
@AccountOBamount as numeric(18,2),
@AccountOBdepamount as numeric(18,2),
@JournalOBDr as numeric(18,2),
@JournalOBCr as numeric(18,2),
@OBDr as numeric(18,2),
@OBCr as numeric(18,2),
@GroupDesc as varchar(50),
@GroupID as integer,
@CompanyName as varchar(100),
@dtFROMDate as datetime,
@dtToDate as datetime,
@intrepgroupid as int,
@striscaption as varchar(5),
@intparentgroupid as int,
@strrepgroupname as varchar(50),
@strnote as varchar(50),
@intcolwidth as int,
@strdwise as char(1),
@intdorder as int,
@intfinmonth as varchar(5),
@intfinyear as varchar(5),
@numamount as numeric(18,2),
@strpartcode as varchar(5),
@intretainedacc as int,
@DebtorID as int,
@CreditorID  as int,
@strfromdate as varchar(10)
Create table #PL(
CompanyID integer,
AcID int,
AccCode varchar(50),
AccDesc varchar(100),
AcType varchar(1),
GroupID integer,
GroupName varchar(50),
amount numeric(18,2),
ParentGroupID int,
reportgroupid int,
repgroupname varchar(50),
note varchar(50),
dwise char(1),
dorder int)
-- getting the start date of the fin year
select @dtFromDate = sdate, @strfromdate=convert(varchar,sdate,120) from vwfinyearperiod where
convert(datetime,@strToDate,101) between sdate and edate
SELECT @dtToDate = convert(datetime, @strToDate)
select @strpartcode = partionchar from aaccrepformat where companyid = @intcompanyid and
formatid = @intformatid  and type = ''b''
set @strpartcode = ''%''+rtrim(ltrim(@strpartcode))+''%''
Declare curbs Cursor For
--Commented By Venkitesh For Changingt to took the accountid from Table
SELECT arg.AccountID, GM.GroupID, GM.GroupDesc, AccountCode, AccountDesc, AccountType,
isnull(Openingamount,0) obcr, isnull(Openingdepamount,0) obdr, ParentGroupID,
arg.repgroupid, repg.groupname,repg.groupcode,repg.departmentwise,repg.displayorderid
FROM  aGroupMaster GM, (select a.companyid,a.Openingamount,a.Openingdepamount, a.accountcode,
a.accountdesc,a.accountid,b.formatid,b.groupid repgroupid,a.GroupID accGroupid
from aAccountMaster a, aRepFormatAccounts b
where a.accountid=b.accountid and a.companyid=b.companyid) arg,
aaccrepgroup repg, aaccrepformat repf
WHERE
arg.companyid =repg.companyid and arg.repgroupid = repg.groupid and repg.formatid=repf.formatid
and repf.companyid=repg.companyid
AND (GM.AccountType = ''a'' OR GM.AccountType = ''l'')
and gm.groupid=arg.accgroupid
AND GM.CompanyID = arg.companyid  AND arg.CompanyID = @intCompanyID and
repg.formatid = @intformatid and repf.type = ''b''
--and am.accountid <> (select Retainedearningsacc from asettings where companyid = @intcompanyid)
ORDER BY repg.displayorderid
--Commented By Venkitesh For Changingt to took the accountid from Table
/*SELECT am.AccountID, GM.GroupID, GM.GroupDesc, AccountCode, AccountDesc, AccountType,
isnull(Openingamount,0) obcr, isnull(Openingdepamount,0) obdr, ParentGroupID,
arg.repgroupid, repg.groupname,repg.groupcode,repg.departmentwise,repg.displayorderid
FROM aAccountMaster AM, aGroupMaster GM, (select companyid, accountid,
(case isnumeric(substring(controlledaccount, patindex(@strpartcode,controlledaccount)+2,3)) when 1
then (convert(int,substring(controlledaccount, patindex(@strpartcode,controlledaccount)+2,3))) when 0 then 0 end) repgroupid
from aAccountMaster) arg,  aaccrepgroup repg, aaccrepformat repf
WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''a'' OR GM.AccountType = ''l'')
AND GM.CompanyID = am.companyid  AND AM.CompanyID = @intCompanyID and
am.companyid = arg.companyid and arg.accountid = am.accountid and arg.companyid =
repg.companyid and arg.repgroupid = repg.groupid and repg.companyid = repf.companyid and
repg.formatid = repf.formatid and repg.formatid = @intformatid and repf.type = ''b''
--and am.accountid <> (select Retainedearningsacc from asettings where companyid = @intcompanyid)
ORDER BY repg.displayorderid*/
Open curbs
Fetch Next FROM curbs into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,
@AccountOBamount, @AccountOBdepamount, @intParentGroupID, @intrepgroupid, @strrepgroupname,
@strnote, @strdwise, @intdorder
while @@fetch_status =0
begin
set @dblDebit = 0.0
set @dblCrEDit = 0.0
set @AccountOBdepamount = 0.0
set @AccountOBAmount = 0.0
if @AcType = ''A''
begin
if @bitcons =1
--exec spopeningbalance @strFromDate, @AcID, @intcompanyid, ''c'', @AccountOBdepamount output, @intdep
exec spopeningbalance @strFromDate, @AcID, @intcompanyid, ''c'', @AccountOBAmount output, @intdep
else
exec spopeningbalance @strFromDate, @AcID, @intcompanyid, ''d'', @AccountOBamount output, @intdep
SET @AccountOBamount = isnull(@AccountOBamount,0)
--SET @AccountOBAmount = isnull(@AccountOBAmount,0)
end
else if @AcType = ''L''
begin
if @bitcons = 1
exec spopeningbalance @strFromDate ,@AcID,@intcompanyid,''c'',@AccountOBamount output, @intdep
else
--exec spopeningbalance @strFromDate ,@AcID,@intcompanyid,''d'',@AccountOBAmount output, @intdep
exec spopeningbalance @strFromDate ,@AcID,@intcompanyid,''d'',@AccountOBamount output, @intdep
SET @AccountOBamount = isnull(@AccountOBamount,0)
--SET @AccountOBdepamount = isnull(@AccountOBdepamount,0)
end
if @intdep = 0 --with out department seletion
SELECT @dblDebit = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0) else
isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH,
acompanymaster c WHERE c.companyid = jh.companyid and JD.JournalID = JH.JournalID AND
JH.CompanyID = @intCompanyID AND JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND
(JH.JournalDate >= @dtFROMDate AND JH.JournalDate <= @dtToDate) AND JD.JournalCrEDit
= 0 AND JD.AccountID = @AcID and jh.financialid > 0 Group By JD.AccountID
else -- for departmentwise selection
SELECT @dblDebit = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0) else
isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH,
acompanymaster c WHERE c.companyid = jh.companyid and JD.JournalID = JH.JournalID
AND JH.CompanyID = @intCompanyID AND JH.Cancel = 0 AND JD.CompanyID = @intCompanyID
AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <= @dtToDate) AND
JD.JournalCrEDit = 0 AND JD.AccountID = @AcID and jh.financialid > 0
and jd.departmentid = @intdep Group By JD.AccountID
--set @dbldebit = @dbldebit + @AccountOBdepamount +@AccountOBAmount
if @intdep=0 -- for with out departmentwise selection
SELECT @dblCrEDit = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0) else
isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH,
acompanymaster c
WHERE c.companyid = jh.companyid and JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND
JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
@dtToDate) AND JD.JournalCrEDit = 1 AND JD.AccountID = @AcID and jh.financialid > 0 Group by JD.AccountID
else -- for departmentwise selection
SELECT @dblCrEDit = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0) else
isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH,
acompanymaster c
WHERE c.companyid = jh.companyid and JD.JournalID = JH.JournalID AND JH.CompanyID = @intCompanyID AND
JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (JH.JournalDate >= @dtFROMDate AND JH.JournalDate <=
@dtToDate) AND JD.JournalCrEDit = 1 AND JD.AccountID = @AcID and jh.financialid > 0
and  jd.departmentid= @intdep Group by JD.AccountID
-- set @dblcredit = @dblcredit + @AccountOBdepamount +@AccountOBAmount
if (@actype =''a'')
insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType, @GroupID,
@GroupDesc,  @dbldebit + @AccountOBamount-@dblcredit, @intparentgroupid, @intrepgroupid,
@strrepgroupname,@strnote,@strdwise,@intdorder)
else
insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType, @GroupID,
@GroupDesc,  @dblcredit - @dbldebit - @AccountOBamount , @intparentgroupid, @intrepgroupid,
@strrepgroupname,@strnote,@strdwise,@intdorder)
Fetch Next FROM curbs into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,
@AccountOBamount, @AccountOBdepamount, @intParentGroupID, @intrepgroupid,
@strrepgroupname, @strnote,@strdwise,@intdorder
end
declare @numprofitamt as numeric(18,2)
exec spPLcarryforwardamt @strtodate, @intcompanyid, 0, @numprofitamt output, @intdep,
@bitcons
SELECT companyid, max(repgroupname) groupname, isnull(max(note),'''') note,
isnull(sum(amount),0) amount, max(dwise) gp, @numprofitamt profitamt
FROM #PL group by companyid, reportgroupid
select *, @numprofitamt profitamt from #pl
--end
close curbs
deallocate curbs
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRebateRequest]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebateRequest]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------
--Created on 	: 22/05/2003
--Created by	: R Harikrishnan
--Comments	: For Rebate Request transaction report
-----------------------------------------------------------------
CREATE Procedure [dbo].[spRebateRequest]
	@intShopID 	as int,
	@intRequestID	as int
as
select
	rr.rrreqno,rr.rrreqdate,sm.sperName,ind.IDinvoiceid,ind.idItemID,
	ind.idPQuantity,ind.idUnitPrice,ind.idrebateamount,cm.CustomerName,
	itm.ItemCode,itm.ItemDescription
from
	losrebaterequest rr,losinvoiceheader ih,losinvoicedetail ind, aitem itm,
	aSalesPersonMaster sm,aCustomerMaster cm
where
	rr.rrshopid=ih.ihshopid and rr.rrpoid=ih.ihInvoiceID and
	rr.rrSalesPersonID=sm.sperID and ih.ihshopid=ind.idShopID and
	ih.ihInvoiceID=ind.idInvoiceID and ind.idItemID=itm.itemid and
	ih.ihCustomerID=cm.CustomerID and
	rr.rrreqid=@intRequestID and rr.rrshopid= @intShopID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReexportProjFlow]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReexportProjFlow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spReexportProjFlow 1,4,31
--created on 02/03/2004
--create by dhenea
--purpose :display the Reexport Details
-----------------------------------------
CREATE   proc [dbo].[spReexportProjFlow]
			(@intcompanyid as int,
			 @intshopid as int,
			 @inttransID as int)
	as
	begin
		set nocount on
		Declare
			@intcounter as int,
			@intreferenceid as int,
			@intpandcquotid as int,
			@intpandcrequestid as int,
			@intdepartmentid as int,
			@intpandcpoid as int,
			@intshopquotid as int,
			@intshoporderid as int,
			@intshopinvid as int,
			@blnQuotation as bit,
			@performaid as int
		
	Create table ##ShoprequestFlow(
			CompanyID int,
			Shopid int,
			Transid int,
			Transno  varchar(200),
			TranDate datetime,
			TranName varchar(250),
			Suppid int,
			suppName varchar(250),
			custid int,
			custname varchar(250),
			Remarks varchar(250),
			TransType char(3),
			ReferenceNo varchar(50), --rehReferenceNo
			Paymentterm varchar(250), --rehPaymentterm
			BuyerPoNo varchar(50), --rehBuyerPoNo
			BuyerName varchar(250),-- rehBuyerName
			BuyerAddress varchar(250), --rehBuyerAddress
			LoadedDate datetime, -- rehloadeddate
			ConsigneeName varchar(250), -- rehConsigneeName
			ShipmentDepartureDate datetime, --rehShipmentDepartureDate
			ContainerNo varchar(250),--rehContainerNo
			rehAdvanceAmt numeric (18,2), -- rehAdvanceAmt
			DeliveryDate datetime,   --rehDeliveryDate
			paymenttrem varchar(250), -- rehpaymentterm
			SellingTerm varchar(250),		 --Rehprictype
			flowid int,
			countryname varchar(250) --cust/vendor customer
		 			)
			
		begin 	
			select @intdepartmentid=departmentid from ashops where shopid=@intshopid	
			---Shop Request details - s
			select @intcounter=count(GRHrequestID),@intreferenceid=GRHrequestID
			from mosgoodsrequestheader,mosRequestInvDetail where
			GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
			GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
			reqReexportID=@inttransid and reqReexportID is not null
			group by GRHrequestID, GRHshopID
			
		
			if @intcounter>0
		
			   begin
		                  insert into ##ShoprequestFlow
				  select @intcompanyid,@intshopid,GRHrequestID,GRHrequestno,
				  Grhrequestdate,''Goods Request To HQ'',v.vendorid,
				  v.vendorname,c.customerid,c.customername,GRHremarks,''GR'',
				  Null,null,null,null,null,null,Null,null,null,null,Null,null,null,2,			
				  cn.countryname	
				  from mosgoodsrequestheader,mosRequestInvDetail,losexportheader loe
				  left outer  join acustomermaster c on
					rehcustomerID=customerid and rehcompanyid=c.companyid 	
			          left outer join avendormaster v on
					rehVendorID=vendorid and rehcompanyid=c.companyid	
			          left outer join acountrymaster cn on
					isnull(c.countryid,v.countryid)=cn.countryid
				  where
				  rehExportID=@inttransid  and rehShopID=@intshopid and
				  rehexportid=reqReexportID and	
				  GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
			          GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
		     	          reqReexportID=@inttransid group by GRHrequestID, GRHshopID,
				  GRHrequestID,GRHrequestno,Grhrequestdate,grhremarks,
				  c.customerid,c.customername,v.vendorid,v.vendorname,cn.countryname	
			   	  set  @intcounter=0
			   end	
		
			else
		
			    begin					
		  		set @intreferenceid=0
				set  @intcounter=0
			   end	
					
			
		--- Pandc Request -s
			select @intcounter=count(pohPoid),@intpandcrequestid=pohPoid ,
			@intdepartmentid=pohDepartmentid
			from loPurchaseOrderHeader where
			pohtype=''R'' and pohrequestid  =@intreferenceid
			and  pohdepartmentid=@intdepartmentid and pohcancel=0
			group by pohPoid,pohDepartmentid	
	
			if @intcounter>0
			   begin	
		
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Request'',
				pohVendorID,vendorname,NULL,NULL,pohremarks,''PR'',
				null,null,null,null,null,null,
				null,null,null,null,null,null,Null,3,cn.countryname
				from loPurchaseOrderHeader
				left outer join avendormaster v
					on pohVendorID=vendorid
					and pohcompanyid=companyid
				left outer join acountrymaster cn
					on v.countryid=cn.countryid
			
				where pohtype=''R'' and
				pohShopID=@intshopid and pohCompanyID=@intcompanyid
				and pohpoID=@intpandcrequestid				
				set  @intcounter=0
			  end
			else
				begin
			  		set @intreferenceid=0
					set @intcounter=0	
				end
		
	--pandc quotation--s
			select @intcounter=count(pohPoid),@intpandcquotid=pohPoid ,
			@intdepartmentid=pohDepartmentid
			from loPurchaseOrderHeader where
			left(pohtype,1)=''Q'' and pohQuotationid=@intpandcrequestid
			and  pohdepartmentid=@intdepartmentid and pohcancel=0
			group by pohPoid,pohDepartmentid	
			
			select @intcounter=count(rehExportID),@intpandcquotid=rehExportID,
			@intdepartmentid=rehDepartmentID from losexportheader where
			left(rehtype,1)=''Q'' and rehShopID=@intshopid and
			rehProformaID=@intreferenceid and rehCancelled=0
			group by rehExportID,rehDepartmentID	
			if @intcounter>0
			   begin
					
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Quotation'',pohVendorID,
				vendorname,NULL,NULL,pohremarks,''PQ'',
				null,null,null,null,null,null,
				null,null,null,null,null,null,Null,4,cn.countryname
				from loPurchaseOrderHeader,avendormaster v
				left outer join acountrymaster cn
					on v.countryid=cn.countryid
				where
				vendorid=pohVendorID and v.companyid=pohcompanyid	and
				pohtype=''Q''  and
				pohQuotationid in (select pohPoid
				from loPurchaseOrderHeader where
				pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid)
				and pohdepartmentid=@intdepartmentid
				group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid,cn.countryname
					
				set  @intcounter=0
			   end
			else
			    begin	
			  	 set @intreferenceid=0
	  			 set @intcounter=0
		   	    end	
	--shop Quotation
		set @blnQuotation =0
		set @performaid = @inttransid
	
		 while  @performaid >0
		    begin	
			select @intcounter=count(rehExportID),@intshopquotid=rehExportID
			from losexportheader where
			left(rehtype,1)=''Q'' and rehProformaID=@performaid
			and rehshopid=@intshopid and rehcompanyid=@intcompanyid
			and rehCancelled =0
			group by rehexportid,rehshopid
			if @intcounter>0
			   begin
				
		                insert into ##ShoprequestFlow
			
				select @intcompanyid,@intshopid,rehEXPORTid,rehexportno,
				rehexportdate,''Export Quotation'',v.vendorid,
				v.vendorname,c.customerid,c.customername,rehremarks,''SQ'',
				rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype,5,cn.countryname
				from losexportheader
				left outer  join acustomermaster c on
					rehcustomerID=customerid and rehcompanyid=c.companyid
				left outer join avendormaster v on
					rehVendorID=vendorid and rehcompanyid=c.companyid	
				left outer join acountrymaster cn on
					isnull(c.countryid,v.countryid)=cn.countryid
				where
				left(rehtype,1)=''Q'' and rehProformaID=@performaid
				and rehshopid=@intshopid and rehCancelled =0
				group by rehexportid,rehexportno,rehremarks,rehexportdate,rehshopid,
				rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				c.customerid,c.customername,v.vendorid,v.vendorname,cn.countryname,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype
				set @performaid=@intshopquotid
				set  @intcounter=0
			   end
			else
			    begin	
			  	 set @intreferenceid=0
	  			 set @intcounter=0
				 break
		   	    end	
		    end
		
	--Shop Order
					
			select @intcounter=count(rehexportID),@intshoporderid=rehexportid
			from losexportheader where
			rehtype=''P'' and rehProformaID=@intshopquotid
			and rehshopid=@intshopid and rehcompanyid=@intcompanyid
			AND rehCancelled =0
			group by rehexportid,rehshopid
			
			if @intcounter>0
			   begin
					
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,rehexportid,rehexportno,
				rehexportdate,''Export Order'',v.vendorid,
				v.vendorname,c.customerid,c.customername,rehremarks,''SP'',
				rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype,6,cn.countryname
				from losexportheader
				left outer  join acustomermaster c on
					rehcustomerID=customerid and rehcompanyid=c.companyid
				left outer join avendormaster v on
					rehVendorID=vendorid and rehcompanyid=c.companyid	
				left outer join acountrymaster cn on
					isnull(c.countryid,v.countryid)=cn.countryid
				 where
				rehtype=''P'' and rehProformaID=@intshopquotid
				and rehshopid=@intshopid AND rehCancelled =0
				group by rehexportid,rehexportno,rehremarks,rehexportdate,rehshopid,
				rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype,
				c.customerid,c.customername,v.vendorid,v.vendorname,cn.countryname	
				set  @intcounter=0
			   end
			else
			    begin	
			  	 set @intreferenceid=0
	  			 set @intcounter=0
		   	    end	
	--pandc Purchase Order
			select @intcounter=count(pohPoid),@intpandcpoid=pohpoid
			from loPurchaseOrderHeader where
			pohtype=''P'' and pohQuotationid= @intpandcquotid
			AND pohcancel=0
			and pohdepartmentid=@intdepartmentid
			group by pohPoid	
			if @intcounter>0
			     begin
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Order'',pohVendorID,vendorname,Null,null,pohremarks,''PO'',
				Null,null,null,null,null,null,null,null,null,null,null,null,null,7,cn.countryname
				from
				loPurchaseOrderHeader,avendormaster v
				left outer join acountrymaster cn
					on v.countryid=cn.countryid
				where
				vendorid=pohVendorID and v.companyid=pohcompanyid	and
				pohtype=''P''  and  pohcancel=0 AND
				pohQuotationid in( select transid from ##ShoprequestFlow
				where transtype=''PQ'')
				and pohdepartmentid=@intdepartmentid
				group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,cn.countryname
				set  @intcounter=0
			     end	
			else
			     begin	
				 set @intreferenceid=0
				 set @intcounter=0
			     end	
	--pandc Purchase Bill
			select @intcounter=count(pbhBillID)
			from losPpurchasebillheader
			where pbhPOID= @intpandcpoid
			and pbhdepartmentid=@intdepartmentid
			AND pbhCancelled  =0
			group by pbhbillid	
			if @intcounter>0
			     begin
		             insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pbhBillID,pbhBillNo,
				pbhBillDate,''PandC Purchase Bill'',pbhVendorID,vendorname,Null,Null,
				pbhRemarks,''PB'',Null,null,null,null,null,null,null,null,null,null,null,null,null,8,cn.countryname
				from losPpurchasebillheader,avendormaster v
				left outer join acountrymaster cn
					on v.countryid=cn.countryid	
				 where
				vendorid=pbhVendorID and v.companyid=pbhcompanyid
				AND pbhCancelled  =0 AND
				pbhPOID in( select transid from ##ShoprequestFlow
				where transtype=''PO'')
				and pbhdepartmentid=@intdepartmentid
				group by pbhbillid,pbhbillno,pbhremarks,pbhvendorid,pbhbilldate,
				vendorname,cn.countryname
			     end	
			else
			     begin	
				 set @intreferenceid=0
				 set @intcounter=0
			     end	
	--Shop Invoice
								
			select @intcounter=count(rehexportID),@intshopinvid=rehexportID
			from losexportheader where
			rehtype=''I'' and rehProformaID=@intshoporderid
			and rehshopid=@intshopid and rehcompanyid=@intcompanyid
			AND rehCancelled =0
			group by rehexportid,rehshopid
			
			if @intcounter>0
			   begin
					
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,rehexportid,rehexportno,
				rehexportdate,''Export Invoice'',v.vendorid,
				v.vendorname,c.customerid,c.customername,rehremarks,''SI'',
				rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype,9,cn.countryname
				from losexportheader
				left outer  join acustomermaster c on
					rehcustomerID=customerid and rehcompanyid=c.companyid
				left outer join avendormaster v on
					rehVendorID=vendorid and rehcompanyid=c.companyid	
				left outer join acountrymaster cn on
					isnull(c.countryid,v.countryid)=cn.countryid
				where
				rehtype=''I'' and rehProformaID=@intshoporderid
				and rehshopid=@intshopid
				AND rehCancelled =0	
				group by rehexportid,rehexportno,rehremarks,rehexportdate,
				rehshopid,c.customerid,c.customername,v.vendorid,
				v.vendorname,cn.countryname,rehReferenceNo,rehPaymentterm,rehBuyerPoNo,rehBuyerName,rehBuyerAddress,
				rehloadeddate,rehConsigneeName,rehShipmentDepartureDate,rehContainerNo,
				rehAdvanceAmt,rehDeliveryDate,rehpaymentterm,Rehpricetype
				set  @intcounter=0
			   end
			else
			    begin	
			  	 set @intreferenceid=0
	  			 set @intcounter=0
		   	    end	
	end
			Select * From ##ShoprequestFlow order by flowid
			drop table ##ShoprequestFlow
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on	: 26/08/2003
-- Created by	: Kishore
-- Comments	: This sp sets the Expiry stock of all items, which
--                are not verified in a total stock verification,
--                to zero
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]
				(@intSvdId as int,
				 @intShopId as int,
				 @intExpiryIssueDetailId as int OUTPUT,
				 @intExpiryArrivalDetailId as int OUTPUT) AS
Begin
	Declare @intItemId as int
	Declare @numcurExpiryStock as Numeric(18, 2)
	Declare @dtExpiryDate as DateTime
	
	-- cursor to loop through the non-verified items
	Declare curNonVerifiedItems Cursor For
		SELECT ItemId FROM mosShopStock
		WHERE ShopId = @intShopId
		AND ItemId NOT IN
			(SELECT ItemId FROM losStockVerificationDetail
			WHERE svdId = @intSvdId
			AND svdShopId = @intShopId)
	
	-- cursor to loop through distinct expiry dates
	Declare curExpiry Cursor For
		SELECT DISTINCT ExpiryDate FROM
			(SELECT eadExpiryDate ExpiryDate FROM losExpiryArrivalDetails
			WHERE eadShopId = @intShopId
			AND eadCancel = 0
			UNION ALL
			SELECT eidExpiryDate ExpiryDate FROM losExpiryIssueDetails
			WHERE eidShopId = @intShopId
			AND eidCancel = 0) a		
	Open curExpiry
	Open curNonVerifiedItems
	
	-- get first non-verified itemid
	Fetch Next From curNonVerifiedItems Into @intItemID
	While @@fetch_status = 0
	Begin
		Fetch Next From curExpiry Into @dtExpiryDate
		
		-- check the item id in each Expiry
		While @@fetch_status = 0
		Begin
			-- first get the currect Expiry stock
		SELECT @numcurExpiryStock = qty
		FROM
	         	(SELECT ExpiryDate, ShopId,
			ItemId, SUM(qty) qty
	        	FROM
	       		(SELECT eadExpiryDate ExpiryDate,
			eadShopId ShopId, eadItemId ItemId , SUM(eadItemQty) qty
		FROM losExpiryArrivalDetails
	       		WHERE eadShopId = @intShopId
		AND eadItemId =  @intItemId
	       		AND eadCancel = 0
			AND eadExpiryDate = @dtExpiryDate
			GROUP BY eadExpiryDate, eadShopId, eadItemId
	        	UNION ALL
			SELECT eidExpiryDate, eidShopId, eidItemId, - SUM(eidItemQty)
	        	FROM losExpiryIssueDetails
	        	WHERE eidShopId = @intShopId
		        AND eidItemId = @intItemId
			AND eidCancel = 0
			AND eidExpiryDate = @dtExpiryDate
		        GROUP BY eidExpiryDate, eidShopId, eidItemId) a
		        GROUP BY ExpiryDate, ShopId, ItemId
		        HAVING SUM(qty) <> 0 ) b
		WHERE b.ItemId = @intItemId  -- for extra safety
		
			-- if stock > 0, insert to issue details
			-- otherwise insert to arrival details
			-- to make the net stock zero
			-- Do this only if stock <> 0
			If @numcurExpiryStock > 0
			Begin
				INSERT INTO losExpiryIssueDetails
				(eidinterfaceid, eidShopid, eidTransactionId, eiddetailid,
				eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
				eidpackingqty, eidcancel, eidadjustment)
				VALUES
				(1900, @intShopId, @intSvdId, @intExpiryIssueDetailId,
				@dtExpiryDate, @intItemId,
				ABS(@numcurExpiryStock), 1, ABS(@numcurExpiryStock), 0, 1)
				Set @intExpiryIssueDetailId = @intExpiryIssueDetailId + 1
			End
			Else If @numcurExpiryStock < 0
			Begin
				INSERT INTO losExpiryArrivalDetails
				(eadinterfaceid, eadShopid, eadtransactionid, eaddetailid,
				eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
				eadpackingqty, eadcancel, eadadjustment)
				VALUES
				(1900, @intShopId, @intSvdId, @intExpiryArrivalDetailId,
				@dtExpiryDate, @intItemId,
				ABS(@numcurExpiryStock), 1, ABS(@numcurExpiryStock), 0, 1)
				Set @intExpiryIssueDetailId = @intExpiryIssueDetailId + 1
			End		
			Fetch Next From curExpiry Into @dtExpiryDate
		End
		
		Fetch Next From curNonVerifiedItems Into @intItemID
	End
	Close curNonVerifiedItems
	Deallocate curNonVerifiedItems
	Close curExpiry
	Deallocate curExpiry
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spshoprequestflow]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spshoprequestflow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spshoprequestflow 1,12,47
--------------------------------------
--created on 27/11/03
--create by venkitesh
--purpose :display the transaction details
-----------------------------------------
CREATE  proc [dbo].[spshoprequestflow] (@intcompanyid as int, @intshopid as int,
@inttransID as int)
as
begin
	set nocount on
	Declare
	@intcounter as int,
	@intreferenceid as int,
	@intpandcquotid as int,
	@intpandcrequestid as int,
	@intdepartmentid as int	
	Create table ##ShoprequestFlow(
			CompanyID int,
			Shopid int,
			Transid int,
			Transno  varchar(200),
			TranDate datetime,
			TranName varchar(250),
			Suppid int,
			SuppName varchar(250),
			Remarks varchar(250),
			TransType char(3))
	
		begin
			select @intcounter=count(GRHrequestID),@intreferenceid=GRHrequestID
			from mosgoodsrequestheader,mosRequestInvDetail where
			GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
			GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
			reqinvdinvoiceid=@inttransid group by GRHrequestID, GRHshopID
			if @intcounter>0
			   begin
	                  insert into ##ShoprequestFlow
			  select @intcompanyid,@intshopid,GRHrequestID,GRHrequestno,
			   Grhrequestdate,''Goods Request To HQ'',Null,'''',GRHremarks,''SR''
			   from mosgoodsrequestheader,mosRequestInvDetail where
			   GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
		           GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
	     	           reqinvdinvoiceid=@inttransid group by GRHrequestID, GRHshopID,
			   GRHrequestID,GRHrequestno,Grhrequestdate,grhremarks
			   set  @intcounter=0
			 end	
			else
			    begin					
		  		set @intreferenceid=0
				set  @intcounter=0
			   end	
					
		--- Pandc Request
		
	
			select @intcounter=count(pohPoid),@intpandcrequestid=pohPoid, @intdepartmentid=pohDepartmentid
			from loPurchaseOrderHeader where
			pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid
			group by pohPoid,pohDepartmentid	
			if @intcounter>0
			   begin	
				
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Request'',pohVendorID,vendorname,poHremarks,''PR''
				from loPurchaseOrderHeader,avendormaster  where
				vendorid=pohVendorID and companyid=pohcompanyid	and
				pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid
				group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid	
				set  @intcounter=0
			  end
			else
				begin
			  		set @intreferenceid=0
					set @intcounter=0	
				end
		
	--pandc quotation
			select @intcounter=count(pohPoid),@intpandcquotid=pohPoid ,
			@intdepartmentid=pohDepartmentid
			from loPurchaseOrderHeader where
			pohtype=''Q'' and pohQuotationid=@intpandcrequestid
			and  pohdepartmentid=@intdepartmentid
			group by pohPoid,pohDepartmentid	
			
			if @intcounter>0
			   begin
					
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Quotation'',pohVendorID,vendorname,pohremarks,''PQ''
				from loPurchaseOrderHeader,avendormaster  where
				vendorid=pohVendorID and companyid=pohcompanyid	and
				pohtype=''Q''  and
				pohQuotationid=@intpandcrequestid
				and pohdepartmentid=@intdepartmentid
				group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid		
				set  @intcounter=0
			   end
			else
			    begin	
			  	 set @intreferenceid=0
	  			 set @intcounter=0
			    end	
		
	--pandc Purchase Order
			select @intcounter=count(pohPoid)
			from loPurchaseOrderHeader where
			pohtype=''P'' and pohQuotationid= @intpandcquotid
			and pohdepartmentid=@intdepartmentid
			group by pohPoid	
			if @intcounter>0
			     begin
		                insert into ##ShoprequestFlow
				select @intcompanyid,@intshopid,pohPoid,pohpono,
				pohPodate,''PandC Purchase Order'',pohVendorID,vendorname,pohremarks,''PO''
				from loPurchaseOrderHeader,avendormaster  where
				vendorid=pohVendorID and companyid=pohcompanyid	and
				pohtype=''P''  and
				pohQuotationid=@intpandcquotid
				and pohdepartmentid=@intdepartmentid
				group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname			
				set  @intcounter=0
			     end	
			else
			     begin	
				 set @intreferenceid=0
				 set @intcounter=0
			     end	
			
	end
			Select * From ##ShoprequestFlow
			drop table ##ShoprequestFlow
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopReqFlowWithPrj]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopReqFlowWithPrj]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------
--created on 27/11/03
--create by venkitesh
--Modified By : Hariharan
-- MOdifieed date : 16/12/2004
--purpose :display the transaction details
--    Added fromdate , todate parameter instead of using replace selection formula
-----------------------------------------
--spShopReqFlowWithPrj 1,12,543,2
CREATE  proc [dbo].[spShopReqFlowWithPrj] (@intcompanyid as int, @intshopid as int,
@inttransID as int,@intFromGRequest as int=0, @strFromDate varchar(10),
@strToDate varchar(10))
as
begin
set nocount on
Declare
@intcounter as int,
@intreferenceid as int,
@intpandcquotid as int,
@intpandcrequestid as int,
@intdepartmentid as int,
@intpandcpoid as int,
@intshopquotid as int,
@intshoporderid as int,
@intshopinvid as int
Create table ##ShoprequestFlow(
CompanyID int,
Shopid int,
Transid int,
Transno  varchar(200),
TranDate datetime,
TranName varchar(250),
Suppid int,
suppName varchar(250),
Remarks varchar(250),
TransType char(3),
ProjectStartDate datetime,
ProjectEndDate datetime,
ProjectOtherInfo varchar(250),
CustomDutyByCustomer bit,
Transportation varchar(50),
levels int,
idrPlanNo varchar(250),
idrRefNo  varchar(250),
idrNature varchar(250)
)
if  (@intFromGRequest=0  )
begin
select @intcounter=count(GRHrequestID),@intreferenceid=GRHrequestID
from mosgoodsrequestheader,mosRequestInvDetail where
GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
reqinvdinvoiceid=@inttransid group by GRHrequestID, GRHshopID
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,GRHrequestID,GRHrequestno,
Grhrequestdate,''Goods Request To HQ'',Null,'''',GRHremarks,''SR'',
null,null,null,null,null,1,null,null,null
from mosgoodsrequestheader,mosRequestInvDetail where
GRHrequestID=reqdid and GRHshopID=reqinvdshopid and
GRHshopID=@intshopid and grhrequesttype=''p'' and GRHcancel=0 and
reqinvdinvoiceid=@inttransid group by GRHrequestID, GRHshopID,
GRHrequestID,GRHrequestno,Grhrequestdate,grhremarks
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set  @intcounter=0
end
end
else
begin
set @intreferenceid = @inttransID
end
if (@intfromGrequest=2)
set @intreferenceid = @inttransID
--- Pandc Request
begin
--- Pandc Request
if (@intfromGrequest=0 or @intfromGrequest=1)
begin
select @intcounter=count(pohPoid),@intpandcrequestid=pohPoid, @intdepartmentid=pohDepartmentid
from loPurchaseOrderHeader where
pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid
and pohcancel=0 group by pohPoid,pohDepartmentid
end
else
begin
select @intcounter=count(pohPoid),@intpandcrequestid=pohPoid, @intdepartmentid=pohDepartmentid
from loPurchaseOrderHeader where
pohtype=''R'' and pohshopid=@intshopid and pohPoid=@intreferenceid
and pohcancel=0
group by pohPoid,pohDepartmentid
end
if @intcounter>0
begin
if (@intfromGrequest=0 or @intfromGrequest=1)
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pohPoid,pohpono,
pohPodate,''PandC Purchase Request'',pohVendorID,vendorname,poHremarks,''PR'',
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,
CONVERT(char(2),pohCustomDutyByCustomer),pohTransportation,2,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
from loPurchaseOrderHeader,avendormaster
left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@inttransid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pohVendorID and companyid=pohcompanyid and pohcancel=0 and
pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid
group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid,
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,CONVERT(char(2),pohCustomDutyByCustomer),
pohTransportation,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
end
else
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pohPoid,pohpono,
pohPodate,''PandC Purchase Request'',pohVendorID,vendorname,poHremarks,''PR'',
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,
CONVERT(char(2),pohCustomDutyByCustomer),pohTransportation,2,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
from loPurchaseOrderHeader,avendormaster
left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@inttransid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pohVendorID and companyid=pohcompanyid and pohcancel=0 and
pohtype=''R'' and pohshopid=@intshopid and pohpoid=@intreferenceid
group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid,
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,CONVERT(char(2),pohCustomDutyByCustomer),
pohTransportation,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set @intpandcrequestid= @intreferenceid
end
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--pandc quotation
select @intcounter=count(pohPoid),@intpandcquotid=pohPoid ,
@intdepartmentid=pohDepartmentid
from loPurchaseOrderHeader where
pohtype=''Q'' and pohQuotationid=@intpandcrequestid
and  pohdepartmentid=@intdepartmentid and pohcancel=0
group by pohPoid,pohDepartmentid
if @intcounter>0
begin
if (@intfromGrequest=0 or @intfromGrequest=1)
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pohPoid,pohpono,
pohPodate,''PandC Purchase Quotation'',pohVendorID,vendorname,pohremarks,''PQ'',
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,
CONVERT(char(2),pohCustomDutyByCustomer),pohTransportation,3,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
from loPurchaseOrderHeader,avendormaster
left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@inttransid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pohVendorID and companyid=pohcompanyid and
pohtype=''Q''  and
pohQuotationid in (select pohPoid
from loPurchaseOrderHeader where
pohtype=''R'' and pohshopid=@intshopid and pohrequestid=@intreferenceid)
and pohdepartmentid=@intdepartmentid
group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid,
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,CONVERT(char(2),pohCustomDutyByCustomer),
pohTransportation,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pohPoid,pohpono,
pohPodate,''PandC Purchase Quotation'',pohVendorID,vendorname,pohremarks,''PQ'',
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,
CONVERT(char(2),pohCustomDutyByCustomer),pohTransportation,3,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
from loPurchaseOrderHeader,avendormaster
left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@inttransid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pohVendorID and companyid=pohcompanyid and
pohtype=''Q''  and
pohQuotationid in (select pohPoid
from loPurchaseOrderHeader where
pohtype=''R'' and pohshopid=@intshopid and pohpoid=@intreferenceid)
and pohdepartmentid=@intdepartmentid
group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,pohDepartmentid,
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,CONVERT(char(2),pohCustomDutyByCustomer),
pohTransportation,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--shop Quotation
select @intcounter=count(ihInvoiceID),@intshopquotid=ihinvoiceid
from losinvoiceheader where
ihtype=''Q'' and ihProformaID=@inttransid
and ihshopid=@intshopid and ihcompanyid=@intcompanyid
and ihCancelled =0
group by ihinvoiceid,ihshopid
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,ihinvoiceid,ihinvoiceno,
ihinvoicedate,''Shop Quotation'',Null,Null,ihremarks,''SQ'',
Null,Null,null,NUll,Null,4,
prj.idrPlanNo,prj.idrRefNo,
prj.idrnature
from losinvoiceheader left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@intshopquotid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
ihtype=''Q'' and ihProformaID=@inttransid
and ihshopid=@intshopid and ihCancelled =0
group by ihinvoiceid,ihinvoiceno,ihremarks,ihinvoicedate,ihshopid,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--Shop Order
select @intcounter=count(ihInvoiceID),@intshoporderid=ihinvoiceid
from losinvoiceheader where
ihtype=''P'' and ihProformaID=@intshopquotid
and ihshopid=@intshopid and ihcompanyid=@intcompanyid
AND ihCancelled =0
group by ihinvoiceid,ihshopid
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,ihinvoiceid,ihinvoiceno,
ihinvoicedate,''Shop Order'',Null,Null,ihremarks,''SP'',
Null,Null,null,NUll,Null,5,
prj.idrPlanNo,prj.idrRefNo,
prj.idrnature
from losinvoiceheader left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@intshoporderid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
ihtype=''P'' and ihProformaID=@intshopquotid
and ihshopid=@intshopid AND ihCancelled =0
group by ihinvoiceid,ihinvoiceno,ihremarks,ihinvoicedate,ihshopid,
prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--pandc Purchase Order
select @intcounter=count(pohPoid),@intpandcpoid=pohpoid
from loPurchaseOrderHeader where
pohtype=''P'' and pohQuotationid= @intpandcquotid
AND pohcancel=0
and pohdepartmentid=@intdepartmentid
group by pohPoid
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pohPoid,pohpono,
pohPodate,''PandC Purchase Order'',pohVendorID,vendorname,pohremarks,''PO'',
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,
CONVERT(char(2),pohCustomDutyByCustomer),pohTransportation,6,
prj.idrPlanNo,prj.idrRefNo,
prj.idrnature
from loPurchaseOrderHeader,avendormaster left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@intpandcpoid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pohVendorID and companyid=pohcompanyid and
pohtype=''P''  and  pohcancel=0 AND
pohQuotationid in( select transid from ##ShoprequestFlow
where transtype=''PQ'')
and pohdepartmentid=@intdepartmentid
group by pohPoid,pohpono,pohremarks,pohvendorid,pohpodate,vendorname,
pohProjectStartDate,pohProjectEndDate,pohProjectOtherInfo,CONVERT(char(2),
pohCustomDutyByCustomer),pohTransportation,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--pandc Purchase Bill
select @intcounter=count(pbhBillID)
from losPpurchasebillheader
where pbhPOID= @intpandcpoid
and pbhdepartmentid=@intdepartmentid
AND pbhCancelled  =0
group by pbhbillid
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,pbhBillID,pbhBillNo,
pbhBillDate,''PandC Purchase Bill'',pbhVendorID,vendorname,
pbhRemarks,''PB'',
Null,Null,null,NUll,Null,7,
prj.idrPlanNo,prj.idrRefNo,
prj.idrnature
from losPpurchasebillheader,avendormaster left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@inttransid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
vendorid=pbhVendorID and companyid=pbhcompanyid
AND pbhCancelled  =0 AND
pbhPOID in( select transid from ##ShoprequestFlow
where transtype=''PO'')
and pbhdepartmentid=@intdepartmentid
group by pbhbillid,pbhbillno,pbhremarks,pbhvendorid,pbhbilldate,
vendorname,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
--Shop Invoice
select @intcounter=count(ihInvoiceID),@intshopinvid=ihInvoiceID
from losinvoiceheader where
ihtype=''I'' and ihProformaID=@intshoporderid
and ihshopid=@intshopid and ihcompanyid=@intcompanyid
AND ihCancelled =0
group by ihinvoiceid,ihshopid
if @intcounter>0
begin
insert into ##ShoprequestFlow
select @intcompanyid,@intshopid,ihinvoiceid,ihinvoiceno,
ihinvoicedate,''Shop Credit Invoice'',Null,Null,ihremarks,''SI'',
Null,Null,null,NUll,Null,8,
prj.idrPlanNo,prj.idrRefNo,
prj.idrnature
from losinvoiceheader left outer join losInvoiceProjectRequestDetails prj on
idrInvoiceId=@intshopinvid and idrShopId=@intshopid and
idrCompanyId=@intcompanyid where
ihtype=''I'' and ihProformaID=@intshoporderid
and ihshopid=@intshopid
AND ihCancelled =0
group by ihinvoiceid,ihinvoiceno,ihremarks,ihinvoicedate,
ihshopid,prj.idrPlanNo,prj.idrRefNo,prj.idrnature
set  @intcounter=0
end
else
begin
set @intreferenceid=0
set @intcounter=0
end
end
Select * From ##ShoprequestFlow  where convert(varchar(10),trandate,112)>=@strFromDate
and convert(varchar(10),trandate,112)<= @strToDate
drop table ##ShoprequestFlow
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sptrial1]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptrial1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO SAVE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnHeader 1,''sdgsfd'',''2010-01-01'',2,
--''ssssfg'',2,1.000,1.000,''gggh'',1,1,1
CREATE PROC [dbo].[sptrial1]
(@shopId AS INT,@TransNo AS VARCHAR(50),@TransDate AS DATETIME,@ReferenceID AS INT,
@Remarks AS VARCHAR(250),@DeptId AS INT,@ComExRate AS NUMERIC(18,9),@DepExRate AS NUMERIC(18,9),
@ExRates AS VARCHAR(250),@UserID AS INT,@Confirmed AS INT,@ConfirmedUSerID AS INT
)
AS
DECLARE @intTransId AS INT
DECLARE @intOtherDeptId AS INT
DECLARE @intApartmentId AS INT
DECLARE @intExpenseAccntId AS INT
DECLARE @intToDeptExRate AS NUMERIC(18,9)
BEGIN
SET NOCOUNT ON
if EXISTS (SELECT 1 FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId)
BEGIN
	SELECT @intTransId=MAX(IHRHID)+1
	FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId
END
ELSE
BEGIN
	SET @intTransId=1
END
SELECT @intOtherDeptId=ISNULL(whotherdepid,0),@intApartmentId=ISNULL(whapartmentid,0),
@intExpenseAccntId=ISNULL(whexpenseaccid,0),@intToDeptExRate=isnull(whtodepexrate,0.00)
FROM loswriteoffheader WHERE whShopID=@shopId AND WhID=@ReferenceID
		INSERT INTO [LOs_InHouseCons_ReturnHeader]
		(IHRHShopID,IHRHID,IHRHNo,IHRHDate,IHRHReferenceid,IHRHRemarks,
		IHRHdepartmentid,IHRHconexrate,IHRHdepexrate,IHRHexchangerates,IHRHotherdepid,IHRHtodepexrate,
		IHRHexpenseaccid,IHRHapartmentid,IHRHUserId,IHRHConfirmed,IHRHConfirmedUSerID)
		VALUES
		(@shopId,@intTransId,@TransNo,@TransDate,@ReferenceID,@Remarks,
		@DeptId,@ComExRate,@DepExRate,@ExRates,@intOtherDeptId,@intToDeptExRate,
		@intExpenseAccntId,@intApartmentId,@UserID,@Confirmed,@ConfirmedUSerID)
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceNew]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTrialBalanceNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--modified by  : Hariharan
--Modified Date  : 22/04/2004
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)
--   : used temporary tables for getting data after fetching for first time
--   : Corrected the opening debit and credit balances and net balance made corrected
--***************************************************************************************************************************
--Modified By   : Shinu
--Modified Date  : 26/05/2008
--Comments   : Corrected to Get Total Amount
--***************************************************************************************************************************
--RefNo-1
--Modified By : Yogesh Joe
--Modified On : 05-06-2010
--Comments : The report were showing wrong figure if the ''from date'' is not the start date of a financial year.Now Corrected.
--***************************************************************************************************************************
--Ref.No:2
--Modifted By:Shine Das
--Modified On:09/03/2012
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).
--It has to be corrected.
--***************************************************************************************************************************
CREATE proc [dbo].[spTrialBalanceNew] @strFROMDate as varchar(10), @strToDate as varchar(10),
@intcompanyid as int, @intdepartmentid as int, @bitcons as bit,
@intconsolidation as int=0  as
set ansi_Warnings off
set nocount on
begin
declare @dtFROMDate as datetime
declare @dtToDate as datetime,
@intFinId as int,
@dtPrevFinUnclosedSDate as datetime,
@dtLastFinUnclosedEDate as datetime,
@intCount as int,
@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid int,
journaldetailid int,
journalcredit bit,
accountid int,
Amount numeric(18,2),
ActualAmount numeric(18,2),
departmentid int,
depamount numeric(18,2),
Postgroup int)
Create table #Tempjournalheader
(JournalID int,
CompanyID int,
JournalDate smalldatetime,
ReferenceNo varchar(100),
Remarks varchar(250),
Type char(10),
Cancel bit,
Realised bit,
CurrencyId int,
FinancialID int,
chequedate datetime,
updatetime datetime,
bankdate datetime)
Create table #vwjournalparticulars
(companyid int,
journalid int,
journalcredit bit,
particulars varchar(250))
Create table #TrialBal(
CompanyID int,
DepartmentId int,
DepartmentName varchar(100),
accountid int,
AccCode varchar(50),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
Debit numeric(18,2),
Credit numeric(18,2),
OpDebit numeric(18,2),
OpCredit Numeric(18,2),
OpBal numeric(18,2))
Create table #TrialBalNew(
CompanyID int,
accountid int,
AccCode varchar(50),
AccDesc varchar(100),
AcType varchar(1),
GroupID int,
GroupName varchar(100),
Debit numeric(18,2),
Credit numeric(18,2),
OpDebit numeric(18,2),
OpCredit Numeric(18,2),
OpBal numeric(18,2))
SELECT @dtFROMDate = convert(datetime, @strFROMDate)
SELECT @dtToDate = convert(datetime,@strToDate)
Select @intFinId = financialid from vwfinyearperiod
where convert(datetime,@strFROMDate,101) between sdate and edate
select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
select @intCount = count(*) from aAccountfinyearOpening where
CompanyId = @intCompanyId and FinancialId = @intFinId
Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
where CompanyId = @intCompanyId
--if @intLastFinId = 0     --Ref.No:2   Commented
if ISNULL(@intLastFinId,0) = 0  --Ref.No:2 Added
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = (Select min(financialid) from afinancialyear where
companyid = @intCompanyId ) and CompanyId= @intCompanyId
ELSE
Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
where financialid = @intLastFinId and CompanyId= @intCompanyId
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts        -- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1
Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
insert #Tempjournalheader
Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate
and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
if @intDepartmentId = 0
begin
insert #vwJournalDetails
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
h.CompanyId = @intCompanyId
end
else
begin
insert #vwJournalDetails
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where
JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and
h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and
h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)
end
insert #vwjournalparticulars
Select d.* from #Tempjournalheader h (NOLOCK), vwJournalParticulars  d (NOLOCK)
where h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
and h.Cancel = 0 and h.CompanyId = @intCompanyId
insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,
AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit )
Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,
a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,
0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where
a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid
and a.CompanyId = @intCompanyid
Update #TrialBal set OpBal = opening.Openingamount from (Select AccountId,
DepartmentId, CompanyId, case when @bitcons = 1 then Openingamount else
OpeningDepamount End Openingamount from aaccountfinyearopening where
Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
opening.Accountid = #TrialBal.AccountId and
opening.DepartmentId = #TrialBal.DepartmentId
and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId
Update #TrialBal set OpBal  = OpBal + trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and (#TrialBal.AcType =''A'' or #TrialBal.AcType =''E'')
Update #TrialBal set OpBal  = OpBal - trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and (#TrialBal.AcType =''L'' or #TrialBal.AcType =''I'')
Update #TrialBal set OpBal  = OpBal + trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and (#TrialBal.AcType =''L'' or #TrialBal.AcType =''I'')
Update #TrialBal set OpBal  = OpBal - trialDeb.amount from (Select v.AccountId,
v.DepartmentId, v.CompanyId, case when @bitcons = 1 then
Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From
#vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and
h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
trialDeb.Accountid = #TrialBal.AccountId and
trialDeb.DepartmentId = #TrialBal.DepartmentId
and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId
and (#TrialBal.AcType =''A'' or #TrialBal.AcType =''E'')
--RefNo-1-----------------Starts----------------------------------------------------
--RefNo-1(a)
--Below values are already added to Opening.Hence clearing the values to avoid it from
--cosidering again.
Update #vwJournalDetails SET Amount=0,depamount=0 FROM #Tempjournalheader h
INNER JOIN #vwJournalDetails d ON h.JournalID=d.JournalID
WHERE
h.JournalDate>= @dtPrevFinUnclosedSDate AND h.JournalDate <= @dtLastFinUnclosedEDate
--RefNo-1------------------Ends-----------------------------------------------------
Delete #TrialBal from  (Select #TrialBal.AccountId, #TrialBal.DepartmentId from
#TrialBal left outer join #vwJournalDetails
on #TrialBal.accountid = #vwJournalDetails.accountid and
#TrialBal.Departmentid = #vwJournalDetails.Departmentid
where #vwJournalDetails.DepartmentId is null) novalue
where #TrialBal.accountid = novalue.accountid and
#TrialBal.Departmentid = novalue.Departmentid and #TrialBal.opbal=0
if @intdepartmentid = 0
Begin
insert #TrialBalNew
Select CompanyID, accountid, AccCode, AccDesc, AcType, GroupID, GroupName,
sum(isnull(Debit,0)), sum(isnull(Credit,0)),
sum(isnull(OpDebit,0)), sum(isnull(OpCredit,0)),
sum(isnull(OpBal,0)) from #TrialBal
Group By CompanyID, accountid, AccCode, AccDesc,
AcType, GroupID, GroupName
select jh.companyid, jh.journalid, month(jh.journaldate) tmonth, jh.journaldate,
jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,  case when
convert(int, jd.JournalCredit)  =0 then case when @bitCons = 1 then sum(amount)
Else sum(DepAmount) End else 0 end debitamt, case when  convert(int, jd.JournalCredit)  =1 then ''To''
else ''By'' end as Prefix, case when   convert(int, jd.JournalCredit)  =1 then
case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end creditamt,
case when ((opBal>0 and (t.AcType=''A'' or t.AcType=''E''))   or
(opBal<0 and (t.AcType=''L'' or t.AcType=''I'')))  then abs(opBal) else 0 end openingdr ,
case when ((opBal<0 and (t.AcType=''A'' or t.AcType=''E''))   or
(opBal>0 and (t.AcType=''L'' or t.AcType=''I''))) then abs(opBal) else 0 end openingCr
from #TrialBalNew t left outer join  #vwJournalDetails jd on t.companyid =
jd.companyid and t.accountid  = jd.accountid --and t.departmentid = jd.departmentid
and  @intcompanyid = jd.companyid left outer join #Tempjournalheader jh on
jd.companyid = jh.companyid and jd.journalid = jh.journalid  and 0 = jh.cancel
left outer join #vwjournalparticulars jp on jd.companyid  = jp.companyid and
jd.journalid = jp.journalid  and jd.journalcredit = abs(1 - jp.journalcredit) and
-- @dtFROMDate <= JH.JournalDate AND @dtToDate >= JH.JournalDate  and   --RefNo-1(c)
(jh.financialid > 0 or jh.FinancialId is null), aaccountmaster am  where
am.companyid = t.companyid and am.accountid = t.accountid
Group By jh.companyid, jh.journalid, jh.journaldate, jh.referenceno,
jp.particulars, am.accountcode, am.accountdesc, t.AcType, /* amount, depamount,Shinu 26052008 @simdi*/ opBal,
convert(int, jd.JournalCredit)
End
Else
Begin
insert #TrialBalNew
Select CompanyID, accountid, AccCode, AccDesc, AcType, GroupID, GroupName,
sum(isnull(Debit,0)), sum(isnull(Credit,0)),
sum(isnull(OpDebit,0)), sum(isnull(OpCredit,0)),
sum(isnull(OpBal,0)) from #TrialBal where
DepartmentId in (Select Deptid from #SubDepts1)
Group By CompanyID, accountid, AccCode, AccDesc,
AcType, GroupID, GroupName
select jh.companyid, jh.journalid, month(jh.journaldate) tmonth, jh.journaldate,
jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,  case when
convert(int, jd.JournalCredit)  = 0 then case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end debitamt,
case when  convert(int, jd.JournalCredit)  =1 then ''To'' else ''By'' end as Prefix,
case when  convert(int, jd.JournalCredit)  =1 then case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end creditamt,
case when ((opBal>0 and (t.AcType=''A'' or t.AcType=''E''))   or
(opBal<0 and (t.AcType=''L'' or t.AcType=''I'')))  then abs(opBal) else 0 end openingdr ,
case when ((opBal<0 and (t.AcType=''A'' or t.AcType=''E''))   or
(opBal>0 and (t.AcType=''L'' or t.AcType=''I''))) then abs(opBal) else 0 end openingCr
from #TrialBalNew t left outer join  #vwJournalDetails jd on t.companyid =
jd.companyid and t.accountid  = jd.accountid --and t.departmentid = jd.departmentid
and  @intcompanyid = jd.companyid left outer join #Tempjournalheader jh on
jd.companyid = jh.companyid and jd.journalid = jh.journalid  and 0 = jh.cancel
left outer join #vwjournalparticulars jp on jd.companyid  = jp.companyid and
jd.journalid = jp.journalid  and jd.journalcredit = abs(1 - jp.journalcredit) and
-- @dtFROMDate <= JH.JournalDate AND @dtToDate >= JH.JournalDate  and --RefNo-1(c)
(jh.financialid > 0 or jh.FinancialId is null), aaccountmaster am  where
am.companyid = t.companyid and am.accountid = t.accountid
--and t.DepartmentId in (Select Deptid from #SubDepts1)
Group By jh.companyid, jh.journalid,
jh.journaldate, jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,
t.AcType, /* amount, depamount,--- Shinu 26052008 @simdi*/ opBal, convert(int, jd.JournalCredit)
End
drop table #TrialBal
drop table #SubDepts1
drop table #vwJournalDetails
drop table #Tempjournalheader
end
set nocount off
set ansi_Warnings on' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationReport]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By  :AADYA KUMAR D V
--Created Date:13/10/2011
--Purpose     :This Sp is created from spBankReconciliation,to handle report condition
--            :Report needs  trasaction which are not realised and realised date not in between date range
create PROC [dbo].[spBankReconciliationReport] (@intCompanyID as int,
@strFromDate as varchar(10),
@strToDate as varchar(10),
@intAccID as int,
@intdepid as int) AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
Create table #BankReconciliation(
JournalID int,
CompanyID int,
journalDate datetime,
remarks varchar(500),
DepartmentID int,
ReferenceNo varchar(500),
financialID int,
Type varchar(50),
OpeningCredit numeric(18,2),
OpeningDebit numeric(18,2),
Amount numeric(18,2),
Particulars varchar(500),
journalcredit bit,
prefix varchar(50),
realised datetime,
bankstatus varchar(50),
CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
if @intdepid <> 0
BEGIN
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate , ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
-- and h.JournalDate < @dtFROMDate
-- and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
-- And, all trans not yet realised, or bank date exceeds given period
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
and (h.bankdate is null or h.bankdate > @dtTodate )
--    --hari added one more insert statement for considering the realise date
END
ELSE
BEGIN
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate , ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation order by JournalDate
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationRep]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationRep]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
CREATE   PROC [dbo].[spBankReconciliationRep] (@intCompanyID as int,
@strFromDate as varchar(10),
@strToDate as varchar(10),
@intAccID as int,
@intdepid as int) AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
Create table #BankReconciliation(
JournalID int,
CompanyID int,
journalDate datetime,
remarks varchar(500),
DepartmentID int,
ReferenceNo varchar(500),
financialID int,
Type varchar(50),
OpeningCredit numeric(18,2),
OpeningDebit numeric(18,2),
Amount numeric(18,2),
Particulars varchar(500),
journalcredit bit,
prefix varchar(50),
realised datetime,
bankstatus varchar(50),
CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
if @intdepid <> 0
BEGIN
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate
and (h.bankdate is null or h.bankdate >= @dtTodate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and d.departmentid = @intdepid
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.departmentid = @intdepid
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
ELSE
BEGIN
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate >= @dtfromdate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation where journaldate <=@dtToDate
and (realised is null or realised > @dtToDate )  order by JournalDate
set nocount off
End
-- spBankReconciliation 1, ''20030101'', ''20031231'', 1, 1' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationAsOn25052011]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliationAsOn25052011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Updated On: 08-09-2010
-- Updated By: Regin T.
-- Purpose: Performance Tuning
--   Opening Balance calculation was removed, since it is not used.
--   3 sets of insert queries were combined into 1 by changing where condition.
-- Reference: RefNo-1
--------------------------------------------------------------------------------
CREATE PROC [dbo].[spBankReconciliationAsOn25052011] (@intCompanyID as int,
@strFromDate as varchar(10),
@strToDate as varchar(10),
@intAccID as int,
@intdepid as int) AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
	Create table #BankReconciliation(
	JournalID int,
	CompanyID int,
	journalDate datetime,
	remarks varchar(500),
	DepartmentID int,
	ReferenceNo varchar(500),
	financialID int,
	Type varchar(50),
	OpeningCredit numeric(18,2),
	OpeningDebit numeric(18,2),
	Amount numeric(18,2),
	Particulars varchar(500),
	journalcredit bit,
	prefix varchar(50),
	realised datetime,
	bankstatus varchar(50),
	CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
if @intdepid <> 0
BEGIN
--    Below query to calculate the opening balance is commented, since it is not used. (RefNo-1)
--    SELECT @Creditamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
--    h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid and d.departmentid = @intdepid
--    and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT @Debitamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d,
--    vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
--    h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
--    and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
--
--    SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
--
--
--    SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID =
--    d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
--    and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--    and d.departmentid = @intdepid
--
--    SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and  h.Cancel = 0
--    and d.CompanyID = a.CompanyID and d.accountid = a.accountid
--    and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--    and d.departmentid = @intdepid
--   3 sets of insert queries were combined into 1 by changing where condition. (RefNo-1)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
-- and h.JournalDate < @dtFROMDate
-- and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
-- And, all trans not yet realised, or bank date exceeds given period
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--    --hari added one more insert statement for considering the realise date
--
--    insert into #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    h.bankdate, ''No'', c.Symbol
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate -- change here
--    and d.departmentid = @intdepid
--    and h.JournalDate <= @dtToDate  -- change here
--    and (h.bankdate is null or h.bankdate > @dtTodate)
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
--
--    insert into  #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    --case when h.bankdate > @dttodate then null else h.bankdate end ,
--    h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
--    FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and h.bankdate <= @dtTodate -- change here
--    and d.departmentid = @intdepid
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
END
ELSE
BEGIN
--    Below query to calculate the opening balance is commented, since it is not used. (RefNo-1)
--    SELECT @Creditamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
--    h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
--    and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT @Debitamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d,
--    vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
--    h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid
--    and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate)
--
--    SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate)
--
--
--    SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID =
--    d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
--    and d.accountid = a.accountid  and f.financialid = a.financialid
-- and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--
--    SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and  h.Cancel = 0
--    and d.CompanyID = a.CompanyID and d.accountid = a.accountid
--    and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--   3 sets of insert queries were combined into 1 by changing where condition. (RefNo-1)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
-- and h.JournalDate < @dtFROMDate
-- and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
-- And, all trans not yet realised, or bank date exceeds given period
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--    --hari added one more insert statement for considering the realise date
--
--    insert into #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    h.bankdate, ''No'', c.Symbol
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and (h.bankdate is null or h.bankdate > @dtTodate)
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
--
--    insert into  #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    --case when h.bankdate > @dttodate then null else h.bankdate end ,
--    h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
--    FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and h.bankdate <= @dtTodate
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
END
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation order by JournalDate
set nocount off
End
-- spBankReconciliation 1, ''20030101'', ''20031231'', 1, 1' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation_SIMDI]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation_SIMDI]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ----------------------------------------------------------
-- Reference       : RefNo-1
-- Modified by     : Bijesh.B
-- Purpose         : Performance tuning(sonee)
-- Description     : Since we have reported some problem in the latest sp
--				     in server, Bezigar suggested to take the sp from SIMDI
-- BackUp(in server): spBankReconciliationAsOn25052011
-- --------------------------------------------------------
CREATE PROC [dbo].[spBankReconciliation_SIMDI]
(
	@intCompanyID as int,
	@strFromDate as varchar(10),
	@strToDate as varchar(10),
	@intAccID as int,
	@intdepid as int
)AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
Create table #BankReconciliation(
	JournalID int,
	CompanyID int,
	journalDate datetime,
	remarks varchar(300),
	DepartmentID int,
	ReferenceNo varchar(50),
	financialID int,
	Type varchar(5),
	OpeningCredit numeric(18,2),
	OpeningDebit numeric(18,2),
	Amount numeric(18,2),
	Particulars varchar(300),
	journalcredit bit,
	prefix varchar(5),
	realised datetime,
	bankstatus varchar(12),
CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
/* ----------- RefNo-1 start commented
if @intdepid <> 0
BEGIN
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate
and (h.bankdate is null or h.bankdate > @dtTodate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and d.departmentid = @intdepid
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.departmentid = @intdepid
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
ELSE
BEGIN
	
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate
and (h.bankdate is null or h.bankdate > @dtTodate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
*/ ----------- RefNo-1 ends  commented ------
-- RefNo-1 Start ---------------
SELECT @Creditamount = isnull(sum(d.actualamount),0), @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h , moajournaldetails d    ---, vwjournalparticulars  one  --RefNo-1
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
---h.companyid = one.companyid and h.journalid = one.journalid and  one.journalcredit = 1 and  --RefNo-1
d.JournalCredit=1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
--and d.departmentid = @intdepid  --RefNo-1
and (d.departmentid = @intdepid or @intdepid=0)
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d --,vwjournalparticulars  one   --RefNo-1
WHERE h.JournalID = d.JournalID  and h.CompanyID = d.CompanyID and
--h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and  --RefNo-1
d.JournalCredit=0 and  --RefNo-1
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
---and f.companyid = f.companyid  --RefNo-1
and f.companyid = a.companyid  --RefNo-1
and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--and f.companyid = f.companyid   --RefNo-1
and f.companyid = a.companyid     --RefNo-1
and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
--and f.companyid = f.companyid   --RefNo-1
and f.companyid = a.companyid     --RefNo-1
and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
--and f.companyid = f.companyid   --RefNo-1
and f.companyid = a.companyid      --RefNo-1
and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
INSERT INTO #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID, h.type,
case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when 0 then 0 end
		as OpeningCredit,
case d.JournalCrEDit when 1 then 0 when 0 then @OpeningDebit + @Debitamount end
		as OpeningDebit,
d.actualamount amount, one.particulars as particulars,d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
		h.bankdate, ''No'', c.Symbol
FROM moajournalheader h
INNER JOIN moajournaldetails d ON h.JournalID = d.JournalID
			and h.CompanyID = d.CompanyID and h.cancel = 0
			and h.CompanyID = @intcompanyid and d.accountid = @intaccid
		    --and d.departmentid = @intdepid
			and (d.departmentid = @intdepid or @intdepid=0)
			and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
INNER JOIN vwjournalparticulars one ON h.companyid = one.companyid
			and h.journalid = one.journalid and one.journalcredit = abs(1 - d.journalcredit)
INNER JOIN aAccountMaster a ON d.AccountId = a.AccountId
			and h.CompanyId = a.CompanyId
INNER JOIN aCurrencyMaster c ON a.CurrencyId = c.CurrencyId
			and a.CompanyId = c.CompanyId
--RefNo1 Combined last 2 queries into 1
INSERT INTO #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID,
h.referenceno,h.financialID, h.type,
case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
			as OpeningCredit,
case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end
			as OpeningDebit,
d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h
INNER JOIN moajournaldetails d ON  h.JournalID = d.JournalID
		and h.CompanyID = d.CompanyID and h.cancel = 0
		and h.CompanyID = @intcompanyid
		and d.accountid = @intaccid
	    --and d.departmentid = @intdepid
		and (d.departmentid = @intdepid or @intdepid=0)
		and
		(
				(h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
				and (h.bankdate is null or h.bankdate > @dtTodate))
			or
			(
				(h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
				and h.bankdate <= @dtTodate)
			)		
		)
INNER JOIN vwjournalparticulars  one ON h.companyid = one.companyid
		and h.journalid = one.journalid and one.journalcredit = abs(1 - d.journalcredit)
	INNER JOIN aAccountMaster a ON d.AccountId = a.AccountId
		and h.CompanyId = a.CompanyId
INNER JOIN aCurrencyMaster c ON a.CurrencyId = c.CurrencyId
		and a.CompanyId = c.CompanyId
-- RefNo-1 ends ---------------
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation order by JournalDate
set nocount off
End
-- spBankReconciliation 1, ''20030101'', ''20031231'', 1, 1' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation_FromSIMDI]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation_FromSIMDI]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROC [dbo].[spBankReconciliation_FromSIMDI] (@intCompanyID as int,
@strFromDate as varchar(10),
@strToDate as varchar(10),
@intAccID as int,
@intdepid as int) AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
Create table #BankReconciliation(
	JournalID int,
	CompanyID int,
	journalDate datetime,
	remarks varchar(300),
	DepartmentID int,
	ReferenceNo varchar(50),
	financialID int,
	Type varchar(5),
	OpeningCredit numeric(18,2),
	OpeningDebit numeric(18,2),
	Amount numeric(18,2),
	Particulars varchar(300),
	journalcredit bit,
	prefix varchar(5),
	realised datetime,
	bankstatus varchar(12),
CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
if @intdepid <> 0
BEGIN
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
and d.departmentid = @intdepid
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
and h.JournalDate < @dtFROMDate
and (h.bankdate is null or h.bankdate > @dtTodate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and d.departmentid = @intdepid
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.departmentid = @intdepid
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
ELSE
BEGIN
	
SELECT @Creditamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT @Debitamount = isnull(sum(d.actualamount),0)
FROM moajournalheader h, moajournaldetails d,
vwjournalparticulars  one
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and
h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
(@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f,
moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID and h.CompanyID =
d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
and d.accountid = a.accountid  and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 0 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
where h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID and  h.Cancel = 0
and d.CompanyID = a.CompanyID and d.accountid = a.accountid
and f.financialid = a.financialid
and f.companyid = f.companyid and d.accountid = @intaccid
and h.companyid = @intcompanyid and d.journalcredit = 1 and
h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
and (@dtfromdate between f.sdate and f.edate)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate < @dtFROMDate
and (h.bankdate is null or h.bankdate > @dtTodate )
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--hari added one more insert statement for considering the realise date
insert into #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and (h.bankdate is null or h.bankdate > @dtTodate)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
insert into  #BankReconciliation
SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
-- modified by leo only for v3, to be checked with hari
--case when h.bankdate > @dttodate then null else h.bankdate end ,
h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and h.JournalDate >= @dtFROMDate
and h.JournalDate <= @dtToDate
and h.bankdate <= @dtTodate
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
END
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation order by JournalDate
set nocount off
End
-- spBankReconciliation 1, ''20030101'', ''20031231'', 1, 1' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankReconciliation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Updated On: 08-09-2010
-- Updated By: Regin T.
-- Purpose: Performance Tuning
--   Opening Balance calculation was removed, since it is not used.
--   3 sets of insert queries were combined into 1 by changing where condition.
-- Reference: RefNo-1
--------------------------------------------------------------------------------
CREATE PROC [dbo].[spBankReconciliation] (@intCompanyID as int,
@strFromDate as varchar(10),
@strToDate as varchar(10),
@intAccID as int,
@intdepid as int) AS
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@OpeningDebit as numeric(18,2),
@OpeningCredit as numeric(18,2),
@CurrOpeningCredit as numeric(18,2),
@CurrOpeningDebit as numeric(18,2),
@CreditAmount as numeric(18,2),
@DebitAmount as numeric(18,2),
@intnoofrec as int
	Create table #BankReconciliation(
	JournalID int,
	CompanyID int,
	journalDate datetime,
	remarks varchar(500),
	DepartmentID int,
	ReferenceNo varchar(500),
	financialID int,
	Type varchar(50),
	OpeningCredit numeric(18,2),
	OpeningDebit numeric(18,2),
	Amount numeric(18,2),
	Particulars varchar(500),
	journalcredit bit,
	prefix varchar(50),
	realised datetime,
	bankstatus varchar(50),
	CurrencySymbol varchar(50))
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
if @intdepid <> 0
BEGIN
--    Below query to calculate the opening balance is commented, since it is not used. (RefNo-1)
--    SELECT @Creditamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
--    h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid and d.departmentid = @intdepid
--    and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT @Debitamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d,
--    vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
--    h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid and d.departmentid = @intdepid
--    and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
--
--    SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate) and d.departmentid = @intdepid
--
--
--    SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID =
--    d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
--    and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--    and d.departmentid = @intdepid
--
--    SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and  h.Cancel = 0
--    and d.CompanyID = a.CompanyID and d.accountid = a.accountid
--    and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--    and d.departmentid = @intdepid
--   3 sets of insert queries were combined into 1 by changing where condition. (RefNo-1)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
and d.departmentid = @intdepid
-- and h.JournalDate < @dtFROMDate
-- and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
-- And, all trans not yet realised, or bank date exceeds given period
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--    --hari added one more insert statement for considering the realise date
--
--    insert into #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    h.bankdate, ''No'', c.Symbol
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate -- change here
--    and d.departmentid = @intdepid
--    and h.JournalDate <= @dtToDate  -- change here
--    and (h.bankdate is null or h.bankdate > @dtTodate)
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
--
--    insert into  #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    --case when h.bankdate > @dttodate then null else h.bankdate end ,
--    h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
--    FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and h.bankdate <= @dtTodate -- change here
--    and d.departmentid = @intdepid
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
END
ELSE
BEGIN
--    Below query to calculate the opening balance is commented, since it is not used. (RefNo-1)
--    SELECT @Creditamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid  and h.journalid = one.journalid and one.journalcredit = 1 and
--    h.cancel =0 and h.CompanyID = @intcompanyid  and d.accountid = @intaccid
--    and h.JournalDate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT @Debitamount = isnull(sum(d.actualamount),0)
--    FROM moajournalheader h, moajournaldetails d,
--    vwjournalparticulars  one
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and
--    h.companyid = one.companyid and h.journalid = one.journalid and one.journalcredit = 0 and
--    h.cancel =0 and h.CompanyID = @intcompanyid and d.accountid = @intaccid
--    and h.JournalDate < @dtFROMDate  and (h.bankdate is null or h.bankdate>@dtTodate)
--
--    SELECT  @OpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate)
--
--    SELECT  @OpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
--    and  h.Cancel = 0 and d.CompanyID = a.CompanyID and d.accountid = a.accountid  and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid  and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate < @dtFROMDate and (h.bankdate is null or h.bankdate>@dtTodate  ) and
--    (@dtfromdate between f.sdate and f.edate)
--
--
--    SELECT  @CurrOpeningDebit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f,
--    moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID and h.CompanyID =
--    d.CompanyID and  h.Cancel = 0 and d.CompanyID = a.CompanyID
--    and d.accountid = a.accountid  and f.financialid = a.financialid
-- and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 0 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--
--    SELECT  @CurrOpeningCredit =  isnull(sum(a.Openingactualamount),0)
--    from aaccountfinyearopening a, vwfinyearperiod f, moajournaldetails d, moajournalheader h
--    where h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID and  h.Cancel = 0
--    and d.CompanyID = a.CompanyID and d.accountid = a.accountid
--    and f.financialid = a.financialid
--    and f.companyid = f.companyid and d.accountid = @intaccid
--    and h.companyid = @intcompanyid and d.journalcredit = 1 and
--    h.journaldate >= @dtFROMDate and h.journaldate <= @dtToDate
--    and (@dtfromdate between f.sdate and f.edate)
--   3 sets of insert queries were combined into 1 by changing where condition. (RefNo-1)
insert into #BankReconciliation
SELECT h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
h.financialID, h.type, case d.JournalCrEDit when 1 then @OpeningCredit + @Creditamount when
0 then 0 end as OpeningCredit, case d.JournalCrEDit when 1 then 0 when 0 then
@OpeningDebit + @Debitamount end as OpeningDebit, d.actualamount amount, one.particulars as
particulars, d.journalcredit, case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as
prefix, h.bankdate, ''No'', c.Symbol
FROM moajournalheader h, moajournaldetails d, vwjournalparticulars one,
aAccountMaster a, aCurrencyMaster c
WHERE h.JournalID = d.JournalID
and h.CompanyID = d.CompanyID
and h.companyid = one.companyid
and h.journalid = one.journalid
and one.journalcredit = abs(1 - d.journalcredit)
and h.cancel = 0
and h.CompanyID = @intcompanyid
and d.accountid = @intaccid
-- and h.JournalDate < @dtFROMDate
-- and (h.bankdate is null or h.bankdate > @dtTodate )
and (
(h.JournalDate >=@dtFromDate and h.JournalDate<=@dtToDate)  -- All trans in given period
or
-- And, all trans not yet realised, or bank date exceeds given period
(h.JournalDate < @dtFromDate and (h.bankdate is null or h.bankdate > @dtTodate))
)
and d.AccountId = a.AccountId
and h.CompanyId = a.CompanyId
and a.CurrencyId = c.CurrencyId
and a.CompanyId = c.CompanyId
--    --hari added one more insert statement for considering the realise date
--
--    insert into #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    h.bankdate, ''No'', c.Symbol
--    FROM moajournalheader h, moajournaldetails d, vwjournalparticulars  one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and (h.bankdate is null or h.bankdate > @dtTodate)
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
--
--    insert into  #BankReconciliation
--    SELECT  h.JournalID, h.CompanyID, h.JournalDate, h.remarks, d.departmentID, h.referenceno,
--    h.financialID, h.type, case d.JournalCrEDit when 1 then @CurrOpeningCredit when 0 then 0 end
--    as OpeningCredit,case d.JournalCrEDit when 1 then 0 when 0 then @CurrOpeningDebit end as
--    OpeningDebit, d.actualamount amount, one.particulars as particulars, d.journalcredit,
--    case d.JournalCrEDit when 1 then ''By'' when 0 then ''To'' end as prefix,
--    -- modified by leo only for v3, to be checked with hari
--    --case when h.bankdate > @dttodate then null else h.bankdate end ,
--    h.bankdate, convert(datetime,h.bankdate,101), c.Symbol
--    FROM moaJournalheader h, moajournaldetails d, vwJournalParticulars one,
--    aAccountMaster a, aCurrencyMaster c
--    WHERE h.JournalID = d.JournalID
--    and h.CompanyID = d.CompanyID
--    and h.companyid = one.companyid
--    and h.journalid = one.journalid
--    and one.journalcredit = abs(1 - d.journalcredit)
--    and h.cancel = 0
--    and h.CompanyID = @intcompanyid
--    and d.accountid = @intaccid
--    and h.JournalDate >= @dtFROMDate
--    and h.JournalDate <= @dtToDate
--    and h.bankdate <= @dtTodate
--    and d.AccountId = a.AccountId
--    and h.CompanyId = a.CompanyId
--    and a.CurrencyId = c.CurrencyId
--    and a.CompanyId = c.CompanyId
END
insert into #BankReconciliation values(0, @intcompanyid, @dtfromdate,
null, null, null, null, null,
null, null, null, null, 0, null, null, '''', null)
select * from #BankReconciliation order by JournalDate
set nocount off
End
-- spBankReconciliation 1, ''20030101'', ''20031231'', 1, 1' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankPosition]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankPosition]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  By 	: R Harikrishnan
--Created  On	: 01/08/2003
--Verified By	: Hariharan
--Verified Date : 30/04/2003
--Comments	: For Bank Position Report (Updated from Devl Db)
----------------------------------------------------------------
CREATE Procedure [dbo].[spBankPosition]
	@intCompanyID 	as int,
	@dtToDate 	as datetime,
	@intDeptID 	as int
as
--For testing purpose R Harikrishnan
--set @intCompanyID = 1
--set @dtToDate = ''20030501''
begin
	declare @intDepartmentID 	as int,
		@intAccountID 		as int,
		@intDeptAccCount 	as int,
		@numToDateBalCompCurr	as numeric(18,2),
		@numToDateBalDepCurr	as numeric(18,2),
		@numToDateBalAccCurr	as numeric(18,2),
		@strToDate		as varchar(10)--For passing the value to SP
	set nocount on
	CREATE table #tempDeptAccounts1
	(
		DepartmentID 	int,
		AccountID 	int
	)
	CREATE table #tempDeptAccounts2
	(
		DepartmentID 		int,
		AccountID 		int,
		ToDateBalCompCurr	numeric(18,2),
		ToDateBalDepCurr	numeric(18,2),
		ToDateBalAccCurr	numeric(18,2)
	)
	if @intDeptID=0
	begin
		insert into #tempDeptAccounts1
			select
				da.daDepartmentID, da.daAccountID
			from
				aDeptAccounts da, aAccountMaster am
			where
				da.daCompanyID = am.companyID and da.daAccountID = am.AccountID and
				am.misc like ''%BA%'' and da.daCompanyID =@intCompanyID
	end
	else
	begin
		insert into #tempDeptAccounts1
			select
				da.daDepartmentID, da.daAccountID
			from
				aDeptAccounts da, aAccountMaster am
			where
				da.daCompanyID = am.companyID and da.daAccountID = am.AccountID and
				am.misc like ''%BA%'' and da.daCompanyID =@intCompanyID and
				da.daDepartmentID=@intDeptID
	end
	select
		@intDeptAccCount = count(1)
	from
		#tempDeptAccounts1
	--The SPOpeningBalance called below expects a date type parameter
	--for this parameter u have to pass actual date +1
	set @dtToDate = dateadd(dd,1,@dtToDate)
	set @strToDate = convert(varchar(10),@dtToDate,120)
	while @intDeptAccCount<>0
	begin
		select top 1
			@intDepartmentID =departmentID, @intAccountID =AccountID
		from
			#tempDeptAccounts1
		order by
			departmentID,AccountID
		--Company Currency balance
		exec spOpeningBalance @strToDate,@intAccountID,@intCompanyID,''c'',@numToDateBalCompCurr output,@intDepartmentID
		--Department Currency balance
		exec spOpeningBalance @strToDate,@intAccountID,@intCompanyID,''d'',@numToDateBalDepCurr output,@intDepartmentID
		--Account Currency balnce
		exec spOpeningBalance @strToDate,@intAccountID,@intCompanyID,''a'',@numToDateBalAccCurr output,@intDepartmentID
		--Inserting the values into the temporary table
		insert into #tempDeptAccounts2
			(departmentID,AccountID,ToDateBalCompCurr,ToDateBalDepCurr,
			ToDateBalAccCurr)
		values
			(@intDepartmentID,@intAccountID,@numToDateBalCompCurr,
			@numToDateBalDepCurr,@numToDateBalAccCurr)
		delete from
			#tempDeptAccounts1
		where
			departmentID = @intDepartmentID and AccountID = @intAccountID
		set @intDeptAccCount=@intDeptAccCount-1
	end
	select
		@intCompanyID CompanyId, a.DepartmentID, DateAdd(dd, -1, @dtToDate) ToDate,
		a.ToDateBalAccCurr,a.ToDateBalDepCurr,a.ToDateBalCompCurr,7 RowOrder,
		''Bank Position as on '' + convert(Varchar(10),DateAdd(dd,-1,@dtToDate),103) Type,b.DepartmentName,1 ColOrder
	from
		#tempDeptAccounts2 a, aDepartmentMaster b
	where
		a.DepartmentID = b.DepartmentID and b.CompanyID = @intCompanyID
	drop table #tempDeptAccounts1
	drop table #tempDeptAccounts2
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spbankdetailsdatewise]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spbankdetailsdatewise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spbankdetailsdatewise    Script Date: 18/01/2003 9:45:45 PM ******/
--Last Modified on 	: 05/12/2002
--Modified by	 	: leo
--comments		: v3
CREATE proc [dbo].[spbankdetailsdatewise] @strondate as varchar(10), @intcompid as int as
set nocount on
declare @dtondate as datetime
declare @outputt as numeric(18,2)
declare @intaccountid as int
declare @straccdesc as varchar(250)
create table #bankopening(
accountdesc varchar(250),
openbalance numeric(18,2))
set @dtondate = convert(datetime, @strondate ,101)
declare curopening cursor for
select accountid, accountdesc from aaccountmaster a, agroupmaster g where a.groupid = g.groupid
and g.accounttype=''a'' and a.misc=''ba''
open curopening
fetch next from curopening into @intaccountid, @straccdesc
while @@fetch_status=0
begin
	set @outputt = 0.00
	execute spopeningbalance @strondate, @intaccountid,1, ''a'', @outputt output
	insert into #bankopening values (@straccdesc, @outputt)
	fetch next from curopening into @intaccountid, @straccdesc
end
close  curopening
deallocate curopening
select type, orderno, referenceno, accountdesc, openbalance, resbalance, transdate, chequedate
from(
select ''Opening Balance'' type, 1 orderno,  '''' referenceno, accountdesc, openbalance, openbalance
resbalance, @dtondate transdate, @dtondate chequedate from #bankopening
union all
select ''Deposits'' type , 2 orderno, '''' referenceno, '' '' accountdesc, 0.00,  0.00 , @dtondate,
@dtondate
union all
select ''Deposits'' Type,  2 orderno, jh.referenceno, ac.accountdesc, jd.ActualAmount,
jd.ActualAmount, jh.journaldate, jh.chequedate from
moajournalheader jh, moajournaldetails jd, aaccountmaster ac where jh.journalid=jd.journalid and
jh.companyid = jd.companyid and jh.type=''c'' and jd.JournalCredit = 0 and
jd.accountid = ac.accountid and jh.cancel=0 and ac.misc = ''ba''
union all
select ''WithDrawels'' type,  3 orderno, '''' referenceno, '' '' accountdesc, 0.00  amount, 0.00,
@dtondate, @dtondate
union all
select ''WithDrawels'' Type, 3 orderno, jh.referenceno, ac.accountdesc, jd.ActualAmount,
-jd.ActualAmount, jh.journaldate, jh.chequedate  from moajournalheader jh,
moajournaldetails jd, aaccountmaster ac where jh.journalid=jd.journalid and
jh.companyid = jd.companyid and jh.type=''c'' and jd.JournalCredit = 1 and
jd.accountid = ac.accountid and jh.cancel=0 and ac.misc = ''ba''
union all
select ''Receipts'' type , 4 orderno, '''' referenceno, '' '' accountdesc, 0.00  amount, 0.00,
@dtondate, @dtondate
union all
select ''Receipts'' Type, 4 orderno, jh.referenceno, ac.accountdesc, jd.ActualAmount,
jd.ActualAmount, jh.journaldate, jh.chequedate from moajournalheader jh,
moajournaldetails jd, aaccountmaster ac where jh.journalid=jd.journalid and
jh.companyid = jd.companyid and jh.type=''r'' and jd.JournalCredit = 0 and
jd.accountid = ac.accountid and jh.cancel=0 and ac.misc = ''ba''
union all
select ''Payments'' type , 5 orderno, '''' referenceno, '' '' accountdesc, 0.00  amount, 0.00,
@dtondate, @dtondate
union all
select ''Payments'' Type, 5 orderno, jh.referenceno, ac.accountdesc, jd.ActualAmount,
-jd.ActualAmount,
jh.journaldate, jh.chequedate from moajournalheader jh,
moajournaldetails jd, aaccountmaster ac where jh.journalid=jd.journalid and
jh.companyid = jd.companyid and jh.type=''p'' and jd.JournalCredit = 1 and
jd.accountid = ac.accountid and jh.cancel=0 and ac.misc = ''ba'' ) bandetails
order by orderno
drop table #bankopening
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_FetchCreditSaleDeliveryDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_FetchCreditSaleDeliveryDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:  Regin T.
-- Create date: 15-07-2010
-- Description:
--   Input:
--     1. Company Id (Not in use now, but to support multiple companies enhancement)
--     2. Shop Id
--     3. Invoice Id
--   Output:
--     Returns the list of items in given invoice
-- To execute: exec spMag_FetchCreditSaleDeliveryDetails 1, 1, 4
-- =============================================================================
CREATE PROC [dbo].[spMag_FetchCreditSaleDeliveryDetails]
@intCompanyId as int
, @intShopId as int
, @intInvoiceId as int
AS
BEGIN
SET NOCOUNT ON;
-- CREDIT INVOICE ITEM DETAILS
SELECT
ihShopId ShopId, ihInvoiceId InvoiceId
, ihInvoiceNo InvoiceNo, ihInvoiceDate InvoiceDate
, ihCustomerId CustomerId, CustomerName
, idItemId ItemId, i.ItemCode, i.ItemDescription
, idPackingTypeId PackId, PackingTypeName, PackingBarCode
, idPQuantity InvoicedPackQty, idQuantity InvoicedQty
, isnull(v.PackQty,0) DeliveredPackQty, isnull(v.Qty,0) DeliveredQty
FROM
losInvoiceHeader ih
INNER JOIN losInvoiceDetail id ON ih.ihShopId=id.idShopId and ih.ihInvoiceId=id.idInvoiceId
INNER JOIN aCustomerMaster c ON ihCustomerId=c.CustomerId
INNER JOIN aPackingType p ON idPackingTypeId=p.PackingTypeId
INNER JOIN aItem i ON id.idItemId=i.ItemId
INNER JOIN aItemPackingDetail ip ON i.ItemId=ip.ItemId AND id.idPackingTypeId=ip.PackingTypeId
-- Join Delivery Verification Details
LEFT OUTER JOIN
(SELECT
dd.CompanyId, dd.ShopId, dd.InvoiceId, dd.ItemId, dd.PackId
, SUM(dd.PackQty) PackQty, SUM(dd.Qty) Qty
FROM
losDeliveryVerificationHeader dh
INNER JOIN losDeliveryVerificationDetails dd
ON dh.CompanyId=dd.CompanyId and dh.ShopId=dd.ShopId
and dh.DeliveryVerificationId=dd.DeliveryVerificationId
WHERE
isnull(dh.Cancelled,0)=0
AND dd.ShopId=@intShopId
AND dd.InvoiceId=@intInvoiceId
GROUP BY
dd.CompanyId, dd.ShopId, dd.InvoiceId, dd.ItemId, dd.PackId) v
ON ih.ihShopId=v.ShopId AND ih.ihInvoiceId=v.InvoiceId
AND id.idItemId=v.ItemId AND id.idPackingTypeId=v.PackId
WHERE
isnull(ihCancelled,0)=0
and idShopId=@intShopId
and idInvoiceId=@intInvoiceId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_FetchCashSaleDeliveryDetails]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_FetchCashSaleDeliveryDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:  Regin T.
-- Create date: 15-07-2010
-- Description:
--   Input:
--  1. Company Id (Not in use now, but to support multiple companies enhancement)
--  2. Shop Id
--  3. Invoice Id (Cash Invoice Id or Credit Invoice Id)
--   Output:
--  Returns the list of sold items
-- To execute:
--  exec spMag_FetchCashSaleDeliveryDetails 1, 1, 17
-- =============================================================================
CREATE PROC [dbo].[spMag_FetchCashSaleDeliveryDetails]
@intCompanyId as int
, @intShopId as int
, @intBillId as int
AS
BEGIN
SET NOCOUNT ON;
-- CASH INVOICE ITEM DETAILS
SELECT
poshShopID ShopId, poshBillID BillId
, poshBillNo BillNo, poshBillDate BillDate
, poshcustomerid CustomerId, poshCustomerName CustomerName
, posdItemID ItemId, i.ItemCode, i.ItemDescription
, posdPackingTypeID PackId, PackingTypeName, PackingBarCode
, posdPQuantity BilledPackQty, posdQuantity BilledQty
, isnull(v.PackQty,0) DeliveredPackQty, isnull(v.Qty,0) DeliveredQty
FROM
losPosHeader
inner join losPosDetail pd ON poshShopID=posdShopID and poshBillID=posdBillID
inner join aPackingType p ON posdPackingTypeID=p.PackingTypeId
INNER JOIN aItem i ON pd.posdItemID=i.ItemId
INNER JOIN aItemPackingDetail ip ON i.ItemId=ip.ItemId AND pd.posdPackingTypeID=ip.PackingTypeId
-- Join Delivery Verification Details
LEFT OUTER JOIN
(SELECT
dd.CompanyId, dd.ShopId, dd.BillId, dd.ItemId, dd.PackId
, SUM(dd.PackQty) PackQty, SUM(dd.Qty) Qty
FROM
losDeliveryVerificationHeader dh
INNER JOIN losDeliveryVerificationDetails dd
ON dh.CompanyId=dd.CompanyId and dh.ShopId=dd.ShopId
and dh.DeliveryVerificationId=dd.DeliveryVerificationId
WHERE
isnull(dh.Cancelled,0)=0
AND dd.ShopId=@intShopId
AND dd.BillId=@intBillId
GROUP BY
dd.CompanyId, dd.ShopId, dd.BillId, dd.ItemId, dd.PackId) v
ON poshShopId=v.ShopId AND poshBillId=v.BillId
AND posdItemId=v.ItemId AND posdPackingTypeId=v.PackId
WHERE
isnull(poshCancelled,0)=0
and poshShopID=@intShopId
and poshBillID=@intBillId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_DeleteDeliveryVerification]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_DeleteDeliveryVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:  MANUNADH.U.
-- Create date: 10-08-2010
-- Description: To use in the Delivery Item Verification Module
--   Input:
--     1. Company Id (Not in use now, but to support multiple companies enhancement)
--     2. Shop Id
--     3. @Id-Invoice Id
--	   4. @Type --Invoice or bill
--   Output:
--     Returns TRUE if items are already fully delivered,
--    FALSE otherwise.
-- =============================================================================
-- =============================================================================
CREATE PROC [dbo].[spMag_DeleteDeliveryVerification]
@CompanyId AS INT
,@ShopId AS INT
,@Id AS INT
,@Type AS nchar(1)  --''I'' FOR INVOICE & ''B'' FOR BILLS
AS
BEGIN
	DECLARE @Count NUMERIC(18,3)
	DECLARE @DeliveryVerificationId AS INT
	SET NOCOUNT ON;
	IF @Type =''I''
	  BEGIN
		-- Check if Invoice is delivered already.
		SELECT @Count=COUNT(*) FROM losDeliveryVerificationDetails where invoiceid=@Id and shopid=@ShopId AND COMPANYID=@CompanyId
		IF @Count > 0
		  BEGIN
			SELECT @DeliveryVerificationId=DeliveryVerificationId FROM losDeliveryVerificationDetails where invoiceid=@Id and shopid=@ShopId AND COMPANYID=@CompanyId
			delete from losDeliveryVerificationDetails where invoiceid=@Id and shopid=@ShopId AND COMPANYID=@CompanyId  -- DeliveryVerificationId=@DeliveryVerificationId
			delete from losDeliveryVerificationHeader  where DeliveryVerificationId=@DeliveryVerificationId
		  END
	  END
	ELSE IF @Type =''B''
	  BEGIN
		-- Check if Invoice is delivered already.
		SELECT @Count=COUNT(*) FROM losDeliveryVerificationDetails where BillID=@Id and shopid=@ShopId AND COMPANYID=@CompanyId
		IF @Count > 0
		  BEGIN
			SELECT @DeliveryVerificationId=DeliveryVerificationId FROM losDeliveryVerificationDetails where BillID=@Id and shopid=@ShopId AND COMPANYID=@CompanyId
			delete from losDeliveryVerificationDetails where BillID=@Id and shopid=@ShopId AND COMPANYID=@CompanyId --DeliveryVerificationId=@DeliveryVerificationId
			delete from losDeliveryVerificationHeader  where DeliveryVerificationId=@DeliveryVerificationId
		  END
	  END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInsertTillHeader]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertTillHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 29/Sep/2010
--Created by	: Praveen S
--Comments	: For Inserting the Details In Till Header
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spInsertTillHeader]
@tillid INT,
@tillname VARCHAR(50),
@tilloutletid INT,
@tillcompanyid INT,
@tillremarks VARCHAR(250),
@tillactive BIT,
@tillStatus INT = 3
AS BEGIN
	 SET NOCOUNT ON
	 INSERT INTO TillHeader(till_th_tillid,till_th_tillname,till_th_outletid,
	 till_th_companyid,till_th_statusid,till_th_remarks,till_th_active)
	 VALUES
	 (@tillid,@tillname,@tilloutletid,@tillcompanyid,@tillStatus,@tillremarks,@tillactive)
		
END' 
END
GO
/****** Object:  View [dbo].[vwnotcoastingpayments]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnotcoastingpayments]'))
EXEC dbo.sp_executesql @statement = N'
CREATE  view [dbo].[vwnotcoastingpayments] as
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate, phAmount,phexchangerate ,(phAmount*phexchangerate)CompanyAmount,(phAmount*phdepexrate)DepartmentAmount  from
(select phFinancialID,phpohid,phdepexrate ,phAmount,phCustomerID,phVendorID,phPayee,phPaymentDate,phpaymentid,phCompanyID, pddPaymentID,phDepartmentID,phPaymentNo, pddhqpoid ,pddAmount,phexchangerate ,pddAmount*phexchangerate as amount
from ahqpaymentvoucherheader  , ahqpaymentvoucherdebitdetails  where pddhqpoid is not null
and pddPaymentID=phPaymentID and phCancelled=0
and pddhqpoid  not in  (select pbhPOID  from LOspPurchaseBillHeader where pbhCancelled=0)) vw1 ,lopurchaseorderheader,adepartmentmaster where
DepartmentID=phDepartmentID  and  phDepartmentID = pohDepartmentid
and pohPoid=pddhqpoid
union all
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate, phAmount,phexchangerate,(phAmount*phexchangerate)CompanyAmount,(phAmount*phdepexrate)DepartmentAmount
from ahqpaymentvoucherheader  , ahqpaymentvoucherdebitdetails ,adepartmentmaster where  pddPaymentID=phPaymentID --and phFinancialID=4
and  phCancelled=0 and DepartmentID=phDepartmentID
and phPaymentNo in (select    h.referenceno   from moajournaldetails d
inner join moajournalheader h on h.journalid=d.Journalid and h.Cancel=0 and AccountID= 520 and type=''p'') and pddhqpoid  is null'
GO
/****** Object:  View [dbo].[vwHqPurchaseOrderpre]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrderpre]'))
EXEC dbo.sp_executesql @statement = N'
/*
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
/****** Object:  View [dbo].[vwHqPurchaseOrder]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder]'))
EXEC dbo.sp_executesql @statement = N'
/*
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
/****** Object:  View [dbo].[vwInHouseConsumption]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInHouseConsumption]'))
EXEC dbo.sp_executesql @statement = N'
--Created by Sreejith G A
--Created on 12/07/2010
--Purpose : To show Inhouse consumption details
Create view [dbo].[vwInHouseConsumption] as
select whShopID as ShopID,WhDate as ConsDate,WdItemID as ItemId,a.ItemDescription,atc.ItemCategoryID,
atc.CategoryNameDescription ItemCategory,abm.BrandName,WdWriteoffQty as InhConsQty,WdunitID as UnitId,
whotherdepid as ToDeptID,au.UnitName
from loswriteoffdetail lwd
left outer join loswriteoffheader on whid=wdid
left outer join aitem a on a.itemid= lwd.WdItemID
left outer join aBrandMaster abm on abm.brandname= a.brand
left outer join aitemcategory atc on atc.ItemCategoryID=a.ItemCategoryID
left outer join aunit au on au.unitid=a.UnitsID'
GO
/****** Object:  View [dbo].[vwShoprequestpending]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShoprequestpending]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[vwShoprequestpending] as
select GRHrequestID,GRHrequestNO,GRHshopID,GRHrequestDate,GRHremarks,
GRDitemID,GRDgoodQty,GRDbadQty,''PO Request'' Transtype,0 ToShopid
from mosgoodsrequestheader,mosgoodsrequestdetail
where GRHrequestID=GRDrequestID  and grhshopid=grdshopid and
GRHIssuenotegenerated=0 and GRHcancel=0 and grhrequesttype=''p''
union all
select GRHrequestID,GRHrequestNO,GRHshopID,GRHrequestDate,GRHremarks,
GRDitemID,GRDgoodQty,GRDbadQty,''Godown Request'',0
from mosgoodsrequestheader,mosgoodsrequestdetail  where
GRHrequestID=GRDrequestID  and grhshopid=grdshopid and
GRHIssuenotegenerated=0 and GRHcancel=0 and grhrequesttype=''G''
union all
select SRHrequestID,SRHrequestNO,SRHshopid,SRHrequestdate,SRHremarks,
srditemid,srdgoodqty,srdbadqty,''Shop to Shop Request'',srdToShopid
from mesrequesttoshopheader a, mesrequesttoshopdetail b
where a.SRHrequestID=SRDrequestid and SRHshopid=srdshopid and
SRHUsed=0 and SRHcancelled=0 and srhType=''s''
union all
select SRHrequestID,SRHrequestNO,SRHshopid,SRHrequestdate,SRHremarks,
srditemid,srdgoodqty,srdbadqty,''Inter Department Request'',srdToShopid
from mesrequesttoshopheader a,mesrequesttoshopdetail b
where
a.SRHrequestID=SRDrequestid and SRHshopid=srdshopid and
SRHUsed=0 and SRHcancelled=0 and srhType=''R'''
GO
/****** Object:  View [dbo].[vwshoppurchaseBills]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchaseBills]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 09/12/2002, 29/06/2009
--Modified by  : leo,Sebin
--Comments  : v3
--Sebin 29/062009 (lphbillamount-isnull(lphdiscount,0)) altered to lphbillamount
CREATE view [dbo].[vwshoppurchaseBills] as
select lphcompanyid, lphshopid, lphDepartmentid, lphBillid, lphbillno, lphvendorbillno,
lphbilldate, lphduedateforpayment lphduedate, lphvendorid, lphbillamount lphamount,
0 as paidamount, (lphbillamount) * lphexchangerate lphcamount,
(lphbillamount) * lphdepexrate lphdamount
from loslocalpurchaseheader where lphcancelled=0 and lphsettled=0 and lphcashpurchase=0
and lphConfirmed=1'
GO
/****** Object:  View [dbo].[vwLoyaltyPointsDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLoyaltyPointsDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By   :Shinu
-- Created On   :03/07/2007
-- Purpose      :For Points Calculation in LMS
-- Modified by  :
-- Modified on  :
-- Comments     :
create view [dbo].[vwLoyaltyPointsDetails] as
SELECT   PoshShopID shopId,poshBillId BiilID,poshBillNo BillNo,poshBilldate BillDate,poshCustomerid CustomerID,
CustomerName,cc.contactId ContactID,cc.FirstName +'' ''+ cc.Lastname ContactName ,sum(posdUnitPrice)Amount,
PoshDepartmentID DepartmentID,ContactcardNo LoyaltyCardNo,
poshCounterID CounterID,cast(round(sum(posdUnitPrice)/Amount,2)as numeric(18,2)) as Points,
cast(round((sum(posdUnitPrice)/Amount)*PointsValue,2)as numeric(18,2)) PointsValue,''POS'' Type
FROM  LOsPosHeader los
INNER JOIN  LOsPosDetail lod ON los.poshShopID = lod.posdShopID AND
los.poshBillID = lod.posdBillID
INNER JOIN  aLoyaltyCardContactDetails lcd ON los.ContactCardNo = lcd.CardNo AND los.poshCompanyID = lcd.CompanyID
INNER JOIN  aLoyaltyCardMaster lcm ON lcd.CardID = lcm.CardID AND los.poshCompanyID = lcm.CompanyID
INNER JOIN  CrmContact cc ON lcd.ContactID = cc.ContactID AND los.poshCompanyID = cc.Companyid
INNER JOIN  aCustomerMaster ac ON los.poshcustomerid = ac.CustomerID AND los.poshCompanyID = ac.CompanyID
Inner Join aitem ai ON ai.itemid=lod.posdItemId and ai.LoyaltyAvailable=1
where poshcancelled =0 and poshreturned=0
group by PoshShopID,poshBillId,poshBillNo,poshBilldate,poshCustomerid,CustomerName,
cc.contactId ,cc.FirstName +'' ''+ cc.Lastname,PoshDepartmentID,PoshDepartmentID ,
ContactcardNo,PoshCounterID,Amount,PointsValue
Union All
SELECT   ihShopID ,ihInvoiceId ,ihinvoiceNo,IhInvoicedate,ihCustomerid ,CustomerName,cc.contactId ,
cc.FirstName +'' ''+ cc.Lastname,sum(idUnitPrice),ihDepartmentID,ContactcardNo,0,
cast(round(sum(idUnitPrice)/Amount,2)as numeric(18,2))  ,
cast(round((sum(idUnitPrice)/Amount)*PointsValue,2)as numeric(18,2)),''INV''
FROM   LOsInvoiceHeader los
INNER JOIN  LOsinvoiceDetail lod ON los.ihShopID = lod.idShopID AND
los.ihInvoiceId = lod.idInvoiceId
INNER JOIN  aLoyaltyCardContactDetails lcd ON los.ContactCardNo = lcd.CardNo AND los.ihCompanyID = lcd.CompanyID
INNER JOIN  aLoyaltyCardMaster lcm ON lcd.CardID = lcm.CardID AND los.ihCompanyID = lcm.CompanyID
INNER JOIN  CrmContact cc ON lcd.ContactID = cc.ContactID AND los.ihCompanyID = cc.Companyid
INNER JOIN  aCustomerMaster ac ON los.ihcustomerid = ac.CustomerID AND los.ihCompanyID = ac.CompanyID
Inner Join aitem ai ON ai.itemid=lod.idItemId and ai.LoyaltyAvailable=1
where ihcancelled =0 and ihGoodsReturned=0 and ihType=''I''
group by ihShopID ,ihInvoiceId ,ihinvoiceNo,IhInvoicedate,ihCustomerid ,CustomerName,cc.contactId ,
cc.FirstName +'' ''+ cc.Lastname  ,ihDepartmentID,ContactcardNo,Amount,PointsValue'
GO
/****** Object:  View [dbo].[vwimportitem_sa]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwimportitem_sa]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwimportitem_sa]
as SELECT aItem."ItemCode", aItem."ItemDescription", aItem."brand",aSize."SizeName", aColor."ColorName",aUnit."UnitCode",
	sum(lOspPurchaseBillDetail."pbdItemQuantity")as quantity,aVendorMaster."VendorName"
FROM
{ oj ((((("AdminV2"."dbo"."LOspPurchaseBillHeader" LOspPurchaseBillHeader INNER JOIN "AdminV2"."dbo"."aVendorMaster" aVendorMaster ON
LOspPurchaseBillHeader."pbhVendorID" = aVendorMaster."VendorID")
INNER JOIN "AdminV2"."dbo"."LOspPurchaseBillDetail" LOspPurchaseBillDetail ON
LOspPurchaseBillHeader."pbhBillID" = LOspPurchaseBillDetail."pbdBillID")
INNER JOIN "AdminV2"."dbo"."aItem" aItem ON
LOspPurchaseBillDetail."pbdItemID" = aItem."ItemID")
LEFT OUTER JOIN "AdminV2"."dbo"."aColor" aColor ON
aItem."ColorID" = aColor."ColorID")
INNER JOIN "Adminv2"."dbo"."aUnit" aUnit ON
aItem."UnitsID" = aUnit."UnitID")
LEFT OUTER JOIN "AdminV2"."dbo"."aSize" aSize ON
aItem."SizeID" = aSize."SizeID"}
WHERE
LOspPurchaseBillHeader."pbhBillDate" >= ''2007-1-1'' AND
LOspPurchaseBillHeader."pbhBillDate" < ''2008-2-29'' AND
aItem."brand" = ''CAPAROL''
group by aItem."ItemCode", aItem."ItemDescription", aItem."brand",aSize."SizeName", aColor."ColorName",aUnit."UnitCode",
aVendorMaster."VendorName"'
GO
/****** Object:  View [dbo].[vwloiarrivaldetail]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwloiarrivaldetail]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwloiarrivaldetail] as
select adArrivalID, adGodownID, adItemID, isnull(pc.quantity,0) * adDespatchedQty despacthedqty,
isnull(pc.quantity,0) * adReceivedQty receivedqty, adcostprice  from loiarrivaldetail ad,
apackingtypecapacitydetail pc, aitem i where i.unitsid = pc.unitsid and pc.packingtypeid =
ad.adpackingtypeid and i.itemid = ad.aditemid
union all
select asdArrivalID, asdGodownID, asdItemID, asdDespatchedGoodQty,
asdReceivedGoodQty, asdcostprice from loiarrivalshipmentdetail'
GO
/****** Object:  View [dbo].[vwLocalUserRightsRptDtls]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalUserRightsRptDtls]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By	: Hariharan
--Modified Date	: 04/02/2004
--COMMENTS	: MODIEIFIED TO INCLUDE REPORT RIGHTS
CREATE view [dbo].[vwLocalUserRightsRptDtls] as
select ai.interfacename,ai.interfaceid,au.userid,au.username,au.shopid,au.godownid,
case when Patindex(''%N%'', functionrights)>0 then ''Y'' else ''N'' end  New,
case when Patindex(''%E%'', functionrights)>0 then ''Y'' else ''N''  end  Edit,
case when Patindex(''%D%'', functionrights)>0 then ''Y'' else ''N''  end  [Delete],
case when Patindex(''%U%'', functionrights)>0 then ''Y'' else ''N''  end  Posting ,
case when Patindex(''%P%'', functionrights)>0  then ''Y'' else''N'' end  Printing,ai.ModuleCode,
Case substring(ai.Modulecode, 1, 2) when ''po'' then ''Point of Sales - Transactions'' when ''pa'' then
''Point Of Sales - Admin'' when ''inv'' then ''Inventory - Transactions''
when ''invadm'' then ''Inventory - Admin'' end ModuleName
from louserrights ar left outer join ainterface ai on
ar.interfaceid=ai.interfaceid  and ar.companyid=ai.companyid
left outer join lousers au on au.userid=ar.userid  group by
ai.interfaceid,ai.interfacename,au.userid,au.username,FunctionRights,ai.ModuleCode,
au.shopid,au.godownid
Union ALl
Select cd.RepDetailName +  '' - '' + ai.Reportname,ai.Reportid,au.userid,au.username, au.shopid, au.godownid,
''-'' New, ''-'' Edit, ''-'' [Delete], ''-'' [Print], ''-'' [Posting],
substring(rc.repCatName, 1, 50),case rc.RepCatName when ''PANDC'' then ''Purchase And Costing - Reports''
when ''Accounts'' then ''Accounts - Reports'' when ''Payroll'' then ''Payroll - Reports''
when ''Budgeting'' then ''Budgeting - Reports'' when ''Admin'' then ''Admin'' when ''Administration'' then
''Administration - Reports'' end ModuleName
from loUsers au, aloreportrights ar, areports ai, reportcategorydetail cd,
reportcategoryheader rc where ar.reportid = ai.reportid  and au.userid = ar.userid
and ai.ReportCatId = cd.RepCatId and ai.ReportDetailId = cd.RepDetailID and
rc.repCatId = cd.repCatId and rc.type =''R''
group by au.shopid,au.godownid, ai.reportid, cd.RepDetailName, ai.ReportName, au.userid, au.username,
rc.RepCatName
Union ALl
Select cd.RepDetailName +  '' - '' + ai.Reportname,ai.Reportid,au.userid,au.username, au.shopid, au.godownid,
''-'' New, ''-'' Edit, ''-'' [Delete], ''-'' [Print], ''-'' [Posting],
substring(rc.repCatName, 1, 50),case rc.RepCatName when ''PANDC'' then ''Purchase And Costing - Reports''
when ''Accounts'' then ''Accounts - Reports'' when ''Payroll'' then ''Payroll - Reports''
when ''Budgeting'' then ''Budgeting - Reports'' when ''Admin'' then ''Admin'' when ''Administration'' then
''Administration - Reports'' end ModuleName  from loUsers au, aloreportrights ar, areports ai, reportcategorydetail cd,
reportcategoryheader rc where ar.reportid = ai.reportid  and au.userid = ar.userid
and ai.ReportCatId = cd.RepCatId and ai.ReportDetailId = cd.RepDetailID and
rc.repCatId = cd.repCatId and rc.type =''A''
group by au.shopid,au.godownid, ai.reportid, cd.RepDetailName, ai.ReportName, au.userid, au.username,
rc.RepCatName'
GO
/****** Object:  View [dbo].[vwquotationtracking2]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking2]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwquotationtracking2] as
select vw.pohshopid,vw.pohpoid,vw.pohrequestid,vw.HQRequestNo,
case when vw.ShopRequetNO  is not null then  vw.ShopRequetNO else mos.Grhrequestno end as ShopRequetNO,
'''' as QuotationNo
from vwquotationtracking1 vw left outer join mosgoodsrequestheader mos
on vw.pohrequestid=mos.grhrequestid and vw.pohshopid =mos.grhshopid'
GO
/****** Object:  View [dbo].[vwrebateapproval]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrebateapproval]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last modified by : Santhosh M
--Added ihcancelled field on 01/10/2003
CREATE view [dbo].[vwrebateapproval] as
SELECT
	idItemID,ihInvoiceID,ihinvoiceno,ihInvoiceDate,ItemCode,ItemDescription,rrshopid,idQuantity,idunitprice,idPQuantity,
	rrreqid,rrreqno, rrreqdate,rrsalespersonid,Spername,idrebateamount,ihcancelled
FROM
LOsInvoiceDetail
INNER JOIN
LOsInvoiceHeader ON
ihInvoiceID=idInvoiceID and ihshopid=idshopid
LEFT OUTER JOIN aItem  ON
idItemID = ItemID
LEFT OUTER JOIN losrebaterequest on
ihShopID =rrshopid AND rrpoid=ihInvoiceID
		
LEFT OUTER JOIN asalespersonmaster  ON
rrsalespersonid = Sperid
where
		 rrpoid=ihInvoiceID and ihShopID =rrshopid and ihtype=''P'''
GO
/****** Object:  View [dbo].[vwConfirmedDeliveryNote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwConfirmedDeliveryNote]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------
-- Ceated by : MANUNADH.U
-- Date      : 07/12/2011
-- Comments  : To get all the confirmed DeliveryNote to list in the Unconfirm Transaction interface
------------------------------------------------------------------------------------------
create VIEW [dbo].[vwConfirmedDeliveryNote]
AS
select H.DnShopid,H.DndnId,H.DndnNo,H.DndnDate,H.DnCustomerID,H.dnCustomerName,
CONVERT(VARCHAR(5),H.DnDeliveryTime,108) + '' '' + RIGHT(CONVERT(VARCHAR,H.DnDeliveryTime, 109),2)DeliveryTime
from  losDeliveryNoteheader H
inner join losDeliveryNoteDetail D ON h.DnShopid = d.DndShopid and h.DndnId = d.DnDdnId
LEFT OUTER JOIN losInvoiceHeader PO ON d.dndinvoiceid = po.ihinvoiceid and d.dndshopid = po.ihshopid
left outer join losInvoiceHeader ih on PO.ihInvoiceId = ih.IhProformaId and PO.IhSHopId = ih.IhSHopId
	and ih.ihType=''I'' AND ih.ihCancelled =0
where H.DNCANCELLED=0  and H.dnConfirmed=1 and isnull(ih.ihinvoiceid,0)=0'
GO
/****** Object:  View [dbo].[vwcreditnote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditnote]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcreditnote    Script Date: 18/01/2003 9:45:35 PM ******/
--Last Modified on  : 28/12/2002
--Modified by  : dheena
--Comments  : add department name add id
CREATE view [dbo].[vwcreditnote] as
select dcncompanyid, dcnid, dcndate, dcnrefno, dcnreferenceno, case when dcncustomerid is not
null then cus.customername else ven.vendorname end Debitto, dcnamount, dcncancelled,
dcncancelledremarks, dcndetails, dcnexchangerate, dcndepexrate,dcndepartmentid,d.DepartmentName,UpdateTime
from debitcreditnote dcn
left outer join acustomermaster cus on dcn.dcncompanyid = cus.companyid and dcn.dcncustomerid =
cus.customerid
left outer join avendormaster ven on dcn.dcncompanyid = ven.companyid and dcn.dcnvendorid =
ven.vendorid ,adepartmentmaster d
where  dcndebit = 0 and d.DepartmentID=dcndepartmentid and DCNCompanyid=d.companyid'
GO
/****** Object:  View [dbo].[vwcreditinvoice]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditinvoice]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------
--Modified on  : 07/08/2003.08/08/2003,03/12/2003, 03/02/2004, 05/02/2004,27-01-2012
--Modified by : R Harikrishnan,venki(added canceled remarks), Hariharan,Yogesh Joe,MANUNADH. U
--Comments : Changed the isnull condition for other
--  : iddescription, Added other charges amount
--  : given ihProformaId condition for joining with Delivery Note
--  : GROUP BY condition given to avoid duplicates
---------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 14-08-2009
-- Purpose: Added Kit Item Details
-- Added the column ihinvoiceamount since it is necessary for "To Screen" print and "To Printer" print
---------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 28-01-2010
-- Purpose: Added SerialNos column to get the comma separated serial numbers of sold items
---------------------------------------------------------------------
-- Modified By: Aadyakumar.D.V.
-- Modified On: 23-05-2011
-- Find this view is latest chandlier update
-- So i am updating this view from KJI-987303
---------------------------------------------------------------------
-- Ref.No.1
-- Modified By: Aadyakumar.D.V.
-- Modified On: 13-09-2011
-- Bug fixing in report rptCreditInvoiceA5,error msg "Blob variable can''t use in formule field"
---------------------------------------------------------------------
-- Ref.No.2
-- Modified By: Nidheesh P V
-- Modified On: 24-09-2011
-- Added customer TIN
---------------------------------------------------------------------
-- Ref.No.3
-- Modified By: MANUNADH. U
-- Modified On: 24-10-2011 ,27-01-2012
-- Purpose   : To solve the issue in Credit Invoice report
-- Issue   : Delivery Note No is not showing in the Credit Invoice report.Also addres is showing incorrectly.
---------------------------------------------------------------------
-- Ref.No.4
-- Modified By: SHINE DAS
-- Modified On: 22-11-2011
-- Issue   : Address is showing incorrectly. And warranty dates added.
---------------------------------------------------------------------
-- Ref.No.5
-- Modified By: AADYA KUMAR D V
-- Modified On: 23-11-2011
-- Issue   : Added idBillDetailID
---------------------------------------------------------------------
-- Ref.No.6
-- Modified By: SHINE DAS
-- Modified On: 21-12-2011
-- Issue   : If more serial numbers are existing, all numbers are not listing in reports.
-- To solve it VARCHAR(100) changed to VARCHAR (MAX)
---------------------------------------------------------------------
CREATE view  [dbo].[vwcreditinvoice]  as
select v1.*,  v2.ihInvoiceNo as PurchaseOrderNO, shopName,
case when v1.idItemType=''I'' then
--dbo.fnIssueSerialNos(1504, v1.ihshopid, v1.ihinvoiceid, v1.iditemid) --Ref.No.1
convert(varchar(MAX),dbo.fnIssueSerialNos(1504, v1.ihshopid, v1.ihinvoiceid, v1.iditemid))--Ref.No.1   -- Ref.No.6
else '''' end idSerialNos from
(
-- To get Normal Items
select isnull(spername,'''') spername,ihdiscount,case when (isnull(iddescription,'''') ='''') then
vw.itemdescription else iddescription end itemdescription,ihinvoiceid,ihinvoiceno,ihReferenceNo,
ihshopid,ihinvoicedate,ihduedate,iditemid,idquantity,idpquantity,idunitprice,idactualunitprice,
idcostprice,ihRecAddUser,ihRecModifyUser,UnitCode,packingtypecode,customername,Address1,Address2,
Address3,Symbol,idpackingtypeid,u.unitid,a.itemcode,ihremarks,unitname,packingtypename,ihexchangerate,
ihdepexrate,dndnno,dndndate,
case when len(ihcancelledremarks)<>0 then ihcancelledremarks else AC.Address1+'',''+AC.Address2+'',''+AC.Address3 end address, -- Ref.No.4
--case when ihcancelled =1 then ihcancelledremarks else AC.Address1+'',''+AC.Address2+'',''+AC.Address3 end address, -- Ref.No.4
--case when ihcancelled =0 then ihcancelledremarks else '''' end address, --<<Ref.No.3>>
a.itemtype,ihdutypaidby,idcdcustcur,isnull(ocd.ioAmount,0) OtherChargesAmt,ihcancelled,
isnull(idFreeQuantity,0) idFreeQuantity,ihcancelledremarks,idCustomPrice CustomPrice,ihinvoiceamount,
idItemType,CUSTOMERTIN,    --Ref.No.2
idServWarrantyUpto,idPartsWarrantyUpto, -- Ref.No.4
idBillDetailID -- Ref.No.5
from losinvoiceheader
left outer join asalespersonmaster sp on ihsalespersonid = sp.sperid
left outer join
(
select ioShopID,ioInvoiceID,sum(ioAmount) ioAmount
from losInvoiceOC
group by ioShopID,ioInvoiceID
) ocd on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID
left outer join
(
select dnshopid, dndnid,  dndnno, dndndate, dndinvoiceid
from LosDeliveryNoteDetail dd, LosDeliveryNoteHeader dh
where dd.dndshopid = dh.dnshopid and dd.dnddnid = dh.dndnid and dh.Dncancelled =0
group by dnshopid, dndnid,dndnno,dndndate,dndinvoiceid
)dn --on ihProformaID = dndinvoiceid --on ihinvoiceid = dndinvoiceid  --<<Ref.No.3>>Old
on (ihProformaID = dndinvoiceid or ihinvoiceid = dndinvoiceid)  --<<Ref.No.3>>New
and ihshopid = dnshopid,
losinvoicedetail,aitem a,apackingtype p,vwitemdescription vw,aunit u,acustomermaster ac,acurrencymaster c
where ihshopid= idshopid and ihinvoiceid=idinvoiceid and idpackingtypeid=p.packingtypeid and
iditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid and
ac.customerid=ihcustomerid and ac.currencyid=c.currencyid and ihtype=''I'' -- I stands for Invoice
and (idItemType=''I'' or idItemType=''0'' or idItemType is null) -- To fetch ONLY Normal Item
union all
-- To get Kit Items
select isnull(spername,'''') spername,ihdiscount, case when (isnull(iddescription,'''') ='''') then k.KitName
else iddescription end itemdescription,ihinvoiceid,ihinvoiceno,ihReferenceNo,ihshopid,ihinvoicedate,
ihduedate,k.KitID ItemID, idKitQuantity Quantity,idKitQuantity PQuantity,
idKitActualPrice*idKitQuantity Amount, --sum(idUnitPrice) Amount,
idKitActualPrice,sum(idcostprice) CostPrice,ihRecAddUser,ihRecModifyUser,UnitCode,packingtypecode,
customername,Address1,Address2, Address3, Symbol, k.PackingTypeID,k.UnitID, k.KitCode, ihremarks, unitname,
packingtypename,ihexchangerate, ihdepexrate, dndnno, dndndate,
case when len(ihcancelledremarks)<>0 then ihcancelledremarks else AC.Address1+'',''+AC.Address2+'',''+AC.Address3 end address, -- Ref.No.4
--case when ihcancelled =1 then ihcancelledremarks else AC.Address1+'',''+AC.Address2+'',''+AC.Address3 end address,-- Ref.No.4
--case when ihcancelled =0 then ihcancelledremarks else '''' end address, --<<Ref.No.3>>
'''' ItemType, ihdutypaidby, idcdcustcur,isnull(ocd.ioAmount,0) OtherChargesAmt,
ihcancelled, isnull(idFreeQuantity,0) idFreeQuantity,
ihcancelledremarks, idCustomPrice CustomPrice, ihinvoiceamount, idItemType,CUSTOMERTIN  --Ref.No.2
,idServWarrantyUpto,idPartsWarrantyUpto,          -- Ref.No.4
idBillDetailID -- Ref.No.5
from losinvoiceheader
left outer join aSalesPersonMaster sp on ihsalespersonid = sp.sperid
left outer join
(
Select ioShopID,ioInvoiceID,sum(ioAmount) ioAmount
from losInvoiceOC
group by ioShopID,ioInvoiceID
) ocd on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID
left outer join
(
select dnshopid, dndnid,  dndnno, dndndate, dndinvoiceid
from LosDeliveryNoteDetail dd, LosDeliveryNoteHeader dh
where dd.dndshopid = dh.dnshopid and dd.dnddnid = dh.dndnid and dh.Dncancelled =0
group by dnshopid, dndnid,  dndnno, dndndate,dndinvoiceid
) dn --on ihProformaID = dndinvoiceid --on ihinvoiceid = dndinvoiceid  --<<Ref.No.3>> Old
on (ihProformaID = dndinvoiceid or ihinvoiceid = dndinvoiceid)  --<<Ref.No.3>>New
and ihshopid = dnshopid,
losinvoicedetail, aKitItemMaster k, apackingtype p, aunit u,acustomermaster ac, acurrencymaster c
where ihshopid=idshopid and ihinvoiceid=idinvoiceid and idKitID=k.KitID
and k.PackingTypeID=p.packingtypeid and u.unitid=k.UnitID
and ac.customerid=ihcustomerid and ac.currencyid=c.currencyid and ihtype=''I''
and idItemType=''K'' -- To fetch ONLY Kit Item
group by isnull(spername,''''),ihdiscount,
case when (isnull(iddescription,'''') ='''') then k.KitName else iddescription end,
ihinvoiceid,ihinvoiceno,ihReferenceNo, ihshopid, ihinvoicedate, ihduedate,
k.KitID, idKitQuantity, idKitActualPrice, ihRecAddUser, ihRecModifyUser, UnitCode, packingtypecode,
customername,Address1,Address2, Address3, Symbol, k.PackingTypeID,
k.UnitID, k.KitCode, ihremarks, unitname, packingtypename,
ihexchangerate, ihdepexrate, dndnno, dndndate,
case when ihcancelled =0 then ihcancelledremarks else '''' end,
ihdutypaidby, idcdcustcur,isnull(ocd.ioAmount,0),
ihcancelled, isnull(idFreeQuantity,0),
ihcancelledremarks, idCustomPrice, ihinvoiceamount, idItemType,CUSTOMERTIN,idServWarrantyUpto,idPartsWarrantyUpto,   --Ref.No.2
idBillDetailID -- Ref.No.5
)v1
left outer  join
(
select a.ihInvoiceNo,a.ihshopid ,ih.ihinvoiceid from losInvoiceHeader
a left outer join   losInvoiceHeader ih on a.ihinvoiceid = ih.ihproformaid
and a.ihshopid = ih.ihshopid and a.ihcompanyid = ih.ihcompanyid
) v2 On v1.ihshopid=v2.ihshopid and v1.ihinvoiceid=v2.ihinvoiceid
left outer join ashops on v1.ihshopid=shopid
--group by v1.idBillDetailID
---------
---------'
GO
/****** Object:  View [dbo].[vwcreditpurchaserequest]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditpurchaserequest]'))
EXEC dbo.sp_executesql @statement = N'
--done by venki 230203
--use :- for getting the purchase request transaction report
--Last Modified by  :santhosh M
--Added ihcancelled 0n 30/09/2003
---------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 23-04-2010
-- Purpose:
-- Added Kit Item Details
-- Added the column ihinvoiceamount
-- since it is necessary for "To Screen" print and "To Printer" print
---------------------------------------------------------------------
CREATE view [dbo].[vwcreditpurchaserequest] as
select
case when isnull(iddescription,'''')='''' then vw.itemdescription else iddescription end
itemdescription, ihinvoiceid,ihinvoiceno,ihReferenceNo, ihshopid, ihinvoicedate,
ihduedate, iditemid, idquantity, idpquantity, idunitprice, idactualunitprice,
idcostprice, ihRecAddUser, ihRecModifyUser, UnitCode, packingtypecode, customername,
Address1,Address2, Address3, Symbol, idpackingtypeid, u.unitid, a.itemcode, ihremarks,
unitname, packingtypename, ihexchangerate, ihdepexrate,  case when ihcancelled =0 then
ihcancelledremarks else '''' end address,ihcancelled,ihcancelledremarks,
idCustomPrice CustomPrice, ihinvoiceamount, idItemType
from
losinvoiceheader ,losinvoicedetail, aitem a, apackingtype p,
vwitemdescription vw, aunit u, acustomermaster ac, acurrencymaster c
where
ihshopid= idshopid and ihinvoiceid=idinvoiceid and idpackingtypeid=p.packingtypeid and
iditemid=a.itemid and a.itemid=vw.itemid and u.unitid=a.unitsid  and
ac.customerid = ihcustomerid and ac.currencyid=c.currencyid and ihtype=''R'''
GO
/****** Object:  View [dbo].[vwCreditPurchaseQuotation]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditPurchaseQuotation]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------
--Last modified by  : Hariharan
--Modified Date     : 13/03/2004
---------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 23-04-2010
-- Purpose:
-- Added Kit Item Details
-- Added the column ihinvoiceamount
-- since it is necessary for "To Screen" print and "To Printer" print
---------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 17-05-2010
-- Added: dueperiod,ih.ihcustomerid,ihsalespersonid,notes
-- since these columns are required to customize report.
---------------------------------------------------------------------
-- Modified By: VinothMurugan V
-- Modified On: 04-11-2010
-- Added: Adding userid
--Client : Linkserve
---------------------------------------------------------------------
-- Modified By: Nidheesh P V
-- Modified On: 23-09-2011
-- Added: Adding Tax details
--RefNo: RefNo-1
---------------------------------------------------------------------
-- Modified By: MANUNADH.U
-- Modified On: 07-02-2012
-- Added: CHECK WHETHER idpquantity IS OR NOT TO AVOID DIVIDE BY ZERO ERROR
-- RefNo: RefNo-2
---------------------------------------------------------------------
CREATE VIEW [dbo].[vwCreditPurchaseQuotation] AS
-- To get Normal Items
Select   distinct case when isnull(iddescription,'''')='''' then vw.itemdescription else
iddescription end itemdescription, ih.ihinvoiceid,ih.ihinvoiceno,ih.ihReferenceNo,ih.ihshopid, ih.ihinvoicedate,
ih.ihduedate, iditemid, idquantity, idpquantity,idunitprice, idactualunitprice, idcostprice, ihRecAddUser,
ihRecModifyUser, UnitCode,packingtypecode, customername,Address1,Address2, Address3,CUSTOMERTIN, Symbol,
idpackingtypeid,   --RefNo-1
u.unitid, a.itemcode, ihremarks, unitname, packingtypename, ihexchangerate,ihdepexrate,dh.ihinvoiceid as requestid,
dh.ihinvoiceno as requestno,dh.ihinvoicedate as requestdate,case when ihcancelled =0 then
ihcancelledremarks else '''' end address,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,ih.ihcancelled,
ih.ihcancelledremarks,ihDiscount, idItemType, idCustomPrice CustomPrice, ihinvoiceamount
,day(ih.ihduedate-ih.ihinvoicedate)dueperiod,ih.ihcustomerid,ihsalespersonid,notes,ihuserid
,idItemTaxPercentage as TaxPercentage,idItemTaxAmount as TaxAmount,
ISNULL( convert(numeric(18,2),(idItemTaxAmount/(CASE idpquantity WHEN 0 THEN 1 else idpquantity END ))) ,0) TaxRate  --RefNo-1 --<<RefNo-2>>
--convert(numeric(18,2),(idItemTaxAmount/idpquantity)) as TaxRate  --RefNo-1
---,OtherCharges.ServTaxPercentage,OtherCharges.ServTaxRate,OtherCharges.ServTaxAmount
,idstatus as status --sandeep
from losinvoiceheader ih
	left outer join
	(
		select ihproformaid,ihinvoiceid,ihshopid,ihinvoiceno,ihinvoicedate from losinvoiceheader dh
		where dh.ihcancelled=0
	) dh on ih.ihProformaID = dh.ihInvoiceID and ih.ihShopID = dh.ihShopID
	Left Outer Join
	(
		select ioShopID, ioInvoiceID, sum(ioAmount) ioAmount from losInvoiceOC
		group by ioShopID,ioInvoiceId
	) OtherCharges On ih.ihShopId = OtherCharges.ioShopId and ih.ihInvoiceId = OtherCharges.ioInvoiceId,
	losinvoicedetail, aitem a, apackingtype p, vwitemdescription vw,aunit u, acustomermaster ac, acurrencymaster c
where ih.ihshopid = idshopid and ih.ihinvoiceid = idinvoiceid and idpackingtypeid = p.packingtypeid and
	iditemid = a.itemid and a.itemid = vw.itemid and u.unitid = a.unitsid and ac.customerid = ihcustomerid and
	ac.currencyid = c.currencyid and left(ihtype,1) = ''Q'' and isnull(idItemType,''I'')=''I'' -- To fetch ONLY Normal Item
union all
-- To get Kit Items
Select distinct case when (isnull(iddescription,'''') ='''') then k.KitName else iddescription end itemdescription,
ih.ihinvoiceid, ih.ihinvoiceno,ih.ihReferenceNo,ih.ihshopid, ih.ihinvoicedate, ih.ihduedate,k.KitID ItemID,
idKitQuantity Quantity, idKitQuantity PQuantity,idKitActualPrice*idKitQuantity Amount, --sum(idUnitPrice) Amount,
idKitActualPrice, sum(idcostprice) CostPrice,ihRecAddUser, ihRecModifyUser, UnitCode,p.packingtypecode, customername,
Address1,Address2, Address3,CUSTOMERTIN, Symbol, k.Packingtypeid,     --RefNo-1
u.unitid, k.KitCode, ihremarks, unitname, packingtypename, ihexchangerate,ihdepexrate,  dh.ihinvoiceid as requestid,
dh.ihinvoiceno as requestno,dh.ihinvoicedate as requestdate,case when ihcancelled =0 then
ihcancelledremarks else '''' end address,IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,ih.ihcancelled,
ih.ihcancelledremarks,ihDiscount, idItemType, idCustomPrice CustomPrice, ihinvoiceamount
,day(ih.ihduedate-ih.ihinvoicedate)dueperiod,ih.ihcustomerid,ihsalespersonid, '''' notes,ihuserid
,idItemTaxPercentage as TaxPercentage,idItemTaxAmount as TaxAmount,
ISNULL( convert(numeric(18,2),(idItemTaxAmount/(CASE idKitQuantity WHEN 0 THEN 1 else idKitQuantity END))),0) TaxRate       --RefNo-1    --<<RefNo-2>>
--convert(numeric(18,2),(idItemTaxAmount/idKitQuantity)) as TaxRate       --RefNo-1
---,OtherCharges.ServTaxPercentage,OtherCharges.ServTaxRate,OtherCharges.ServTaxAmount
,'''' as status --sandeep
from losinvoiceheader ih
	left outer join
	(
		select ihproformaid , ihinvoiceid,ihshopid,ihinvoiceno,ihinvoicedate from losinvoiceheader dh
		where dh.ihcancelled=0
	) dh on ih.ihProformaID = dh.ihInvoiceID and ih.ihShopID = dh.ihShopID
	Left Outer Join
	(
		select ioShopID, ioInvoiceID, sum(ioAmount) ioAmount from losInvoiceOC group by ioShopID,ioInvoiceId
	) OtherCharges On ih.ihShopId = OtherCharges.ioShopId and ih.ihInvoiceId = OtherCharges.ioInvoiceId,
	losinvoicedetail,aKitItemMaster k, apackingtype p,aunit u, acustomermaster ac, acurrencymaster c
where ih.ihshopid = idshopid and ih.ihinvoiceid = idinvoiceid and k.PackingTypeID = p.packingtypeid and
idKitID=k.KitID and u.unitid = k.UnitID and ac.customerid = ihcustomerid and ac.currencyid = c.currencyid
and left(ihtype,1) = ''Q'' and idItemType=''K'' -- To fetch ONLY Kit Item
group by case when (isnull(iddescription,'''') ='''') then k.KitName else iddescription end,ih.ihinvoiceid,ih.ihinvoiceno,
ih.ihReferenceNo,ih.ihshopid, ih.ihinvoicedate, ih.ihduedate,k.KitID, idKitQuantity, idKitQuantity,
idKitActualPrice*idKitQuantity,idKitActualPrice, ihRecAddUser, ihRecModifyUser, UnitCode,packingtypecode,
customername,Address1,Address2, Address3, Symbol, k.Packingtypeid,u.unitid, k.KitCode, ihremarks, unitname,
packingtypename, ihexchangerate,ihdepexrate,dh.ihinvoiceid,dh.ihinvoiceno,dh.ihinvoicedate,
case when ihcancelled =0 then ihcancelledremarks else '''' end,IsNull(OtherCharges.ioAmount, 0),ih.ihcancelled,
ih.ihcancelledremarks,ihDiscount, idItemType, idItemType, idCustomPrice, ihinvoiceamount,
ih.ihcustomerid,ihsalespersonid,ihuserid,idItemTaxPercentage,idItemTaxAmount,CUSTOMERTIN        --RefNo-1
---------------------------------------------'
GO
/****** Object:  View [dbo].[vwCreditPurchaseOrder]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditPurchaseOrder]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwCreditPurchaseOrder] AS
select
case when (iddescription is null or iddescription ='''') then vw.itemdescription else
iddescription end itemdescription, ih.ihinvoiceid,ih.ihinvoiceno,ih.ihReferenceNo,
ih.ihshopid, ih.ihinvoicedate, ih.ihduedate, iditemid, idquantity, idpquantity,
idunitprice, idactualunitprice, idcostprice, ihRecAddUser, ihRecModifyUser, UnitCode,
packingtypecode, customername,Address1,Address2, Address3, Symbol, idpackingtypeid,
u.unitid, a.itemcode, ihremarks, unitname, packingtypename, ihexchangerate,
ihdepexrate,  dh.ihinvoiceid as quotationid,dh.ihinvoiceno as quotationno,
dh.ihinvoicedate as quotationdate,case when ihcancelled =0 then ihcancelledremarks
else '''' end address, IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,ih.ihcancelled,
ih.ihcancelledremarks, idCustomPrice CustomPrice, ihinvoiceamount, idItemType
from
losinvoiceheader ih
left outer join
(select
ihproformaid , ihinvoiceid,ihshopid,ihinvoiceno,ihinvoicedate
from
losinvoiceheader dh
where  dh.ihcancelled=0) dh
on ih.ihProformaID=dh.ihInvoiceID and ih.ihShopID=dh.ihShopID
Left Outer Join (select
ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
from
losInvoiceOC
group by
ioShopID,ioInvoiceId) OtherCharges
On ih.ihShopId = OtherCharges.ioShopId
and ih.ihInvoiceId = OtherCharges.ioInvoiceId,
losinvoicedetail, aitem a, apackingtype p, vwitemdescription vw, aunit u,
acustomermaster ac, acurrencymaster c
where
ih.ihshopid= idshopid and ih.ihinvoiceid=idinvoiceid and
idpackingtypeid=p.packingtypeid and iditemid=a.itemid and a.itemid=vw.itemid and
u.unitid=a.unitsid  and ac.customerid = ihcustomerid and ac.currencyid=c.currencyid and
ihtype=''P''
and (idItemType=''I'' or idItemType=''0'' or idItemType='''' or idItemType is null) -- To fetch ONLY Normal Item
union all
--The below code is added to handle the kititems separately--Yogesh--21-08-2009
select
k.KitName, ih.ihinvoiceid,ih.ihinvoiceno,ih.ihReferenceNo,
ih.ihshopid, ih.ihinvoicedate, ih.ihduedate, k.KitID, idKitQuantity,idKitQuantity,
idKitActualPrice*idKitQuantity Amount, idKitActualPrice, sum(idcostprice) CostPrice, ihRecAddUser, ihRecModifyUser, UnitCode,
packingtypecode, customername,Address1,Address2, Address3, Symbol, k.PackingTypeID,
u.unitid, k.KitCode, ihremarks, unitname, packingtypename, ihexchangerate,
ihdepexrate,  dh.ihinvoiceid as quotationid,dh.ihinvoiceno as quotationno,
dh.ihinvoicedate as quotationdate,case when ihcancelled =0 then ihcancelledremarks
else '''' end address, IsNull(OtherCharges.ioAmount, 0) OtherChargesTotal,ih.ihcancelled,
ih.ihcancelledremarks, idCustomPrice CustomPrice, ihinvoiceamount, idItemType
from
losinvoiceheader ih
left outer join
(select
ihproformaid , ihinvoiceid,ihshopid,ihinvoiceno,ihinvoicedate
from
losinvoiceheader dh
where  dh.ihcancelled=0) dh
on ih.ihProformaID=dh.ihInvoiceID and ih.ihShopID=dh.ihShopID
Left Outer Join
(select
ioShopID, ioInvoiceID, sum(ioAmount) ioAmount
from
losInvoiceOC
group by
ioShopID,ioInvoiceId) OtherCharges
On ih.ihShopId = OtherCharges.ioShopId
and ih.ihInvoiceId = OtherCharges.ioInvoiceId,
losinvoicedetail, aKitItemMaster k, apackingtype p,aunit u,
acustomermaster ac, acurrencymaster c
where
ih.ihshopid= idshopid and ih.ihinvoiceid=idinvoiceid and
k.PackingTypeID=p.packingtypeid and idKitID=k.KitID and
u.unitid=k.UnitID  and ac.customerid = ihcustomerid and ac.currencyid=c.currencyid and
ihtype=''P''
and idItemType=''K'' -- To fetch ONLY Kit Item
GROUP BY
ih.ihshopid,ih.ihinvoiceid,ih.ihinvoiceno,ih.ihinvoicedate,ih.ihduedate,
k.KitID,k.KitCode,k.KitName,idKitQuantity,
Symbol,ihexchangerate,ihdepexrate,idKitActualPrice,packingtypecode,u.unitid,
ih.ihReferenceNo,idKitActualPrice,ihRecAddUser,ihRecModifyUser,UnitCode,customername,Address1,Address2, Address3,
k.PackingTypeID,ihremarks, unitname,dh.ihinvoiceid,dh.ihinvoiceno,dh.ihinvoicedate,ihcancelled,ihcancelledremarks,
OtherCharges.ioAmount,PackingTypeName, idCustomPrice, ihinvoiceamount, idItemType'
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking2]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking2]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwPurchaseOrderTracking2] as
select vw.pohpoid,
case when vw.porequestid is not null then vw.porequestid else a.pohrequestid end as pohrequestid,
case when vw.pohshopid is not null then vw.pohshopid else a.pohshopid end as pohshopid,
vw.ShopRequetNO,
a.pohpono as HQRequestNo,vw.QuotationNO,vw.PrePurchaseNo from vwpurchaseordertracking1 vw left outer join loPurchaseOrderHeader a on
vw.pohquotationid=a.pohpoid or vw.porequestid=a.pohpoid or vw.pohprepurchaseid=a.pohpoid'
GO
/****** Object:  View [dbo].[vwserbookingpartsblocked]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserbookingpartsblocked]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwserbookingpartsblocked] as
-- CREATED for giving the parts replaced in one booking
-- to show in service booking slip report
--------------------------------------------------------------------
--Modified on                   : 20/08/2003,2 3/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
--Adding new table LosServiceInvHeader and modfied the fields
----------------------------------------------------------------
select  serbookhcompanyid, serbookhid, sercallbkhno serbookno, sercallbkhdate serbookdate, repbkdserpartsid blockitemid,
repbkdqty blockqty, serbookhshopid blockshopid,serbookhInspectionNo,serbookhInspectionDate,
serinvhprocno,serinvhprocdate from
losbookpartsreplacedetails pd, losservicebookingheader bh
left outer join loscallbookingheader ls on bh.serbookhRefId=ls.sercallbkhid
left outer join losserviceheader on bh.serbookhid=serinvhbookingid
and serbookhshopid=serinvhshopid and serbookhcompanyid=serinvhcompanyid where
pd.repbkdshopid =  bh.serbookhshopid and pd.repbkdserbookid = bh.serbookhid
and serbookhstatus=''c'' and serbookhinpcancelled=0 and serbookhid not in
(Select isnull(serinvhbookingid,0) from losserviceheader where serinvhshopid=serbookhshopid)
union all
select sh.serinvhcompanyid, serbookhid, sercallbkhno, sercallbkhdate, repinvdpartsid,
repinvdqty blockqty, sh.serinvhshopid  blockshopid,serbookhInspectionNo,serbookhInspectionDate,
serinvhprocno,serinvhprocdate from losinvpartsreplacedetails pd,
LosServiceInvHeader sh  inner join losserviceheader  los on
los.serinvhid=sh.serinvhjobcardid and los.serinvhcompanyid=sh.serinvhcompanyid and
los.serinvhshopid=sh.serinvhshopid , losservicebookingheader bh
left outer join loscallbookingheader ls on bh.serbookhRefId=ls.sercallbkhid
where
pd.repinvdshopid =  sh.serinvhshopid and pd.repinvinvoiceid = sh.serinvhid
and pd.repinvcompanyid = sh.serinvhcompanyid and serbookhcompanyid=sh.serinvhcompanyid
and serbookhid =  serinvhbookingid and serbookhshopid = sh.serinvhshopid'
GO
/****** Object:  View [dbo].[vwShipmentExpences]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentExpences]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by  : Shinu
-- Created on  : 03/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get the Shipment Expences
-----------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShipmentExpences] AS
select pohCompanyID,pohDepartmentID,pohPOID,POHVendorID,pohpoDate,PohpoNo,phPaymentNo,pbhBillNo,VendorName,AccountDesc,pddAmount from loPurchaseOrderHeader
INNER JOIN (select pddHqPoID,phPaymentNo,AccountDesc,pddAmount FROM ahqpaymentvoucherdebitdetails
INNER JOIN ahqpaymentvoucherHeader ON phPaymentID=pddPaymentID And phCancelled=0
INNER JOIN aAccountMaster ON AccountID=pddAccountID
where pddHqPoID is not Null
)Det on Det.pddHqPoID=PohpoID
INNER JOIN aVendorMaster ON vendorID=pohVendorID
Left Outer JOIN LOspPurchaseBillHeader ON pbhPOID=pohPOID'
GO
/****** Object:  View [dbo].[vwShipmentwiseitem]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentwiseitem]'))
EXEC dbo.sp_executesql @statement = N'
---Created By               : Prasanth joseph
---Created On               : 27-12-2007
---Created For              : To get Purchase bill wise item
---Modified By              : Nidheesh P V
---Modified By              : 12-08-2010
---comments     : Added Item Quantity also
CREATE view [dbo].[vwShipmentwiseitem] as
select pbhBilliD,pbhBillDate,pbhVendorID,pbhDepartmentID,pbdItemID,pbdPOQuantity,convert(numeric(18,2),(pbdPOQuantity*Quantity))Qty from
LOspPurchaseBillHeader inner join LOspPurchaseBillDetail d
on pbhBillID=pbdBillID
inner join aitem a on a.itemid=pbdItemID
inner join aPackingTypeCapacityDetail p  on pbdPackingTypeID=PackingTypeID and a.unitsid=p.UnitsID
where  pbhCancelled=0'
GO
/****** Object:  View [dbo].[vwserialnoAudit]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwserialnoAudit]'))
EXEC dbo.sp_executesql @statement = N'
--Created on  :30/08/2010
--Created by   : jyothish
create view [dbo].[vwserialnoAudit]
as
SELECT poshShopID,poshBillID,poshBillNo,poshBillDate,''POS'' Type,isnull(poshcustomerid,0)CutomerID ,
poshCustomerName  CustomerName,
CASE WHEN poshcustomerid IS not NULL THEN Address1+''''+Address2+''''+Address3 else poshCustomerName end  Address,
CASE WHEN poshcustomerid IS not NULL THEN PhoneNo else poshCustomerName end  PhoneNo ,posdItemID,sidSerialNo
FROM losposheader ph LEFT OUTER JOIN acustomermaster c ON ph.poshcustomerid=c.CustomerId
INNER JOIN  losposdetail pt ON  ph.poshShopID=pt.posdShopID  and ph.poshBillID=pt.posdBillID
INNER JOIN  (select * from  losserialissuedetails  where sidInterfaceID=1502)vw on vw.sidShopID=ph.poshShopID
and vw.sidTransactionID=ph.poshBillID and vw.sidItemID=pt.posdItemID
lEFT OUTER JOIN (select sehBillID,sehShopID,sadSerialNo from losposexchangeheader lx ,losserialArrivalDetails lr  where
	lx.sehBillID is not null and lx.sehCancelled=0 and lx.sehShopID=lr.sadShopID
	and sadInterfaceID=1518 and lx.sehExchangeID=lr.sadTransactionID)vwex on vwex.sehBillID=poshBillID and poshShopID=sehShopID
and sadSerialNo=sidSerialNo where sadSerialNo is null  and poshCancelled=0
union all
SELECT   ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,''Credit Invoice'' Type,ihCustomerID,
CustomerName,Address1+''''+Address2+''''+Address3 Address,PhoneNo ,idItemID,sidSerialNo
FROM losinvoiceheader lh LEFT OUTER JOIN acustomermaster c ON lh.ihCustomerID=c.CustomerId
INNER JOIN  losinvoiceDetail lt on lt.idShopID =lh.ihShopID and lt.idInvoiceID=lh.ihInvoiceID
INNER JOIN  (select * from  losserialissuedetails  where sidInterfaceID=1504)vw on vw.sidShopID= lh.ihShopID
and  vw.sidTransactionID=lh.ihInvoiceID and lt.idItemID=vw.sidItemID
LEFT OUTER JOIN (select GrnhInvoiceID,grnhShopid,sadSerialNo from losgoodsreturnnoteheader lx ,losserialArrivalDetails lr  where
	lx.GrnhInvoiceID is not null and lx.GrnhCancel=0 and lx.grnhShopid=lr.sadShopID
	and sadInterfaceID=1512 and lx.GrnhGoodsreturnnoteID=lr.sadTransactionID)vwex on vwex.GrnhInvoiceID=ihInvoiceID and ihShopID=grnhShopid
and  sadSerialNo=sidSerialNo  where sadSerialNo is null and ihCancelled=0'
GO
/****** Object:  View [dbo].[vwShipmentRelatedExpenses]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShipmentRelatedExpenses]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By   : Hariharan R
-- Created Date : 25/01/2004
CREATE VIEW [dbo].[vwShipmentRelatedExpenses] AS
--
select pohPOId, pohPONo, AccountDesc, phLCPayment , pddDescription,
pddAmount, (pddAmount * phExchangeRate) CompanyAmount,
loPurchaseOrderHeader.pohPoDate, pohVendorId VendorId, VendorName,
pbhBillNo BillNo, pbhBillDate BillDate, chCostingNo CostingNo,
chCostingDate CostingDate, pddDescription Remarks, chdepartmentid departmentid,
PBHBILLAMOUNT, pbhExchangeRate, pbhlcamount
from aHqPaymentVoucherHeader, aHqPaymentVoucherDebitDetails,
aAccountMaster, (loPurchaseOrderHeader left outer join lospPurchaseBillHeader
on loPurchaseOrderHeader.pohPoId = lospPurchaseBillHeader.pbhPoId
and lospPurchaseBillHeader.pbhCancelled = 0)
left outer join loaCostingHeader
on lospPurchaseBillHeader.pbhBillId = loaCostingHeader.chBillId
and loaCostingHeader.chCancelled = 0,
aVendorMaster
where pohPOID = pddHQPOID
and pohCompanyID = pddCompanyid
and phPaymentID = pddPaymentID
and phCompanyId = pddCompanyID
and pddAccountID = Accountid
and pohVendorId = aVendorMaster.VendorId
and phCancelled = 0
and phLCPayment in (''CDP'', ''SOC'', ''j'', ''SCP'', ''SCDP'')'
GO
/****** Object:  View [dbo].[vwshipmentexpensespaidorprojected]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentexpensespaidorprojected]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentexpensespaidorprojected    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshipmentexpensespaidorprojected] as
select phpaymentno, phpaymentdate, pohpono, pohpodate,pbhbillno, pbhbilldate,chcostingno,
chcostingdate, accountdesc, pdddescription,  pddamount, phamount,
phcustomeramount, phlcpayment, case phlcpayment when ''SOC'' then ''Shipment Other Charges'' when
''LCO'' then ''LC Outstanding'' when ''LCM'' THEN ''LC Margin Payment'' When ''J'' then
''Projected Expenses'' when ''CDP'' then ''Custom Duty'' end type,
case phlcpayment when ''SOC'' then 3 when ''LCO'' then 5
when ''LCM'' THEN 1 When ''J'' then 4 when ''CDP''
then 2 end typeorder, pbhbillamount, pbhexchangerate, phexchangerate, pohvendorid, c.currencyname, c.symbol,
phdepexrate, pbhdepexrate
from ahqpaymentvoucherheader h, ahqpaymentvoucherdebitdetails d,
aaccountmaster a, lopurchaseorderheader, losppurchasebillheader, loacostingheader,
acurrencymaster c, avendormaster v where h.phpaymentid = d.pddpaymentid and h.phcompanyid = d.pddcompanyid and
d.pddaccountid = a.accountid and pddhqpoid=pohpoid and pohpoid = pbhpoid and
pohcompanyid = pbhcompanyid and pbhbillid=chbillid and pohvendorid = v.vendorid
and v.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwPopulateGodownArrivals]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPopulateGodownArrivals]'))
EXEC dbo.sp_executesql @statement = N'
/*
CREATED BY : SHINE DAS
CREATED ON : 11.05.2012
Purpose	   : To populate godown arrival details in Cancel posting.
*/
CREATE VIEW [dbo].[vwPopulateGodownArrivals] AS
select ah.ahArrivalID ArrivalID, ahArrivalNo ArrivalNo, ahArrivalDate ArrivalDate,
cast(cast(sum(si.adDespatchedQty) as decimal(18,2)) as varchar(20)) DespatchedQty,
cast(cast(sum(si.adReceivedQty) as decimal(18,2)) as varchar(20)) ReceivedQty,
ahdepartmentid departmentid,ahLocalGodownId GodownId
from loiArrivalHeader AH, loiarrivaldetail si where
ahCancelled = 0 and ahposted=1 and  ah.ahlocalGodownId=si.adGodownId
and ah.aharrivalid=si.adarrivalid
group by ahArrivalID,ahArrivalNo,ahArrivalDate,ahdepartmentid,ahlocalGodownId
union all
select ah.ahArrivalID ArrivalID, ahArrivalNo ArrivalNo, ahArrivalDate ArrivalDate,
cast(cast(sum(si.asdDespatchedGoodQty) as decimal(18,2)) as varchar(20)) DespatchedQty,
cast(cast(sum(si.asdReceivedGoodQty) as decimal(18,2)) as varchar(20)) ReceivedQty,
ahdepartmentid departmentid, ahLocalGodownId GodownId
from loiArrivalHeader AH, loiarrivalshipmentdetail si where
ahCancelled = 0 and ahposted=1 and ah.ahlocalGodownId=si.asdGodownID
and ah.aharrivalid=si.asdArrivalID
group by ahArrivalID,ahArrivalNo,ahArrivalDate,ahdepartmentid,ahlocalGodownId'
GO
/****** Object:  View [dbo].[vwPendingDeliveries]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPendingDeliveries]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view lists all pending deliveries
-- Coded By: Regin T.
-- Coded On: 03-06-2010
--------------------------------------------------------------------------------
--Modified By : Nidheesh P V
--Modified on : 16/02/2011
--Commentes : Added ''cash customer'' in Deliveru note requiremnet also.
--So commented the checking of  p.poshCustomerId is not null in ''BILL'' type
--------------------------------------------------------------------------------
CREATE view [dbo].[vwPendingDeliveries] as
-- Credit Invoice
SELECT DISTINCT ihShopID ShopId, ihInvoiceID TransId, ihInvoiceNo TransNo, CustomerId,
CASE WHEN dd.CustomerName is not null THEN dd.CustomerName
else c.CustomerName end CustomerName, ''INV'' TransType
, cast(left(dd.DeliveryDate,12)+right(dd.DeliveryTime,7) as datetime) DeliveryDateTime
, dd.DeliveryRemarks, i.ihsalespersonid SalesPersonId, sp.Spername SalesPersonName,
NULL CounterId, NULL CounterName
-- Logic to find the time elapsed since the invoice is raised
-- 1. Combine Invoice Date and Invoice Time
-- 2. Find the no. of minutes between the invoice time and the current server time.
-- 3. Divide the result from step 2 by 60.0 to get the time in term of hours.
-- 4. Trim out the fractional part from the result of step 3 by casting to int.
-- 5. Append "Hrs" to the result of step 4.
-- 6. Perform modulo 60 operation on the result of step 2 to fetch the minutes.
-- 7. Add leading zero to no. of minutes. e.g. 03
-- 8. Append "Mts" to the result of step 7.
-- 9. Combine elapsed hours (result of step 5) and minutes (result of 8).
, cast(cast(datediff(n,left(i.ihInvoiceDate,12)+right(i.ihInvoiceTime,7)
,current_timestamp)/60.0 as int) as nvarchar(20))+'' Hrs : ''
+ right(''00''+cast(datediff(n,left(i.ihInvoiceDate,12)+right(i.ihInvoiceTime,7)
,current_timestamp) % 60 as nvarchar(10)),2)+'' Mts'' ElapsedTime
FROM losInvoiceHeader i
left outer join aCustomerMaster c on i.ihCustomerID=c.CustomerID
left outer join aSalesPersonMaster sp on i.ihsalespersonid=sp.Sperid
left outer join losDeliveryDetails dd on i.ihShopId=dd.ShopId and i.ihInvoiceId=dd.CreditInvoiceId
left outer join
(select dndShopId, DnDinvoiceId from losdeliverynotedetail d
inner join losdeliverynoteheader h on d.dndDnId=h.dnDnId and d.dndShopid=h.dnShopid
where isnull(h.dncancelled,0)=0) dn on i.ihShopID=dn.DnDShopid and i.ihInvoiceId=dn.DnDinvoiceId
WHERE IsNull(i.ihCancelled, 0) = 0 and IsNull(i.ihDeliveryNeeded, 0) = 1
and ihType = ''I'' and dn.dndShopId is null
union all
-- Purchase Order
SELECT DISTINCT ihShopID, ihInvoiceID, ihInvoiceNo, CustomerID,
CASE WHEN dd.CustomerName is not null THEN dd.CustomerName
ELSE c.CustomerName end CustomerName, ''PO'' TransType
, cast(left(dd.DeliveryDate,12)+right(dd.DeliveryTime,7) as datetime)
, dd.DeliveryRemarks, i.ihsalespersonid SalesPersonId, sp.Spername SalesPersonName,
NULL CounterId, NULL CounterName
, cast(cast(datediff(n,left(i.ihInvoiceDate,12)+right(i.ihInvoiceTime,7)
,current_timestamp)/60.0 as int) as nvarchar(20))+'' Hrs : ''
+ right(''00''+cast(datediff(n,left(i.ihInvoiceDate,12)+right(i.ihInvoiceTime,7)
,current_timestamp) % 60 as nvarchar(10)),2)+'' Mts'' ElapsedTime
FROM losInvoiceHeader i
left outer join aCustomerMaster c on i.ihCustomerID=c.CustomerID
left outer join aSalesPersonMaster sp on i.ihsalespersonid=sp.Sperid
left outer join losDeliveryDetails dd on i.ihShopId=dd.ShopId and i.ihInvoiceId=dd.CreditInvoiceId
left outer join
(select dndShopId, DnDinvoiceId from losdeliverynotedetail d
inner join losdeliverynoteheader h on d.dndDnId=h.dnDnId and d.dndShopid=h.dnShopid
where isnull(h.dncancelled,0)=0) dn on i.ihShopID=dn.DnDShopid and i.ihInvoiceId=dn.DnDinvoiceId
WHERE IsNull(i.ihCancelled, 0) = 0 and IsNull(i.ihDeliveryNeeded, 0) = 1
and ihType = ''P'' and i.ihtransfinished=1 and (dn.dndShopId is null)
union all
-- Cash Sales
SELECT distinct poshShopID, poshBillID, poshBillNo, CustomerID
--, CASE WHEN dd.CustomerName is not null THEN dd.CustomerName
--ELSE c.CustomerName end CustomerName
, coalesce(dd.CustomerName,c.CustomerName,poshCustomerName)[CustomerName]
, ''BILL'' TransType
,cast(left(dd.DeliveryDate,12)+right(dd.DeliveryTime,7) as datetime)
, dd.DeliveryRemarks, p.poshsalespersonid, sp.Spername,
poshCounterId, CounterName
, cast(cast(datediff(n,left(p.poshBillDate,12)+right(p.poshBillTime,7)
,current_timestamp)/60.0 as int) as nvarchar(20))+'' Hrs : ''
+ right(''00''+cast(datediff(n,left(p.poshBillDate,12)+right(p.poshBillTime,7)
,current_timestamp) % 60 as nvarchar(10)),2)+'' Mts''
FROM losPosheader p
left outer join aCustomerMaster c on poshcustomerid=c.CustomerID
left outer join aSalesPersonMaster sp on p.poshsalespersonid=sp.Sperid
left outer join losDeliveryDetails dd on p.poshShopId=dd.ShopId and p.poshBillId=dd.CashInvoiceId
left outer join aCounterMaster cm on p.poshShopId=cm.CounterShopId and p.poshCounterId=cm.CounterId
left outer join
(select dndShopId, dndBillid from losdeliverynotedetail d
inner join losdeliverynoteheader h on d.dndDnId=h.dnDnId and d.dndShopid=h.dnShopid
where isnull(h.dncancelled,0)=0) dn on p.poshShopID=dn.DnDShopid and p.poshBillID=dn.dndBillid
WHERE IsNull(p.poshCancelled, 0) = 0 and IsNull(p.poshDeliveryNeeded, 0) = 1
--and p.poshCustomerId is not null
and dn.dndShopId is null'
GO
/****** Object:  View [dbo].[vwCancelEditUser]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCancelEditUser]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW  [dbo].[vwCancelEditUser] AS
-- =============================================
-- Added by:  Praveen
-- Create date: 10th August 2010
-- Description: Displays Cancel/Edit User
-- =============================================
(select aUser= case
when (
(poshRecModifyUser is null or ltrim(rtrim(poshRecModifyUser))='''') and
(poshRecAddUser is not null and ltrim(rtrim(poshRecAddUser))<>'''')
)
then isnull(poshRecAddUser,'''')+'' - ''+isnull(cast(updatetime as char),'''')
when (
(poshRecModifyUser is not null and ltrim(rtrim(poshRecModifyUser))<>'''')
)
then isnull(poshRecModifyUser,'''')+'' - ''+isnull(cast(updatetime as char),'''')
end,
poshShopID,poshbillid from LosPosFAndBHeader)'
GO
/****** Object:  View [dbo].[vwDebitNote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitNote]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 		: 28/12/02
-- Modified by 		: dheena
-- Comments 		: add depid
-----------------------------------------------------------
-- Modified on          : 30/08/2003
-- Modified by          : Kishore
-- Comments             : Added UpdateTime column
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-----------------------------------------------------------
CREATE VIEW [dbo].[vwDebitNote] AS
select dcncompanyid, dcnid, dcndate, dcnrefno, dcnreferenceno,
case when dcncustomerid is not null then cus.customername
else ven.vendorname end Debitto, dcnamount, dcncancelled, dcncancelledremarks, dcndetails,
dcndepartmentid,DepartmentName, dcn.UpdateTime
from debitcreditnote dcn
left outer join acustomermaster cus on
dcn.dcncompanyid = cus.companyid
and dcn.dcncustomerid = cus.customerid
left outer join avendormaster ven on
dcn.dcncompanyid = ven.companyid
and dcn.dcnvendorid = ven.vendorid,adepartmentmaster d
where  dcndebit = 1
and dcn.dcncompanyid = d.CompanyID
and d.DepartmentId = dcndepartmentid'
GO
/****** Object:  View [dbo].[vwDebitCreditNote]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitCreditNote]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 29/03/2003
--Modified by		: Santhosh M
--Comments		: v3
--Added cancelled
CREATE view [dbo].[vwDebitCreditNote]
as
select
	dn.dcnno, dn.dcnCusVenRefNo, dn.DCNcompanyid,dn.dcnid,dn.dcnrefno,dn.dcndate,dn.dcndebit,
	dn.DCNVendorId,vm.vendorname,vm.Address1 as vaddr1,vm.Address2 as vaddr2,vm.Address3 as vaddr3,
	av.CityName as vCity,dn.DCNCustomerId,cm.customername,cm.Address1 as caddr1,cm.Address2 as caddr2,
	cm.Address3 as  caddr3,ac.CityName as cCity,vCur.Symbol as VendorCur,cCur.Symbol as CustCur,
	dn.DCNAmount,dn.DCNDetails, dn.dcnexchangerate, dn.dcndepexrate,dn.dcndepartmentid,dn.dcncancelled
from
	debitcreditnote dn
	left outer join acustomermaster cm on dn.dcncustomerid= cm.customerid and dn.dcncompanyid = cm.companyid
	left outer join avendormaster vm on dn.dcnvendorid=vm.vendorid and dn.dcncompanyid = vm.companyid
	left outer join acurrencymaster Vcur on vm.CurrencyID=Vcur.CurrencyID and vm.companyid = vcur.companyid
	left outer join acurrencymaster cCur on cm.CurrencyID=ccur.CurrencyID and cm.companyid = ccur.companyid
	left outer join acity ac on vm.cityid = ac.cityid
	left outer join acity av on cm.cityid = av.cityid'
GO
/****** Object:  View [dbo].[vwDebitCreditCheckList]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitCreditCheckList]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 		: 28/12/02
-- Modified by 		: dheena
-- Comments 		: add departmentid
---------------------------------------------------------------------------
-- Modified on		: 29/08/2003
-- Modified by          : Kishore
-- Added                : UpdateTime
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
---------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDebitCreditCheckList] AS
select DCNCompanyID, dcnid, dcnno, dcndate, dcnreferenceno,
case when (dcnvendorid is not null) then ''Vendor''
when (dcncustomerid is not null) then ''Customer'' end
as caption, case when (dcnvendorid is not null) then vm.vendorname
when (dcncustomerid is not null) then cm.customername
end as custorven,acc.accountdesc , dcnamount, dcndetails,
dm.departmentname, dcndebit, dcncancelled, dcnposted,
dcnexchangerate, dcnrefno , dcncusvenrefno,dcn.dcndepartmentid, dcn.UpdateTime
from debitcreditnote dcn left outer join  avendormaster vm
on dcn.dcncompanyid = vm.companyid and dcn.dcnvendorid = vm.vendorid
left outer join  acustomermaster cm
on dcn.dcncompanyid = cm.companyid and dcn.dcncustomerid = cm.customerid,
aaccountmaster acc , adepartmentmaster dm
where dcn.dcncompanyid = acc.companyid and dcn.dcnotheraccid = acc.accountid
and dcn.dcncompanyid = dm.companyid and dcn.dcndepartmentid = dm.departmentid'
GO
/****** Object:  View [dbo].[vwdcnwithcontrolaccdep]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdcnwithcontrolaccdep]'))
EXEC dbo.sp_executesql @statement = N'
--created by   : Hariharan
--Created Date : 31/10/2002
--for referenceno population in debitcreditnote
--Modified  by : Venkitesh
--Created Date : 01/07/2004
CREATE  view [dbo].[vwdcnwithcontrolaccdep] as
select distinct dcnno, dcnid, dcndate, dcnremarks, dcnotheraccid, dcndebit,
dcnexchangerate, dcnamount, ca.maindepid, dcncompanyid, DCNCustomerID,
DCNVendorId, departmentname, dcndepexrate, dcnexchangerates ,acc.accountdesc from
debitcreditnote dc, adepcontrolaccounts ca , adepartmentmaster d,aaccountmaster acc
where acc.accountid=ca.controlaccid and acc.companyid=ca.CompanyID and
ca.companyid = dcncompanyid and ca.controlaccid = dc.DCNOtherAccId and dcncancelled =0
and childdcnid is null and parentdcnid is null and parentreceiptid is null
and parentpaymentid is null
and dc.dcndepartmentid = d.departmentid'
GO
/****** Object:  View [dbo].[vwitemdescpurchseorder]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemdescpurchseorder]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwitemdescpurchseorder] as
select * from vwitemdesc where type=1 and poditemid not in (select poditemid from  vwitemdesc where type=0)
union
select * from vwitemdesc where type=0'
GO
/****** Object:  View [dbo].[vwsuppreplacements]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsuppreplacements]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwsuppreplacements    Script Date: 06/03/2003 09:13:13 ******/
/****** Object:  View dbo.vwsuppreplacements    Script Date: 26/01/2003 18:14:35 ******/
--Modified By 	: Hariahran
--Modified Date : 27/09/2002
--------------------------------------------------------------------
--Modified on                   : 20/08/2003
--Modified by                   : Reji Abraham
--Comments                     : Additional table loscallbookingheader is added  and modified fields, previous fields are alias names
----------------------------------------------------------------
CREATE view [dbo].[vwsuppreplacements] as
select serbookhcompanyid,reprechno,reprechdate, sercallbkhno serbookhno, sercallbkhdate serbookhdate,serbookhshopid,
sercallbkhslno serbookhslno, bk.serbookhdeldate, sercallbkhpurchdate serbookhpurchdate, sercallbkpartcode serbookpartcode,
v.itemdescription, rqd.repreqqty reqqty, isnull(rd.reprecqty,0) recvdqty, repreqdtagno,
repreqhreceived, sercallbkhcategid serbookhcategid, v.code from losservicebookingheader bk inner join loscallbookingheader los on
los.serCallBkhid=serbookhrefid and los.serCallBkhcompanyid=bk.serbookhcompanyid and
bk.serbookhshopid=los.serCallBkhshopid,
losreplacerequestheader rqh left outer join losreplacereceiveheader rh
on rqh.repreqhid = rh.reprechid and rqh.repreqhcompanyid = rh.reprechcompanyid
and rqh.repreqshopid = rh.reprechshopid and rqh.repreqhcancelled=1
left outer join losreplacerequestdetails rqd on rqh.repreqhid= rqd.repreqdid
and rqh.repreqshopid= rqd.repreqdshopid and rqh.repreqhcompanyid = rqd.repreqdcompanyid
left outer join losreplacereceivedetails rd on  rh.reprechid = rd.reprecdid and
rh.reprechcompanyid = rd.reprecdcompanyid and rh.reprechshopid = rd.reprecdshopid
and rh.reprechcancelled = 1 and rqd.repreqditemid = rd.reprecditemid ,
vwitemdescription v where serbookhid = repreqdbookid and
serbookhshopid = repreqdshopid and serbookhcompanyid=repreqdcompanyid and
repreqditemid = v.itemid'
GO
/****** Object:  View [dbo].[vwdatewisearrivalHQ]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdatewisearrivalHQ]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 18/01/2003 9:45:35 PM ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 14/09/2002 12:48:06 AM ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 20/11/2001 9:58:59 AM ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 17/11/2001 9:21:28 PM ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 16/06/2001 15:36:31 ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 09/03/2001 02:32:26 ******/
/****** Object:  View dbo.vwdatewisearrivalHQ    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwdatewisearrivalHQ] as
select aditemid,adgodownid,aharrivaldate,sum(adreceivedqty) as incomingqty from loiarrivalheader,loiarrivaldetail
where adgodownid=ahlocalgodownid and adarrivalid=aharrivalid and ahCancelled=0
group by adgodownid,aharrivaldate,aditemid'
GO
/****** Object:  View [dbo].[vwtoolsreturn]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtoolsreturn]'))
EXEC dbo.sp_executesql @statement = N'
--comments: created for Tools return Transaction report
--done: venki 040803
CREATE view [dbo].[vwtoolsreturn] as
select s.shopid,s.shopname,h.tlrethid,h.tlrethno,ah.alchno,h.tlrethdate,d.tlretdtoolsid,f.assetname,ah.alchtechnicianid,p.spername,d.tlretdcomments from LosserToolsReturnheader h,ashops s,
LosserToolsallocationheader Ah,
LosserToolsReturnDetail d left outer join fixedasset f on FixedAssetID=tlretdtoolsid,
asalespersonmaster p where h.tlrethid=d.tlretdid and h.tlrethShopid=d.tlretdShopid
and h.tlrethCompanyId=d.tlretdCompanyId and s.shopid=h.tlrethShopid and h.tlrethcancelled=0
and ah.alchcompanyid=h.tlrethCompanyId and ah.alchshopid=h.tlrethShopid
and ah.alchid=tlrethallocid and ah.alchtechnicianid=p.sperid'
GO
/****** Object:  StoredProcedure [dbo].[SpServiceAlerts]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpServiceAlerts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  by dheena
--Created  date 10-12-2003
--purpose service alerts
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
CREATE proc [dbo].[SpServiceAlerts] @intcompanyid as int,
@intshopid as int,@strfromdate as varchar(10),@strTodate as varchar(10) as
set nocount on
begin
declare
@intcount as int,
@dtpConFromDate as datetime,
@dtpConToDate as datetime,
@intAlerdays as int,
@BitAlertype as int,
@dtplastServiceDate as datetime,
@intcustomerid as int,
@inttotDateno as int,
@intserviceperiod as int,
@intservicecount as int,
@dtpPAckageDate as datetime,
@intcounter as int,
@dtpTodate as datetime ,
@dtpFromdate as datetime ,
@dtpServicePerioddate as datetime
CREATE table #temp2 (
intmchID int,
intshopid int,
intcompanyid  int,
intcustomerid int,
serviceid  int,
intalertday  int,
inttype int,
dtpFromdate datetime,
dtpTodate datetime,
intserviceperiod int,
intcounter  int identity (1,1) not null,
SerPerioddate datetime,
SerPeriodType  varchar(4))
CREATE table #temp3(
intConid  int,
intconcompanyid int,
intconshopid int,
intconCustid int,
intconservid int,
intalertday int,	
dtpconServiceDate datetime)
CREATE table #temp5(
intConid  int,
intconcompanyid int,
intconshopid int,
intconCustid int,
intconservid int,	
intalertday int,
dtpconServiceDate datetime,
intcounter  int identity (1,1) not null)
CREATE table #temp4 (
tempshopid int,
tempcompanyid int,
tempserivedate datetime,
tempcustomerid int,
tempcounter  int identity (1,1) not null)
	
if @strfromdate <> '''' and @strTodate <>''''
Begin 		
	set @dtpConFromDate=convert(datetime,@strfromdate,101)
	set @dtpConToDate=convert(datetime,@strTodate,101)
	
insert into #temp2 (intmchID,intshopid,intcompanyid ,
intcustomerid ,serviceid ,intalertday ,
inttype ,dtpFromdate ,dtpTodate ,intserviceperiod,SerPeriodType,SerPerioddate)
select
	distinct mchID,mchShopID,mchCompanyID, mchCustomerID,
	msdServiceID,msdAlertdays,cast(isnull(msdAlerttype,0) as int),
	max(mcdFromDate) fromdate ,max(mcdToDate) todate ,msdSerPeriod,
	msdSerPeriodType,
	case
		when msdSerPeriodType=''D'' then dateadd(D,isnull(msdAlertdays,0),isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType=''M'' then dateadd(M,isnull(msdAlertdays,0),isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType=''Y'' then dateadd(yyyy,isnull(msdAlertdays,0),isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType is null then dateadd(D,isnull(msdAlertdays,0),isnull(lastservicedate,PAckageDate)) else
		'''' end lastservicedate
	from 	losSerMaintenanceContractHeader ,losSerMaintenanceContractDetail
		left outer join (
		select
			max(serinvhprocdate) lastservicedate,serinvhshopid,serCallBkhcustomerid,
			serCallBkhcompanyid
		from
			losCallBookingHeader,losserviceheader,losSerMaintenanceContractHeader
		where
			serCallBkhshopid=serinvhshopid and serCallBkhcompanyid=
			serinvhcompanyid and serCallBkhcancelled=0 and
			serinvhjobinvcancelled=0 and serCallBkhid=serinvhbookingid
			and serinvhshopid=mchShopID and serCallBkhcompanyid=mchCompanyID
			and serCallBkhcustomerid=mchCustomerID
		group by serinvhshopid,serCallBkhcustomerid,serCallBkhcompanyid) ase on
		ase.serinvhshopid=mcdShopID and serCallBkhcompanyid=mcdCompanyID
		and (mcdFromDate>=lastservicedate and mcdToDate<=lastservicedate) ,
		losSerMaintenanceServiceDetail,apackagesettings
		where  mchCompanyID=msdCompanyID  and mchCancelled=0
		and mchID =msdMCID and mchShopID=msdShopID and mchShopID=mcdShopID
		and mchID =mcdID and mchCompanyID=mcdCompanyID and mchCompanyID=companyid and	
	        mchShopID=@intshopid and mchCompanyID=@intcompanyid and
		(mcdFromDate>=@dtpConFromDate and mcdToDate<=@dtpConToDate)
		
	group by
		mchCustomerID,msdServiceID,msdAlertdays,cast(isnull(msdAlerttype,0) as int)
		,msdSerPeriod,mchShopID,mchCompanyID,mchID,msdSerPeriod,msdSerPeriodType,
		lastservicedate,PAckageDate	
end
else
begin	
select @dtpPAckageDate=PAckageDate from apackagesettings
	where companyid=@intcompanyid		
	insert into #temp2 (intmchID,intshopid,intcompanyid ,
	intcustomerid ,serviceid ,intalertday ,
inttype ,dtpFromdate ,dtpTodate ,intserviceperiod,SerPeriodType,SerPerioddate)
select
	distinct mchID,mchShopID,mchCompanyID, mchCustomerID,
	msdServiceID,msdAlertdays,cast(isnull(msdAlerttype,0) as int),
	max(mcdFromDate) fromdate ,max(mcdToDate) todate ,msdSerPeriod,
	msdSerPeriodType,
	case
		when msdSerPeriodType=''D'' then dateadd(D,msdSerPeriod,isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType=''M'' then dateadd(M,msdSerPeriod,isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType=''Y'' then dateadd(yyyy,msdSerPeriod,isnull(lastservicedate,PAckageDate))
		when msdSerPeriodType is null then dateadd(D,msdSerPeriod,isnull(lastservicedate,PAckageDate)) else
		'''' end lastservicedate
from 	losSerMaintenanceContractHeader ,losSerMaintenanceContractDetail
	left outer join (
	select
		max(serinvhprocdate) lastservicedate,serinvhshopid,serCallBkhcustomerid,
		serCallBkhcompanyid
	from
		losCallBookingHeader,losserviceheader,losSerMaintenanceContractHeader
	where
		serCallBkhshopid=serinvhshopid and serCallBkhcompanyid=
		serinvhcompanyid and serCallBkhcancelled=0 and
		serinvhjobinvcancelled=0 and serCallBkhid=serinvhbookingid
		and serinvhshopid=mchShopID and serCallBkhcompanyid=mchCompanyID
		and serCallBkhcustomerid=mchCustomerID
	group by serinvhshopid,serCallBkhcustomerid,serCallBkhcompanyid) ase on
	ase.serinvhshopid=mcdShopID and serCallBkhcompanyid=mcdCompanyID
	and (mcdFromDate>=lastservicedate and mcdToDate<=lastservicedate) ,
	losSerMaintenanceServiceDetail,apackagesettings
where  mchCompanyID=msdCompanyID and mchCancelled=0
	and mchID =msdMCID and mchShopID=msdShopID and mchShopID=mcdShopID
	and mchID =mcdID and mchCompanyID=mcdCompanyID and mchCompanyID=companyid and	
mchShopID=@intshopid and mchCompanyID=@intcompanyid  and mcdToDate>=PAckageDate
group by
	mchCustomerID,msdServiceID,msdAlertdays,cast(isnull(msdAlerttype,0) as int)
	,msdSerPeriod,mchShopID,mchCompanyID,mchID,msdSerPeriod,lastservicedate,
	PAckageDate,msdSerPeriodType
end 	
select @intcount=min(intcounter) from #temp2								
while @intcount>0
	Begin 		
		select @intcustomerid=intcustomerid,@BitAlertype=inttype,@dtpTodate=dtpTodate
		,@dtpServicePerioddate=SerPerioddate,@dtpFromdate=dtpFromdate
		 from #temp2 where intcounter=@intcount
		delete from  #temp4
		delete from #temp5
		insert into #temp4 (tempshopid ,tempcompanyid ,tempserivedate,tempcustomerid)
		select serinvhshopid,serCallBkhcompanyid,serinvhprocdate,serCallBkhcustomerid	
		from
			losCallBookingHeader,losserviceheader
		where
			serCallBkhshopid=serinvhshopid and serCallBkhcompanyid=
			serinvhcompanyid and serCallBkhcancelled=0 and
			serinvhjobinvcancelled=0 and serCallBkhid=serinvhbookingid
			and serCallBkhcustomerid=@intcustomerid and serinvhshopid=@intshopid	
		group by serinvhshopid,serCallBkhcustomerid,serCallBkhcompanyid,serinvhprocdate
		order by serCallBkhcustomerid,serinvhprocdate	
		
		select @intservicecount=count(*) 		
		from
			losCallBookingHeader,losserviceheader
		where
			serCallBkhshopid=serinvhshopid and serCallBkhcompanyid=
			serinvhcompanyid and serCallBkhcancelled=0 and
			serinvhjobinvcancelled=0 and serCallBkhid=serinvhbookingid
			and serCallBkhcustomerid=@intcustomerid and serCallBkhshopid=@intshopid
		group by serinvhshopid,serCallBkhcustomerid,serCallBkhcompanyid,serinvhprocdate
		order by serCallBkhcustomerid,serinvhprocdate		
		
		 if @BitAlertype=1
		      begin 						
			insert into #temp3	
			select intmchid,intcompanyid,intshopid,intcustomerid,serviceid,intalertday,
			SerPerioddate
			from #temp2 where intcounter=@intcount and SerPerioddate<=dtpTodate
		  end 	         	
		else
		   begin											
			--set @dtplastServiceDate=@dtpServicePerioddate	
			set @dtplastServiceDate=@dtpFromdate
			while @dtplastServiceDate <=@dtptodate
			begin 	
				insert into #temp5 (intConid,intconcompanyid ,intconshopid ,
				intconCustid ,intconservid ,intalertday,dtpconServiceDate)					
				select intmchid,intcompanyid,intshopid,intcustomerid,serviceid,intalertday,
				 case isnull(SerPeriodType,'''')
				when ''D'' then 						
				dateadd(D,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when ''M'' then
				dateadd(M,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when ''Y'' then
				dateadd(yyyy,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when '''' then
				dateadd(D,intserviceperiod,isnull(@dtplastServiceDate,PAckageDate))
				else '''' end  					
				from #temp2,apackagesettings where intcounter=@intcount and
				@dtplastServiceDate <=@dtptodate and companyid=intcompanyid
				order by SerPerioddate
				
				select @dtplastServiceDate=
				case isnull(SerPeriodType,'''')
				when ''D'' then 						
				dateadd(D,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when ''M'' then
				dateadd(M,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when ''Y'' then
				dateadd(yyyy,intserviceperiod, isnull(@dtplastServiceDate,PAckageDate))
				when '''' then
				dateadd(D,intserviceperiod,isnull(@dtplastServiceDate,PAckageDate))
				else '''' end  					
				from #temp2,apackagesettings where intcounter=@intcount and
				@dtplastServiceDate <=@dtptodate and companyid=intcompanyid
				
				insert into #temp3				
				select intConid,intconcompanyid ,intconshopid ,intconCustid ,
				intconservid ,intalertday,dtpconServiceDate from #temp5 left outer join #temp4
				on tempcustomerid=intconCustid and tempshopid=intconshopid
				and intcounter=tempcounter where tempcounter is  null
				and dtpconServiceDate <=@dtptodate
				delete from #temp5
				set @dtplastServiceDate=@dtplastServiceDate					
			   end
					
		  end
		Delete from #temp2 where intcounter=@intcount	
		delete from #temp4			
		select @intcount=min(intcounter) from #temp2
	end     	
	--drop table #temp1
	drop table #temp2
	if @strfromdate <> '''' and @strTodate <>''''
	Begin
	select mchNo [Machine No],sername [Service Name],customername [Customer Name],
	dtpconServiceDate [Servicing Date],mchShopID,mchCompanyID,mchContractRefNo
	,customerid,mchID,serid, ItemDescription, MOdelNo from #temp3  left outer join losSerMaintenanceContractHeader on
	mchShopID=intconshopid and mchCompanyID=intconcompanyid and mchID=intConid,acustomermaster c,aservicemaster
	,apackagesettings s, losSerMaintenanceMachineDetail, aitem ai where intconCustid=customerid and
	intconservid=serid and intconcompanyid=c.companyid
	and mmdCompanyID = intconcompanyid and mmdMCID = intConid and mmdShopID = intconshopid
	and mmdMachineID = ai.itemid
	--and (packagedate+intalertday)>=dtpconServiceDate
	end
	else
	begin
	select mchNo [Machine No],sername [Service Name],customername [Customer Name],
	dtpconServiceDate [Servicing Date], mchShopID,mchCompanyID,mchContractRefNo, ItemDescription, MOdelNo from #temp3
	left outer join losSerMaintenanceContractHeader on
	mchShopID=intconshopid and mchCompanyID=mchCompanyID and mchID=intConid,acustomermaster c,aservicemaster
	,apackagesettings s, losSerMaintenanceMachineDetail, aItem ai where intconCustid=customerid and
	intconservid=serid and intconcompanyid=c.companyid and
	 (packagedate+intalertday)>=dtpconServiceDate and mchCompanyID = mmdCompanyID
	and mmdCompanyID = intconcompanyid and mmdMCID = intConid and mmdShopID = intconshopid
	and mmdMachineID = ai.itemid
end 	
	drop table #temp3
	drop table #temp4
	drop table #temp5	
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSerialNoFetch]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSerialNoFetch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------
--Usage : execute spSerialNoFetch  ''adads'',501
------
CREATE   PROCEDURE [dbo].[spSerialNoFetch] @Serialno as VARCHAR(50),@intItemID AS INT AS
Set noCount on
CREATE table #tmptable (
ID  int,
IDNO  varchar(100),
Billdate datetime ,
custID  int,
customername  varchar(200),
Address  varchar(800),
phoneno  varchar(200)
)
BEGIN
DECLARE @interfaceid INT,
@intShopID INT,
@inttransactionID INT
declare opcur cursor for SELECT InterfaceID,ShopID,TransactionID FROM vwSerialNofetch
WHERE ItemID=@intItemID and SerialNO=@Serialno
open opcur
fetch next from opcur into @interfaceid,@intShopID,@inttransactionID
while @@fetch_status =0
begin
IF @interfaceid=1502 --pos
BEGIN
insert #tmptable
SELECT poshBillID,poshBillNo,poshBillDate,isnull(poshcustomerid,0),
poshCustomerName  CustomerName,
CASE WHEN poshcustomerid IS not NULL THEN Address1+''''+Address2+''''+Address3 else poshCustomerName end  Address,
CASE WHEN poshcustomerid IS not NULL THEN PhoneNo else poshCustomerName end  PhoneNo
FROM losposheader LEFT OUTER JOIN acustomermaster c ON poshcustomerid=c.CustomerId
WHERE poshBillID=@inttransactionID AND poshShopID=@intShopID
END
IF @interfaceid=1504 --credit Invoice
Begin
insert #tmptable
SELECT ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,
CustomerName,Address1+''''+Address2+''''+Address3 Address,PhoneNo
FROM losinvoiceheader LEFT OUTER JOIN acustomermaster c ON ihCustomerID=c.CustomerId
WHERE ihInvoiceID=@inttransactionID and ihShopID=@intShopID
END
IF @interfaceid=5008 or @interfaceid=5023 or @interfaceid=5025 or @interfaceid=5024  --special invoice
Begin
insert #tmptable
SELECT IhInvoiceID,IhReferenceNo,IhInvoiceDate,IhCustomerID,
CustomerName,Address1+''''+Address2+''''+Address3 Address,c.PhoneNo
FROM losSpecialInvoiceHeader LEFT OUTER JOIN acustomermaster c ON IhCustomerID=c.CustomerId
WHERE IhInvoiceID=@inttransactionID and IhShopID=@intShopID
end
fetch next from opcur into @interfaceid,@intShopID,@inttransactionID
end
close opcur
deallocate opcur
select ID,IDNO,Billdate,isnull(custID,0),customername,isnull(Address,''-''),isnull(phoneno,''-'') from #tmptable
Set noCount off
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSellingPriceFetchWOPriceChange]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellingPriceFetchWOPriceChange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By  : Aneesh YK
--Created Date: 31/01/2006
--Note        : This peocedure is same as spSellpriceCurrwise but, i have avoided the checking
--  pricechanged = 0 condition to fetch the already existing selling price
--       : This has been done for Redwave
-----------------------------------------------
--REFNO:01
--MODIFIED BY : NIDHEESH PV
--MODIFIED ON : 24/02/2011
--COMMENTS :THE SEGMENT ID IS SELECTED FROM SHOP-CUST DETAILS INSTED OF CUSTOMER MASTER
-----------------------------------------------
--REFNO:02
--MODIFIED BY : NIDHEESH PV
--MODIFIED ON : 28/03/2011
--COMMENTS : IF AUTOMATED SEGMENT WISE PRICE FIXATION IS ENABLED
--THEN MANUALLY FIXED PRICES OF SEGMENTS NEED NOT TO BE CONSIDERED.
-----------------------------------------------
CREATE proc [dbo].[spSellingPriceFetchWOPriceChange] @intCompanyId as int, @intShopid as int, @intCustomerId as int=0,
@intitemid as int, @intpackid as int, @intCash as int =1, @intCurrencyID as int
as
Declare @intpriceathq as int,
@intsellCount as int,
@intSegmentId as int,
@AutoSegmentSP as bit
begin
Select @intpriceathq = Pricefixedathq from aitem where itemid = @intitemid
Select @AutoSegmentSP = AutomateSegmentwisePrice from apackagesettings --REFNO:02
------------------REFNO:01---------------------------------
--select @intSegmentId = isnull(segmentid,0) from acustomermaster where
--customerid = @intCustomerid and Companyid =@intCompanyId
select @intSegmentId = isnull(segmentid,0) from ashopcustomerdetails where
customerid = @intCustomerid and shopid=@intShopid --and Companyid =@intCompanyId
-------------------REFNO:01---------------------------------
select @intsellCount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and segmentId = @intSegmentID
--REFNO:02--START-
if @AutoSegmentSP=1
begin
set @intsellCount=0
end
--REFNO:02--ENDS-
if @intSellCount=0 --Checking for Customer Segments
begin
select @intSegmentId = isnull(segmentid,0) from Ashops where
shopid = @intShopid and Companyid =@intCompanyId
select @intsellCount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
segmentId = @intSegmentId
--REFNO:02--START-
if @AutoSegmentSP=1
begin
set @intsellCount=0
end
--REFNO:02--ENDS-
--Checking for Shop Segments
if @intSellCount=0 --NO segment wise price fixed for this item
exec spsellpriceCurrwiseWOPriceChange @intCompanyId, @intShopid ,
@intItemID, @intPackId, 0, @intpriceathq,
@intCash, @intCurrencyID
else --If shop segment available
exec spsellpriceCurrwiseWOPriceChange @intCompanyId, @intShopid ,
@intItemID, @intPackId, @intSegmentId, @intpriceathq,
@intCash, @intCurrencyID
end
else --If Customer segment available
exec spsellpriceCurrwiseWOPriceChange @intCompanyId, @intShopid ,
@intItemID, @intPackId, @intSegmentId, @intpriceathq,
@intCash, @intCurrencyID
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSellingPriceFetch]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSellingPriceFetch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spSellingPriceFetch    Script Date: 18/01/2003 9:45:45 PM ******/
--Created By  : Hariharan R
--Created Date: 14/12/2002
-----------------------------------------------
--REFNO:01
--MODIFIED BY : NIDHEESH PV
--MODIFIED ON : 24/02/2011
--COMMENTS :THE SEGMENT ID IS SELECTED FROM SHOP-CUST DETAILS INSTED OF CUSTOMER MASTER
-----------------------------------------------
--REFNO:02
--MODIFIED BY : NIDHEESH PV
--MODIFIED ON : 28/03/2011
--COMMENTS : IF AUTOMATED SEGMENT WISE PRICE FIXATION IS ENABLED
--THEN MANUALLY FIXED PRICES OF SEGMENTS NEED NOT TO BE CONSIDERED.
-----------------------------------------------
CREATE proc [dbo].[spSellingPriceFetch] @intCompanyId as int, @intShopid as int, @intCustomerId as int=0,
@intitemid as int, @intpackid as int, @intCash as int =1, @intCurrencyID as int
as
Declare @intpriceathq as int,
@intsellCount as int,
@intSegmentId as int,
@priceChanged as int,
@AutoSegmentSP as bit
begin
Select @intpriceathq = Pricefixedathq from aitem where itemid = @intitemid
Select @AutoSegmentSP = AutomateSegmentwisePrice from apackagesettings --REFNO:02
--------------------REFNO:01-------------------------
--select @intSegmentId = isnull(segmentid,0) from acustomermaster where
--customerid = @intCustomerid and Companyid =@intCompanyId
select @intSegmentId = isnull(segmentid,0) from ashopcustomerdetails where
customerid = @intCustomerid and shopid=@intShopid --and Companyid =@intCompanyId
--------------------REFNO:01-------------------------
select @intsellCount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and segmentId = @intSegmentID
and pricechanged = 0
--REFNO:02--START-
if @AutoSegmentSP=1
begin
set @intsellCount=0
end
--REFNO:02--ENDS-
if @intSellCount=0 --Checking for Customer Segments
begin
select @intSegmentId = isnull(segmentid,0) from Ashops where
shopid = @intShopid and Companyid =@intCompanyId
select @intsellCount = count(isnull(itemid,0)) from losshopitemshipmentdetail where
itemid = @intitemid and packingtypeid = @intpackid and
segmentId = @intSegmentId and pricechanged = 0
--REFNO:02--START-
if @AutoSegmentSP=1
begin
set @intsellCount=0
end
--REFNO:02--ENDS-
--Checking for Shop Segments
if @intSellCount=0 --NO segment wise price fixed for this item
exec spsellpriceCurrwise @intCompanyId, @intShopid ,
@intItemID, @intPackId, 0, @intpriceathq,
@intCash, @intCurrencyID
else --If shop segment available
exec spsellpriceCurrwise @intCompanyId, @intShopid ,
@intItemID, @intPackId, @intSegmentId, @intpriceathq,
@intCash, @intCurrencyID
end
else --If Customer segment available
exec spsellpriceCurrwise @intCompanyId, @intShopid ,
@intItemID, @intPackId, @intSegmentId, @intpriceathq,
@intCash, @intCurrencyID
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesConfirmation]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesConfirmation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
--Created on  : 12/03/2003
--Created by    : R Harikrishnan
--Comments  : For Sales Confirmation report
-----------------------------------------------------------------------
--Modified on  : 02/08/2003
--Modified by   : R Harikrishnan
--Comments  : Added declared price
-----------------------------------------------------------------------
CREATE procedure [dbo].[spSalesConfirmation]
@intShopID as int,
@intPOID   as int
as
select
h.ihInvoiceNo,h.ihInvoiceDate,h.ihReferenceNo,d.idPQuantity,d.idQuantity,d.idcostprice,
it.ItemDescription,it.Part_code,it.Volume, cm.CustomerName, cur.Symbol,
u.UnitName,org.CountryName orgin,con.CountryName Consignment,pt.PackingTypeName,d.idDeclaredPrice
,CategoryNameDescription
from
losInvoiceHeader h,LosInvoiceDetail d,aCustomerMaster cm,aCountryMaster Org,aCountryMaster Con,
aitem it,
aItemCategory ait
,aUnit u,aCurrencyMaster cur,aPackingType pt
where
h.ihShopID = d.idShopID and h.ihInvoiceID = d.idInvoiceID and
h.ihCompanyID = cm.CompanyID and h.ihCustomerID = cm.customerID and
d.idItemID = it.ItemID and d.idPackingTypeID *= pt.PackingTypeID and
it.OrginCountryID *= org.CountryID and it.ConsignmentCountryID *= con.CountryID and
it.UnitsID = u.unitID and cm.CompanyID = cur.CompanyID and cm.CurrencyID = cur.CurrencyID AND
h.ihShopID=@intShopID and h.ihInvoiceID=@intPOID and  it.ItemCategoryID=ait.ItemCategoryID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckShopUserRights]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_CheckShopUserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : Rajesh Kamalakshan
-- Create date : 18/03/2010
-- Description : To check the user rights for a shopuser
-- =============================================
create PROCEDURE [dbo].[spMagnolia_CheckShopUserRights] --1820,6
-- Add the parameters for the stored procedure here
@interfaceid int,
@UserIDd int
AS
BEGIN
select lour.functionrights from ainterface ai,louserrights lour
where  lour.interfaceid= ai.interfaceid and lour.UserID=@UserIDd
and ai.interfaceid=@interfaceid and lour.modulecode=''poc''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sptrial]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptrial]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO SAVE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnHeader 1,''sdgsfd'',''2010-01-01'',2,
--''ssssfg'',2,1.000,1.000,''gggh'',1,1,1
CREATE PROC [dbo].[sptrial]
(@shopId AS INT,@TransNo AS VARCHAR(50),@TransDate AS DATETIME,@ReferenceID AS INT,
@Remarks AS VARCHAR(250),@DeptId AS INT,@ComExRate AS NUMERIC(18,9),@DepExRate AS NUMERIC(18,9),
@ExRates AS VARCHAR(250),@UserID AS INT,@Confirmed AS INT,@ConfirmedUSerID AS INT
)
AS
DECLARE @intTransId AS INT
DECLARE @intOtherDeptId AS INT
DECLARE @intApartmentId AS INT
DECLARE @intExpenseAccntId AS INT
DECLARE @intToDeptExRate AS NUMERIC(18,9)
BEGIN
SET NOCOUNT ON
if EXISTS (SELECT 1 FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId)
BEGIN
	SELECT @intTransId=MAX(IHRHID)+1
	FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId
END
ELSE
BEGIN
	SET @intTransId=1
END
SELECT @intOtherDeptId=ISNULL(whotherdepid,0),@intApartmentId=ISNULL(whapartmentid,0),
@intExpenseAccntId=ISNULL(whexpenseaccid,0),@intToDeptExRate=isnull(whtodepexrate,0.00)
FROM loswriteoffheader WHERE whShopID=@shopId AND WhID=@ReferenceID
BEGIN TRY
	BEGIN TRAN
		INSERT INTO [LOs_InHouseCons_ReturnHeader]
		(IHRHShopID,IHRHID,IHRHNo,IHRHDate,IHRHReferenceid,IHRHRemarks,
		IHRHdepartmentid,IHRHconexrate,IHRHdepexrate,IHRHexchangerates,IHRHotherdepid,IHRHtodepexrate,
		IHRHexpenseaccid,IHRHapartmentid,IHRHUserId,IHRHConfirmed,IHRHConfirmedUSerID)
		VALUES
		(@shopId,@intTransId,@TransNo,@TransDate,@ReferenceID,@Remarks,
		@DeptId,@ComExRate,@DepExRate,@ExRates,@intOtherDeptId,@intToDeptExRate,
		@intExpenseAccntId,@intApartmentId,@UserID,@Confirmed,@ConfirmedUSerID)
	COMMIT TRAN
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	SELECT ERROR_MESSAGE() AS ERRORDESCRIPTION,ERROR_NUMBER() AS ERRORNUMBER
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO SAVE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnHeader 1,''sdgsfd'',''2010-01-01'',2,
--''ssssfg'',2,1.000,1.000,''gggh'',1,1,1
CREATE PROC [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]
(@shopId AS INT,@TransNo AS VARCHAR(50),@TransDate AS DATETIME,@ReferenceID AS INT,
@Remarks AS VARCHAR(250),@DeptId AS INT,@ComExRate AS NUMERIC(18,9),@DepExRate AS NUMERIC(18,9),
@ExRates AS VARCHAR(250),@UserID AS INT,@Confirmed AS INT,@ConfirmedUSerID AS INT
)
AS
DECLARE @intTransId AS INT
DECLARE @intOtherDeptId AS INT
DECLARE @intApartmentId AS INT
DECLARE @intExpenseAccntId AS INT
DECLARE @intToDeptExRate AS NUMERIC(18,9)
BEGIN
SET NOCOUNT ON
if EXISTS (SELECT 1 FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId)
BEGIN
	SELECT @intTransId=MAX(IHRHID)+1
	FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId
END
ELSE
BEGIN
	SET @intTransId=1
END
SELECT @intOtherDeptId=ISNULL(whotherdepid,0),@intApartmentId=ISNULL(whapartmentid,0),
@intExpenseAccntId=ISNULL(whexpenseaccid,0),@intToDeptExRate=isnull(whtodepexrate,0.00)
FROM loswriteoffheader WHERE whShopID=@shopId AND WhID=@ReferenceID
		INSERT INTO [LOs_InHouseCons_ReturnHeader]
		(IHRHShopID,IHRHID,IHRHNo,IHRHDate,IHRHReferenceid,IHRHRemarks,
		IHRHdepartmentid,IHRHconexrate,IHRHdepexrate,IHRHexchangerates,IHRHotherdepid,IHRHtodepexrate,
		IHRHexpenseaccid,IHRHapartmentid,IHRHUserId,IHRHConfirmed,IHRHConfirmedUSerID)
		VALUES
		(@shopId,@intTransId,@TransNo,@TransDate,@ReferenceID,@Remarks,
		@DeptId,@ComExRate,@DepExRate,@ExRates,@intOtherDeptId,@intToDeptExRate,
		@intExpenseAccntId,@intApartmentId,@UserID,@Confirmed,@ConfirmedUSerID)
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO SAVE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnHeader 1,''sdgsfd'',''2010-01-01'',2,''ssssfg'',2,1.000,1.000,''gggh'',1,1,1
create  PROC [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]
(@shopId AS INT,@TransNo AS VARCHAR(50),@TransDate AS DATETIME,@ReferenceID AS INT,
@Remarks AS VARCHAR(250),@DeptId AS INT,@ComExRate AS NUMERIC(18,9),@DepExRate AS NUMERIC(18,9),
@ExRates AS VARCHAR(250),@UserID AS INT,@Confirmed AS INT,@ConfirmedUSerID AS INT,
@OutStrMessage as varchar(100)='''' OUT,@intOutTransId AS INT =0 OUT
)
AS
DECLARE @intTransId AS INT
DECLARE @intOtherDeptId AS INT
DECLARE @intApartmentId AS INT
DECLARE @intExpenseAccntId AS INT
DECLARE @intToDeptExRate AS NUMERIC(18,9)
BEGIN
SET NOCOUNT ON
if EXISTS (SELECT 1 FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId)
BEGIN
	SELECT @intTransId=MAX(IHRHID)+1
	FROM [LOs_InHouseCons_ReturnHeader] WHERE IHRHShopID=@shopId
END
ELSE
BEGIN
	SET @intTransId=1
END
SELECT @intOtherDeptId=ISNULL(whotherdepid,0),@intApartmentId=ISNULL(whapartmentid,0),
@intExpenseAccntId=ISNULL(whexpenseaccid,0),@intToDeptExRate=isnull(whtodepexrate,0.00)
FROM loswriteoffheader WHERE whShopID=@shopId AND WhID=@ReferenceID
BEGIN TRY
	BEGIN TRAN
		INSERT INTO [LOs_InHouseCons_ReturnHeader]
		(IHRHShopID,IHRHID,IHRHNo,IHRHDate,IHRHReferenceid,IHRHRemarks,
		IHRHdepartmentid,IHRHconexrate,IHRHdepexrate,IHRHexchangerates,IHRHotherdepid,IHRHtodepexrate,
		IHRHexpenseaccid,IHRHapartmentid,IHRHUserId,IHRHConfirmed,IHRHConfirmedUSerID)
		VALUES
		(@shopId,@intTransId,@TransNo,@TransDate,@ReferenceID,@Remarks,
		@DeptId,@ComExRate,@DepExRate,@ExRates,@intOtherDeptId,@intToDeptExRate,
		@intExpenseAccntId,@intApartmentId,@UserID,@Confirmed,@ConfirmedUSerID)
		SET @OutStrMessage=''Saved Successfully''
		SET @intOutTransId=@intTransId
		COMMIT TRAN					
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
	SET @OutStrMessage=ERROR_MESSAGE()
	SET @intOutTransId=0
	IF ERROR_NUMBER()=2627---CUSTOMISED ERROR---
	BEGIN
		SET @OutStrMessage=''Error Due to duplicated Values''
	END
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb1]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ServiceHistoryWeb1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by Sreejith 18/03/2010
--spMagnolia_ServiceHistoryWeb ''s'',''A.A.A. TRADING COMPANY'','''','''','''',''YAM/SB'',''sd'',''20100323''
--spMagnolia_ServiceHistoryWeb ''S'',''Bank'','''','''','''','''','''',''20040101''
create PROC [dbo].[spMagnolia_ServiceHistoryWeb1] (@shopid as int)
as
begin
select * from vwMagnolia_ServiceHistoryWeb   where shopid=  @shopid
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_ServiceHistoryWeb]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created by Sreejith 18/03/2010
--spMagnolia_ServiceHistoryWeb ''s'',''A.A.A. TRADING COMPANY'','''','''','''',''YAM/SB'',''sd'',''20100323''
--spMagnolia_ServiceHistoryWeb ''S'',''Bank'','''','''','''','''','''',''20040101''
CREATE PROC [dbo].[spMagnolia_ServiceHistoryWeb] @searchType varchar(2),@Fname  varchar(100),@address  varchar(250),
@phoneNo  varchar(50), @shopName as varchar(250),@RefNo as varchar(20),@slno  varchar(50) ,@date datetime
as
begin
if @searchType=''S''        ----''S'' stands for Starts with
begin
set @Fname = @Fname +''%''
end
else if  @searchType=''C''       ----''C'' stands for Contains
begin
set @Fname =  ''%'' + @Fname +''%''
end
if @searchType=''S''
begin
set @address = @address +''%''
end
else if  @searchType=''C''
begin
set @address = ''%''+ @address +''%''
end
if @searchType=''S''
begin
set @phoneNo = @phoneNo +''%''
end
else if  @searchType=''C''
begin
set @phoneNo = ''%''+ @phoneNo +''%''
end
if @searchType=''S''
begin
set @shopName = @shopName +''%''
end
else if  @searchType=''C''
begin
set @shopName = ''%''+ @shopName +''%''
end
if @searchType=''S''
begin
set @RefNo = @RefNo +''%''
end
else if  @searchType=''C''
begin
set @RefNo = ''%''+ @RefNo +''%''
end
if @searchType=''S''
begin
set @slno = @slno +''%''
end
else if  @searchType=''C''
begin
set @slno = ''%''+ @slno +''%''
end
select * from vwMagnolia_ServiceHistoryWeb where
FirstName like  @Fname and
Address like @address and
PhoneNo like @phoneNo and
ShopName like @shopName and
RefNo like @RefNo  and
slno like @slno and   Date >= @date
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO UPDATE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnDetail  1,1,1,1,1,1.1,22,2,2,100,1.1,1.1
create PROC [dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]
(@shopId AS INT,@TransId AS INT,@Remarks AS VARCHAR(250),@Confirmed AS INT,@ConfirmedUSerID AS INT,
@OutStrMessage as varchar(100)='''' OUT
)
AS
BEGIN
BEGIN TRY
	BEGIN TRAN
		UPDATE [LOs_InHouseCons_ReturnHeader]
		SET IHRHRemarks=@Remarks,IHRHConfirmed=@Confirmed,
		IHRHConfirmedUSerID=@ConfirmedUSerID,IHRHModifiedUserId=@ConfirmedUSerID
		WHERE IHRHShopID=@shopId AND IHRHID=@TransId
		SET @OutStrMessage=''Updated Successfully''
	COMMIT TRAN					
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
	SET @OutStrMessage=ERROR_MESSAGE()
	IF ERROR_NUMBER()=2627---CUSTOMISED ERROR---
	BEGIN
		SET @OutStrMessage=''Error Due to duplicated Values''
	END
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[VWItemRateDetails]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWItemRateDetails]'))
EXEC dbo.sp_executesql @statement = N'
create VIEW [dbo].[VWItemRateDetails] as
select b.sname,b.itemid,a.Packingtypename,d.Quantity * b.Itemrate Costprice ,
cast(b.sellingprice as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.sellingprice as varchar(100)) else
cast(cast((b.sellingprice -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end SellingPrice,
cast(b.wholesaleprice as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.wholesaleprice as varchar(100)) else
cast(cast((b.wholesaleprice -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end WholesalePrice,
cast(b.discountprice as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.discountprice as varchar(100)) else
cast(cast((b.discountprice -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end DiscountPrice,
b.packingtypeid ,
cast(b.CreditSP as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.CreditSP as varchar(100)) else
cast(cast((b.CreditSP -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end CreditSP,
cast(b.CreditDP as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.CreditDP as varchar(100)) else
cast(cast((b.CreditDP -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end CreditDP,
cast(b.CreditWP as varchar(100))+'' (''+case when isnull(b.Itemrate,0)=0  then cast(b.CreditWP as varchar(100)) else
cast(cast((b.CreditWP -(d.Quantity * b.Itemrate))/((d.Quantity * b.Itemrate))*100 as numeric (18,2)) as varchar(100))+''%)'' end CreditWP
from
apackingtype a
inner join vwlosshopitemshipmentdetail b on b.packingtypeid=a.packingtypeid
join aPackingTypeCapacityDetail d on d.packingtypeid=a.packingtypeid and d.unitsid=b.unitsid
where b.packingtypeid=a.packingtypeid
and d.packingtypeid=a.packingtypeid'
GO
/****** Object:  View [dbo].[vwinvoiceout]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceout]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwinvoiceout    Script Date: 18/01/2003 9:45:36 PM ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 14/09/2002 12:48:06 AM ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 20/11/2001 9:59:00 AM ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 17/11/2001 9:21:30 PM ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 16/06/2001 15:36:31 ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 09/03/2001 02:32:27 ******/
/****** Object:  View dbo.vwinvoiceout    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwinvoiceout] as
select isdshopid,isdsubitemid,sum(isdquantity) as invoiceqtyout ,ihInvoiceDate  from
LOsInvoiceHeader ,LOsInvoiceSubItemDetail
where ihshopid=isdshopid and ihInvoiceid=isdInvoiceid and ihcancelled=0
group by isdshopid,ihInvoiceDate,isdsubitemid'
GO
/****** Object:  View [dbo].[vwInvoiceServicePartsForPrinting]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInvoiceServicePartsForPrinting]'))
EXEC dbo.sp_executesql @statement = N'
--MODIIFED BY  : HARIHARAN
--MODIFIED DATE : 12/10/2003, 18/10/2003, 04/02/2004, 20/09/2004
--COMMENTS : Added Service amount and parts amount
--  : verified and corrected the query
-- : repinvdtype query modified to correct the population of parts replaced items
--Altered by Sreejith on 27/05/2010  and 03-07-2010
--Added ,li.serinvhcmpexrate and DepCurrencySymbol  field
---------------------------------------------------------------
--RefNo : 01
--Modified Ny : VinothMurugan V.
--Date    : 05/10/2010
--Purpose   : Adding Address ,userid
---------------------------------------------------------
--RefNo : 02
--Modified Ny : Shine Das
--Date    : 06/09/2011
--Purpose   : To show warranty details, neccessary fields added.
---------------------------------------------------------
--Modified Ny :jyothish
--Date    : 10/10/2011
--jyothish added  case  when  cu.address1  is null then serCallBkhaddress
------------------------------------------------------------
--RefNo : 03
--Modified Ny : AADYA KUMAR D V
--Date    : 01/12/2011
--Purpose   : serinvhcustname field added.
---------------------------------------------------------
CREATE VIEW  [dbo].[vwInvoiceServicePartsForPrinting] AS
Select
li.serinvhcompanyid CompanyId,  li.SerinvhId InvoiceId,
li.serinvhshopid ShopId,serCode Code, SerName Description,
serinvdcharge ActRate, serinvdchargetaken Rate,
serinvdqty Qty, serinvdcomments Comments, ''Services'' Type,
SerInvNo, SerInvHDate,SerInvHProcNo, SerInvHProcDate,
case when cu.customername is null then serCallBkhcustomerName   else cu.customername   end   as   CustomerName, li.SerInvHRefNo, li.SerInvHRemarks,
SerInvHBookingId, li.SerInvHItemName, li.SerInvHItemId, SerInvHDueDate, SerInvDQty PackQty,
isnull(serbookadvanceamount,0) BookingAdvance, ''Each'' UnitCode, serInvhCashAcc ,
case
when isnull(serInvhCashAcc,0) = 0 then isnull(cur2.Symbol, ''Mrf'') else
ISNULL(cur1.Symbol, ''Mrf'') end currencysymbol
,isnull(li.serinvhamount,0.00) amount,spername,enddate,endtime
,sercallbkhdate serbookhdate,serbookhinspectiontime,aitem.ModelNo
,serinvhPaceofWork,li.serinvhmetereading,sercallbkrefno serbookrefno,
aitem.Part_code, li.serinvhpartsamt, li.serinvhserviceamt, serinvdType,
''Each'' packcode,
case  when serCallBkhcustomerName is null  then customername else serCallBkhcustomerName end CustName,
serinvhCustomerId, serinvhcancelled  ,li.serinvhcmpexrate,li.serinvhCashInv ,
scm.sercategid, scm.sercatname ,li.seinvhdepexrate,cur3.Symbol  DepCurrencySymbol,'''' packName,li.serinvhuserid,
------------------------------------------------------------  --RefNo : 01
case  when li.serinvhCustomerId is null then ''''
else  case  when  cu.address1  is null then serCallBkhaddress else   cu.address1
end end address1,
case  when li.serinvhCustomerId is null then ''''
else  cu.address2
end  address2,
case  when li.serinvhCustomerId is null then ''''
else  cu.address3
end  address3,
--RefNo : 02
aItem.ItemDescription ServicedItem,aItem.ItemCode ServicedItemCode, los.serCallBkhSerialNo SerialNo,
los.serCallBkhServWarrantyUpto ServiceWarranty,los.serCallBkhPartsWarrantyUpto PartsWarranty,
serinvdItemTaxPercentage, serinvdItemTaxAmount,cu.CUSTOMERTIN,li.serinvhcustname   --RefNo : 03
-----------------------------------------------------------
from
losserviceinvheader li
left outer join losserviceheader on li.serinvhjobcardid=losserviceheader.serinvhid
and li.serinvhshopid=losserviceheader.serinvhshopid and li.serinvhcompanyid=losserviceheader.serinvhcompanyid
left outer join losservicebookingheader bk on losserviceheader.serinvhshopid = serbookhshopid and
serinvhbookingid = serbookhid and losserviceheader.serinvhcompanyid = serbookhcompanyid
left outer join loscallbookingheader los on serbookhrefid = los.serCallBkhid and bk.serbookhcompanyid =
los.serCallBkhcompanyid and bk.serbookhshopid=los.serCallBkhshopid
left outer join losinvoicedservicedetails
on li.serinvhcompanyid = serinvdcompanyid and  li.serinvhshopid = serinvdshopid
and li.serinvhid = serinvdinvoiceid
Left Outer Join aservicemaster m
on serinvdserviceid = serid and  serinvdcompanyid = sercompanyid
inner Join aServiceCategory scm     --- sree
on m.sercategid = scm.sercategid and  m.sercompanyid = scm.sercatcompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid
left outer join acustomermaster cu on li.serinvhCustomerId= cu.customerid
and li.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
left outer join adepartmentmaster adp on li.serinvhdepartmentid= adp.DepartmentID
and li.serinvhcompanyid = adp.CompanyID
left outer join acurrencymaster cur3 on adp.depcurrencyid  =cur3.currencyid
and adp.CompanyID=cur3.companyid
left outer join
( select a1.sertechinvid invid,
max(a1.serinvtechendtime) endtime ,max(a1.serinvTechEstEndDate) enddate,
max(a1.serinvtechid) techid,a1.serinvtechcompanyid tempcompanyid
,a1.serinvtechshopid tempshopid from losservinvoicetechniciandetails a1
where a1.serinvTechEstEndDate in
(select max(a2.serinvTechEstEndDate)
from losservinvoicetechniciandetails a2
where a1.serinvtechcompanyid=a2.serinvtechcompanyid
and a1.serinvtechshopid=a2.serinvtechshopid
and a1.sertechinvid=a2.sertechinvid
group by a1.serinvtechcompanyid, a1.serinvtechshopid , a1.sertechinvid )
group by a1.sertechinvid,a1.serinvtechcompanyid,a1.serinvtechshopid ) as temptechnican
on losserviceheader.serinvhid=invid  and
losserviceheader.serinvhcompanyid=tempcompanyid
and losserviceheader.serinvhshopid=tempshopid         left outer join asalespersonmaster on techid=sperid
left outer join aItem on li.serinvhitemid = aItem.ItemId
left outer join aUnit on aItem.UnitsId = aUnit.UnitId
where
(m.SerCode IS NOT NULL or m.SerCode IS NOT NULL)
and (m.SerCode IS NOT NULL or m.SerCode IS NOT NULL)  and right(serinvdType, 1) <>''n''
union all
Select
repinvcompanyid,  repinvinvoiceid, repinvdshopid, n.itemcode, n.itemdescription,
repinvdsellrate, repinvdrate, repinvdqty, repinvdcomments, ''Parts Replaced'',  serinvno,
serinvhdate, serinvhprocno, serinvhprocdate, case when cu.customername is null then serCallBkhcustomerName   else cu.customername   end   as   CustomerName , li.SerInvHRefNo,
li.serinvhremarks,serinvhbookingid, li.serinvhitemname, li.serinvhitemid,serinvhduedate,repinvpackqty,
isnull(serbookadvanceamount,0) bookingadvance, aUnit.UnitCode,li.serinvhcashacc,
case when isnull(li.serinvhcashacc,0) = 0 then isnull(cur2.Symbol, ''Mrf'') else
isnull(cur1.Symbol, ''Mrf'') end currencysymbol,isnull(li.serinvhamount,0.00) amount,spername,enddate,endtime,
sercallbkhdate,serbookhinspectiontime,m.ModelNo model_no,serinvhPaceofWork,li.serinvhmetereading
,sercallbkrefno serbookrefno,m.Part_code, li.serinvhpartsamt, li.serinvhserviceamt,
repinvdType, PackingTypeCode ,
case when serCallBkhcustomerName  is null then customername else serCallBkhcustomerName end CustName,
serinvhCustomerId, serinvhcancelled ,li.serinvhcmpexrate  ,li.serinvhCashInv ,
'''' sercategid,'''' sercatname,li.seinvhdepexrate,cur3.Symbol  DepCurrencySymbol,p.PackingTypeName packName,li.serinvhuserid,
------------------------------------------------------------  --RefNo : 01
case  when li.serinvhCustomerId is null then ''''--shoplocation
else  case  when  cu.address1  is null then serCallBkhaddress else   cu.address1
end end address1,
case  when li.serinvhCustomerId is null then ''''
else  cu.address2
end  address2,
case  when li.serinvhCustomerId is null then ''''--address
else  cu.address3
end  address3,
--RefNo : 02
m..ItemDescription ServicedItem,m.ItemCode ServicedItemCode, los.serCallBkhSerialNo SerialNo,
los.serCallBkhServWarrantyUpto ServiceWarranty,los.serCallBkhPartsWarrantyUpto PartsWarranty,
repinvdItemTaxPercentage, repinvdItemTaxAmount,cu.CUSTOMERTIN,li.serinvhcustname  --RefNo : 03
-----------------------------------------------------------
from
losinvoicedpartsreplacedetails , losserviceinvheader li
left outer join losserviceheader on li.serinvhjobcardid=losserviceheader.serinvhid and
li.serinvhshopid = losserviceheader.serinvhshopid
and li.serinvhcompanyid=losserviceheader.serinvhcompanyid
left outer join aaccountmaster acc on serInvhCashAcc=accountid
and li.serinvhcompanyid=acc.companyid
left outer join acurrencymaster cur1 on acc.currencyid=cur1.currencyid
and acc.companyid=cur1.companyid
left outer join losservicebookingheader bk on losserviceheader.serinvhshopid = serbookhshopid
and losserviceheader.serinvhbookingid = serbookhid and
losserviceheader.serinvhcompanyid = serbookhcompanyid
LEFT outer join loscallbookingheader los on
serbookhrefid = los.serCallBkhid and bk.serbookhcompanyid = los.serCallBkhcompanyid and
bk.serbookhshopid = los.serCallBkhshopid
left outer join acustomermaster cu on li.serinvhCustomerId= cu.customerid
and li.serinvhcompanyid = cu.companyid
left outer join acurrencymaster cur2 on cu.currencyid=cur2.currencyid
and cu.companyid=cur2.companyid
left outer join adepartmentmaster adp on li.serinvhdepartmentid= adp.DepartmentID
and li.serinvhcompanyid = adp.CompanyID
left outer join acurrencymaster cur3 on adp.depcurrencyid  =cur3.currencyid
and adp.CompanyID=cur3.companyid
left outer join
( select a1.sertechinvid invid,
max(a1.serinvtechendtime) endtime ,max(a1.serinvTechEstEndDate) enddate,
max(a1.serinvtechid) techid,a1.serinvtechcompanyid tempcompanyid
,a1.serinvtechshopid tempshopid from losservinvoicetechniciandetails a1
where a1.serinvTechEstEndDate in
(select max(a2.serinvTechEstEndDate)
from losservinvoicetechniciandetails a2
where a1.serinvtechcompanyid=a2.serinvtechcompanyid
and a1.serinvtechshopid=a2.serinvtechshopid
and a1.sertechinvid=a2.sertechinvid
group by a1.serinvtechcompanyid, a1.serinvtechshopid , a1.sertechinvid )
group by a1.sertechinvid,a1.serinvtechcompanyid,a1.serinvtechshopid ) as temptechnican
on losserviceheader.serinvhid=invid  and
losserviceheader.serinvhcompanyid=tempcompanyid and
losserviceheader.serinvhshopid=tempshopid
left outer join asalespersonmaster on techid=sperid
left outer join  aitem m  on li.serInvhItemId = m.ItemId
, aItem n, aPackingType p  , aunit
where
li.serinvhcompanyid = repinvcompanyid and li.serinvhid = repinvinvoiceid and
li.serinvhshopid = repinvdshopid
and repinvdpartsid = n.itemid and repinvpackid = p.packingtypeid
and n.UnitsId = aUnit.UnitId
and patindex(''%N%'', repinvdType ) = 0'
GO
/****** Object:  View [dbo].[vwInhousePurchasesBilled]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesBilled]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view lists out all inhouse purchases
-- that got billed.
-- Here, prefix ipb stands for Inhouse Purchases Billed
--------------------------------------------------------------------------------
-- Coded By : Regin T.
-- Coded On : 03-03-2010
--------------------------------------------------------------------------------
CREATE view [dbo].[vwInhousePurchasesBilled] as
select ipbdInhousePurchaseId ipbId, iphNo ipbNo, sum(ipbdBilledAmount) ipbBilledAmount
from hqInhousePurchaseBillingDetails
inner join BillsDebitDetails d on ipbdBillId=BillsID and ipbdBillDetailId=BillsDebitID
inner join Bills h on d.BillsID=h.BillsID
inner join loaInhousePurchaseHeader on ipbdInhousePurchaseId=iphId
where Cancelled=0
group by ipbdInhousePurchaseId, iphNo'
GO
/****** Object:  View [dbo].[vwShopSplInvItemAmount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplInvItemAmount]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwShopSplInvItemAmount    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
--altered by :- benzigar
--Altered on :- 26/06/2009
--In special invoice , if item is from multiple godown then sum(idUnitPrice) need to take.
--Previously max(idUnitPrice) is used
--altered by :Nidheesh P V
--altered on :03-08-09
--included idRateType in the select statement
CREATE view [dbo].[vwShopSplInvItemAmount] as
--select idshopid, idInvoiceId, idItemid, sum(reqqty) idquantity,
--case when sum(reqqty)< 0  then -max(idUnitPrice) else max(idUnitPrice) end idunitprice,
--max(idcostprice) costprice from losspecialinvoicedetail group by idShopid, idinvoiceid, iditemid
select idshopid, idInvoiceId, idItemid, sum(reqqty) idquantity,
case when sum(reqqty)< 0  then -sum(idUnitPrice) else sum(idUnitPrice) end idunitprice,
max(idcostprice) costprice,idRateType from losspecialinvoicedetail
group by idShopid, idinvoiceid, iditemid,idRateType'
GO
/****** Object:  View [dbo].[vwshopservicesalesWithOutGST]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopservicesalesWithOutGST]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--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 [dbo].[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
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinCreditInvoice]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinCreditInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY	 : Hariharan
--Created Date	 : 13/02/2004
CREATE Proc [dbo].[spCorrectCostPriceinCreditInvoice] as
set nocount on
Begin
Declare @intCount as int,
	@intItemId as int,
	@intShopId as int,
	@intInvoiceId as int,
	@invDate as datetime,
	@CostPrice as numeric(18,2),
	@intCurrId as int,
	@NumCurCostPrice as numeric(18,2),
	@strInvoiceNo as varchar(50),
	@intCostCount as int
Create table #CreditInvoice
		(spInvoiceDate Datetime,
		spItemid int,
		spInvoiceId int,	
		spShopId int,
		spCorrected bit,
		CurrencyId int,
		ItemCostPr numeric(18, 2),
		InvoiceNo  varchar(50))
Insert #CreditInvoice
Select ihinvoiceDate, IdItemId, IdInvoiceId, idShopId, 0, CurrencyId, Itemrate, ihInvoiceNo from
losInvoiceDetail, LosInvoiceHeader, aCustomerMaster, aitem where
ihInvoiceID = idInvoiceId and ihSHopid = idshopid and ihCancelled = 0
and ihCustomerId = CUstomerid and ihInvoiceDate >''20031231''
and ihType = ''i'' and iditemid = aitem.itemid and ihShopid = 1
order by ihinvoiceDate, idshopid, idinvoiceid, idItemid
	Set @intCount = 0
	Set @intItemId = 0
	Set @intShopId = 0
	Set @intInvoiceId = 0
Select @intCount = count(*) from #CreditInvoice where spCorrected = 0
While @intcount <> 0
	
	Begin
		
		Set @CostPrice = 0
		
		Select top 1 @invDate = spInvoiceDate, @intItemId = spItemID,
		@intInvoiceId = spInvoiceId, @intShopId = spShopID, @intCurrId =CurrencyId,
		@NumCurCostPrice = ItemCostPr, @strInvoiceNo = InvoiceNo from  #CreditInvoice
		where spCorrected = 0
		
		Select top 1 @CostPrice = isnull(cdNewItemCostPrice,0) from
		loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
		and ChCancelled = 0 and isnull(chCostingDate, ''20030101'') <= @invDate
		and cdItemId = @intItemId order by cdCostingId desc
		set @CostPrice  = isnull(@CostPrice , 0)
		set @NumCurCostPrice = isnull(@NumCurCostPrice, 0)
		if @intcurrid = 2
			set @NumCurCostPrice = @NumCurCostPrice/  12.85
		if @CostPrice = 0
			Select top 1 @CostPrice = isnull(cdOldItemCostPrice,0) from
			loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
			and ChCancelled = 0 and cdItemId = @intItemId order by cdCostingId
		set @intCostCount = 0
		Select @intCostCount = count(*) from loaCostingheader ch, loaCostingDetail cd
		where chCostingId = cdCostingId and chCostingId <> 0
		and cdItemid = @intItemId and chCancelled = 0
		
		set @CostPrice  = isnull(@CostPrice , 0)
		if @intCurrId = 2
			set @CostPrice = @CostPrice /12.85
		if @intCostCount = 0
			set @CostPrice  = 0			
	
		if @CostPrice <> 0
			Update losInvoiceDetail set idCostPrice = @Costprice, idguarantee = ''upd''
			where idItemid = @intItemID and idInvoiceiD = @intinvoiceId and
			idshopid = @intShopId
		else	--in case of item costprice not available in costing detail tables
			Update losInvoiceDetail set idCostPrice = @NumCurCostPrice , idguarantee = ''upd''
			where idItemid = @intItemID and idInvoiceiD = @intinvoiceId and
			idshopid = @intShopId
	
	
		Update #CreditInvoice set spCorrected = 1 where spInvoiceId = @intInvoiceId
		and spShopId = @intShopId and spItemID = @intItemId
		Update LosInvoiceHeader set ihPosted = 0 where
		ihInvoiceno = @strInvoiceNo and ihShopId = @intShopId and
		ihInvoiceId = @intInvoiceId
		Update MoajournalHeader set Cancel = 1 where Referenceno = @strInvoiceNo and
		Type = ''ScI''
		
		Select @intCount = count(*) from #CreditInvoice where spCorrected = 0
	End
End
set nocount oFF' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinSplInvoice]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinSplInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY	 : Hariharan
--Created Date	 : 13/02/2004
CREATE Proc [dbo].[spCorrectCostPriceinSplInvoice] as
set nocount on
Begin
Declare @intCount as int,
	@intItemId as int,
	@intShopId as int,
	@intInvoiceId as int,
	@invDate as datetime,
	@CostPrice as numeric(18,2),
	@intCurrId as int,
	@NumCurCostPrice as numeric(18,2),
	@strInvoiceNo as varchar(50)
Create table #SpecialInvoice
		(spInvoiceDate Datetime,
		spItemid int,
		spInvoiceId int,	
		spShopId int,
		spCorrected bit,
		CurrencyId int,
		ItemCostPr numeric(18, 2),
		InvoiceNo  varchar(50))
Insert #SpecialInvoice
Select ihinvoiceDate, IdItemId, IdInvoiceId, idShopId, 0, CurrencyId, Itemrate, ihInvoiceNo from
losSpecialInvoiceDetail, LosSpecialInvoiceHeader, aCustomerMaster, aitem where
ihInvoiceID = idInvoiceId and ihSHopid = idshopid and ihCancelled = 0 and
idActualUnitPrice = idCostPrice and ihCustomerId = CUstomerid and ihInvoiceDate >''20031231''
and iditemid = aitem.itemid
order by ihinvoiceDate, idshopid, idinvoiceid, idItemid
	Set @intCount = 0
	Set @intItemId = 0
	Set @intShopId = 0
	Set @intInvoiceId = 0
Select @intCount = count(*) from #SpecialInvoice where spCorrected = 0
While @intcount <> 0
	
	Begin
		
		Set @CostPrice = 0
		
		Select top 1 @invDate = spInvoiceDate, @intItemId = spItemID,
		@intInvoiceId = spInvoiceId, @intShopId = spShopID, @intCurrId =CurrencyId,
		@NumCurCostPrice = ItemCostPr, @strInvoiceNo = InvoiceNo from  #SpecialInvoice
		where spCorrected = 0
		
		Select top 1 @CostPrice = isnull(cdNewItemCostPrice,0) from
		loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
		and ChCancelled = 0 and isnull(chCostingDate, ''20030101'') <= @invDate
		and cdItemId = @intItemId order by cdCostingId desc
		set @CostPrice  = isnull(@CostPrice , 0)
		set @NumCurCostPrice = isnull(@NumCurCostPrice, 0)
		if @intcurrid = 2
			set @NumCurCostPrice = @NumCurCostPrice/  12.85
		if @CostPrice = 0
			Select top 1 @CostPrice = isnull(cdOldItemCostPrice,0) from
			loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
			and ChCancelled = 0 and cdItemId = @intItemId order by cdCostingId
		set @CostPrice  = isnull(@CostPrice , 0)
		if @intCurrId = 2
			set @CostPrice = @CostPrice /12.85
	
		if @CostPrice <> 0
			Update losSpecialInvoiceDetail set idCostPrice = @Costprice, idSerialNo = ''upd''
			where idItemid = @intItemID and idInvoiceiD = @intinvoiceId and
			idshopid = @intShopId
		else	--in case of item costprice not available in costing detail tables
			Update losSpecialInvoiceDetail set idCostPrice = @NumCurCostPrice , idSerialNo = ''upd''
			where idItemid = @intItemID and idInvoiceiD = @intinvoiceId and
			idshopid = @intShopId
	
	
		Update #SpecialInvoice set spCorrected = 1 where spInvoiceId = @intInvoiceId
		and spShopId = @intShopId and spItemID = @intItemId
		Update losSpecialInvoiceHeader set ihPosted = 0 where
		ihInvoiceno = @strInvoiceNo and ihShopId = @intShopId and
		ihInvoiceId = @intInvoiceId
		Update MoajournalHeader set Cancel = 1 where Referenceno = @strInvoiceNo and
		Type = ''SPI''
		
		Select @intCount = count(*) from #SpecialInvoice where spCorrected = 0
	End
End
set nocount oFF' 
END
GO
/****** Object:  View [dbo].[vwinvoiceswithAdvance]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoiceswithAdvance]'))
EXEC dbo.sp_executesql @statement = N'
--***************************************************************************************************
-- Created by  :  Nidheesh P V
-- Created on  : 12/07/2011
-- Purpose     :
--to display the customer even if the customer has no invoice/settlement but an advance is there.
--used in spDebtorAgeSumWithAdvance
--------------------------------------------------------------------------------------
create VIEW [dbo].[vwinvoiceswithAdvance] 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
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
--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
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
--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
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
--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
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
--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
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))
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
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))
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
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))
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
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))
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
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, sum(isnull(sid.idcdcustcur,0)) DutyAmt,
sum(isnull(idQuantity*idcostprice,0.0)) CostPrice ,CustGroupName
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
/****** Object:  View [dbo].[vw_Report_Service_invoices]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_Service_invoices]'))
EXEC dbo.sp_executesql @statement = N'
--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 [dbo].[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
/****** Object:  View [dbo].[vwitempackingtypecheck]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitempackingtypecheck]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 17/11/2001 9:21:47 PM ******/
/****** Object:  View dbo.vwitempackingtypecheck    Script Date: 16/06/2001 15:36:33 ******/
CREATE view [dbo].[vwitempackingtypecheck] as
select distinct itemid, packingtypeid from
(select distinct poditemid Itemid ,  podpackingtypeid packingtypeid
from lopurchaseorderdetail d,
lopurchaseorderheader h where  h.pohpoid=d.podpoid and h.pohcancel=0
group by poditemid, podpackingtypeid
union all
select distinct posditemid, posdpackingtypeid from losposdetail d,
losposheader h where  h.poshbillid=d.posdbillid and h.poshcancelled=0
group by posditemid, posdpackingtypeid
union all
select distinct iditemid, idpackingtypeid from losinvoicedetail d,
losinvoiceheader h where  h.ihinvoiceid=d.idinvoiceid and h.ihcancelled=0
group by iditemid, idpackingtypeid
union all
select distinct iditemid, idpackingtypeid from losspecialinvoicedetail d,
losspecialinvoiceheader h where  h.ihinvoiceid=d.idinvoiceid and h.ihcancelled=0
group by iditemid, idpackingtypeid
union all
select distinct seditemid, sedpackingtypeid from losposexchangedetail d,
losposexchangeheader h where  h.sehexchangeid=d.sedexchangeid and h.sehcancelled=0
group by seditemid, sedpackingtypeid) packingcheck group by itemid, packingtypeid'
GO
/****** Object:  View [dbo].[vw_Report_Service_Bills]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_Service_Bills]'))
EXEC dbo.sp_executesql @statement = N'
--sp_helptext vw_Report_Servic    -- Modified on  : 05/09/2003
-- Modified by  : Kishore
-- Comments     : Changed BillAmount to BillAmount + LcAmount in purchase bill
----------------------------------------------------------------------------------------
CREATE VIEW [dbo].[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
/****** Object:  View [dbo].[vwInhousePurchasesNotBilled]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInhousePurchasesNotBilled]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view lists out all inhouse purchases
-- that are yet to be billed.
-- Here, prefix ipnb stands for Inhouse Purchases Not Billed
--------------------------------------------------------------------------------
-- Coded By : Regin T.
-- Coded On : 03-03-2010
--------------------------------------------------------------------------------
CREATE view [dbo].[vwInhousePurchasesNotBilled] as
select ipId ipnbId, iphNo ipnbNo, sum(ipAmount*mode) ipnbBalance
from (
select ipId, ipAmount, 1 mode
from vwInhousePurchasesAgainstVendors
union all
select ipbId, ipbBilledAmount, -1 mode
from vwInhousePurchasesBilled ) a
inner join loaInhousePurchaseHeader h on a.ipId=h.iphId
group by ipId, iphNo'
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturDetail]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Update_InHouseCons_ReturDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO UPDATE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnDetail  1,1,1,1,1,1.1,22,2,2,100,1.1,1.1
create PROC [dbo].[spMagnolia_Update_InHouseCons_ReturDetail]
(@shopId AS INT,@TransId AS INT,@ItemId AS INT,@ReturQty AS INT,@ReturnPQty AS INT,
@OutStrMessage as varchar(100)='''' OUT
)
AS
BEGIN
BEGIN TRY
	BEGIN TRAN
		UPDATE [LOs_InHouseCons_ReturnDetail]
		SET IHRDReturnedPqty=@ReturnPQty,IHRDReturnedQty=@ReturQty
		WHERE IHRDShopID=@shopId AND IHRDID=@TransId AND IHRDItemID=@ItemId
		SET @OutStrMessage=''Updated Successfully''
	COMMIT TRAN					
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
	SET @OutStrMessage=ERROR_MESSAGE()
	IF ERROR_NUMBER()=2627---CUSTOMISED ERROR---
	BEGIN
		SET @OutStrMessage=''Error Due to duplicated Values''
	END
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_PopulateInHosueRetunDetls]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_PopulateInHosueRetunDetls]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO UPDATE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnDetail  1,1,1,1,1,1.1,22,2,2,100,1.1,1.1
CREATE PROC [dbo].[spMagnolia_PopulateInHosueRetunDetls]
(@shopId AS INT,@TransId AS INT,@ItemId AS INT,@ReturQty AS INT,@ReturnPQty AS INT,
@OutStrMessage as varchar(100)='''' OUT
)
AS
BEGIN
BEGIN TRY
	BEGIN TRAN
---SELECT InhouseCon.*,IHRHShopID,IHRHReferenceid,IHRDItemID,isnull(ReturnedQty,0)ReturnedQty,
---isnull(ReturnedPQty,0)ReturnedPQty
SELECT * FROM
(
select whShopID,WhID,WhNo,WhDate,WdItemID,WdPqty[ArrivedPQty] from LOswriteoffheader wh
inner join LOswriteoffdetail wd on whShopID=wdShopID and WhID=WdID and WhCancelled=0
--and whShopID=1 and WhID=4
)InhouseCon
INNER JOIN
(
select IHRHShopID,IHRHID,IHRHReferenceid,IHRHNo,IHRHDate,IHRDItemID,
SUM(ISNULL(IHRDArrivedQty,0))OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID)[ReturnedQty],
SUM(ISNULL(IHRDReturnedPqty,0))OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID)[ReturnedPQty]
from LOs_InHouseCons_ReturnHeader rh
inner join LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID
and IHRHCancelled=0 --and IHRHShopID=1
)Returned
on InhouseCon.WhID=Returned.IHRHReferenceid and InhouseCon.whShopID=Returned.IHRHShopID
and InhouseCon.WdItemID=Returned.IHRDItemID
	COMMIT TRAN					
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO SAVE THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
--spMagnolia_Insert_InHouseCons_ReturnDetail  1,1,1,1,1,1.1,22,2,2,100,1.1,1.1
CREATE PROC [dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]
(@shopId AS INT,@TransId AS INT,@DetailId AS INT,@ItemID AS INT,@StrType as char(1),@ShipmentID AS INT,
@ArrivedQty AS NUMERIC(18,2),@ArrivedPQty AS NUMERIC(18,2),@costprice AS NUMERIC(18,2),@PackID AS INT,
@UnitID AS INT,@InhouseConsAccnt AS INT,@ReturPQty AS NUMERIC(18,2),@ReturQty AS NUMERIC(18,2),@OutStrMessage as varchar(100)='''' OUT
)
AS
BEGIN
BEGIN TRY
BEGIN TRAN
INSERT INTO [LOs_InHouseCons_ReturnDetail]
(IHRDShopID,IHRDID,IHRDDetailid,IHRDItemID,IHRDRetrnOrExch,
IHRDShipmentID,IHRDArrivedQty,IHRDArrivedPQty,IHRDPackID,IHRDunitID,
IHRDReturnedPqty,IHRDReturnedQty,IHRDcostprice,IHRDInhouseConsAccnt)
VALUES
(@shopId,@TransId,@DetailId,@ItemID,@StrType,
@ShipmentID,@ArrivedQty,@ArrivedPQty,@PackID,@UnitID,
@ReturPQty,@ReturQty,@costprice,@InhouseConsAccnt)
SET @OutStrMessage=''Saved Successfully''
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
SET @OutStrMessage=ERROR_MESSAGE()
IF ERROR_NUMBER()=2627---CUSTOMISED ERROR---
BEGIN
SET @OutStrMessage=''Error Due to duplicated Values''
END
END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetInHosueRetunDetls]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMagnolia_GetInHosueRetunDetls]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : NIDHEESH PV
--CREATED ON : 05/02/2011
--COMMENTS :TO GET THE DETAILS OF ITEMS WHICH ARE RETURNED AFTER DOING A INHOUSE CONSUMPTION
-- spMagnolia_GetInHosueRetunDetls  1,2,5,0,''20110716'',''20110716'',''D''
------------------------------------------------------------------------------------------
-- RefNo-1
-- Modified by : MANUNADH.U
-- Modified On : 08.08.2011
-- Purpose     : To solve the error in showing the quantity feilds of exchanged item in the
--     Transferout preview report  of inhouse excange /return
-- Solution    : Include IHRDReturnedqty,IHRDReturnedPqty,IHRDRetrnOrExch,IHRDArrivedQty,IHRDArrivedPQty
--     in the PARTITION BY case
---------------------------------------------------------------------------------
CREATE PROC [dbo].[spMagnolia_GetInHosueRetunDetls]
(@CompanyId AS INT,@shopId AS INT,@TransId AS INT,@DeptId AS INT,
@FromDate AS VARCHAR(12),@ToDate AS VARCHAR(12),@StrType AS CHAR(1)
)
--If passing ''D'' date Range will be considered (both From Date & To Date)
--If passing ''N'' date Range will not be considered (As on date is taken, only To Date is considered)
--If passing ''S'' date Range will not be considered (both From Date & To Date will not be considered/for a single transaction)
AS
BEGIN
--BEGIN TRY
-- BEGIN TRAN
SELECT DISTINCT Returned.*,InhouseCon.*,ItemDescription,ShopName,currentde.DepartmentName[FromDept],
otherde.DepartmentName[ToDept]
FROM
(
SELECT DISTINCT whShopID,WhID,WhNo,WhDate,whdepartmentid,whotherdepid--,WdPqty[ArrivedPQty]
FROM LOswriteoffheader wh
left outer JOIN  LOswriteoffdetail wd on whShopID=wdShopID and WhID=WdID and WhCancelled=0
and whtype=''I'' AND (whShopID=@shopId OR @shopId=0)
--group by   WdPqty,whShopID,WhID,WhNo,WhDate,whdepartmentid,whotherdepid
)InhouseCon
INNER JOIN LOs_InHouseCons_Returnheader RTD ON RTD.IHRHdepartmentid=whdepartmentid
INNER JOIN
(
SELECT DISTINCT IHRHShopID,IHRHID,IHRHReferenceid,IHRHNo,IHRHDate,IHRDItemID,IHRDArrivedQty,
IHRHRemarks,
--=======<<RefNo-1>>========<START>
--SUM(ISNULL(IHRDReturnedqty,0))
-- OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID)[ReturnedQty],
--SUM(ISNULL(IHRDReturnedPqty,0))
-- OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID)[ReturnedPQty],
--CASE WHEN IHRDRetrnOrExch=''E'' THEN SUM(ISNULL(IHRDArrivedQty,0))
-- OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID) ELSE 0.00 END ExchangedQty,
--CASE WHEN IHRDRetrnOrExch=''E'' THEN SUM(ISNULL(IHRDArrivedPQty,0))
-- OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID)ELSE 0.00 END ExchangedPQty
SUM(ISNULL(IHRDReturnedqty,0))
OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID,IHRDReturnedqty)[ReturnedQty],
SUM(ISNULL(IHRDReturnedPqty,0))
OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID,IHRDReturnedPqty)[ReturnedPQty],
CASE WHEN IHRDRetrnOrExch=''E'' THEN SUM(ISNULL(IHRDArrivedQty,0))
OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID,IHRDRetrnOrExch,IHRDArrivedQty) ELSE 0.00 END ExchangedQty,
CASE WHEN IHRDRetrnOrExch=''E'' THEN SUM(ISNULL(IHRDArrivedPQty,0))
OVER (PARTITION BY IHRHShopID,IHRHReferenceid,IHRDItemID,IHRHID,IHRDRetrnOrExch,IHRDArrivedPQty)ELSE 0.00 END ExchangedPQty
--=======<<RefNo-1>>========<-END->
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID --AND IHRHCancelled=0
AND (IHRHShopID=@shopId OR @shopId=0) AND (IHRHdepartmentid=@DeptId or @DeptId=0) AND (IHRHID=@TransId OR @TransId=0)
AND ((IHRHDate>=@FromDate AND IHRHDate<=@ToDate AND @StrType=''D'') OR (IHRHDate<=@ToDate AND @StrType=''N'') OR (@StrType=''S''))
)Returned
ON InhouseCon.WhID=Returned.IHRHReferenceid and InhouseCon.whShopID=Returned.IHRHShopID
--AND InhouseCon.WdItemID=Returned.IHRDItemID
INNER JOIN  ashops ON whShopID=shopid
INNER JOIN  adepartmentmaster currentde ON currentde.departmentid=whdepartmentid
INNER JOIN  adepartmentmaster otherde ON otherde.departmentid=whdepartmentid
INNER JOIN  vwItemDescription ON itemid=IHRDItemID
--group by IHRHShopID,IHRHID,IHRHReferenceid,IHRHNo,IHRHDate,IHRDItemID,IHRDArrivedQty,IHRHRemarks,
--[ReturnedQty],[ReturnedPQty],ExchangedQty,ExchangedPQty,InhouseCon.whShopID,InhouseCon.WhID,
--InhouseCon.WhNo,InhouseCon.WhDate,InhouseCon.whdepartmentid,InhouseCon.whotherdepid,
--vwItemDescription.itemdescription,ashops.ShopName,currentde.DepartmentName,otherde.DepartmentName,InhouseCon.ArrivedPQty
--   COMMIT TRAN
--END TRY
--BEGIN CATCH
-- ROLLBACK TRAN
-- SELECT ERROR_MESSAGE() AS ERROMESSAGE, ERROR_NUMBER() AS ERRORNUMBER
--END CATCH
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesQuantityValueReport]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesQuantityValueReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ==============================================================================================
-- Author: LAWRENCE M.
-- Create date: 01 April 2011
-- Description: To show the F&B Bill details in the Sales Quantity Value Report  as per the client
--     : requested format.If the added item is exist inside the selected Till No need to show seperatly.
--     : This stored procedure is used to show the Sales Quantity Value Report
-- Client     : Wings Service
-- ==============================================================================================
-- Ref No:1
-- Modified by: MANUNADH.U.
-- Modified date: 16-01-2012
-- Description: To show ''Qty / Rate'' AND change data type of date from dateime to varchar(10)
-- ==============================================================================================
--spSalesQuantityValueReport ''20111001'',''20111031'',1,3
create PROCEDURE [dbo].[spSalesQuantityValueReport]
(@FromDate AS varchar(10),@ToDate AS varchar(10),@FromTillNo AS INT,@ToTillNo AS INT)
AS
BEGIN
	--<<Ref No:1>>
	declare @From as datetime,@To as datetime
	set @From=convert(datetime,@FromDate)
	set @To=convert(datetime,@ToDate)
	--<<Ref No:1>>
CREATE TABLE #TempSalesQtyvalueRpt
(
intDishID INT,
strDishcode VARCHAR(50),
strDishName VARCHAR(250),
strUnit VARCHAR(50),
strSegment VARCHAR(50),
decRate DECIMAL(18,2),
decQty DECIMAL(18,2),
)
CREATE TABLE #TempCash
(
intCDishID INT,
decCRate DECIMAL(18,2),
decCQty DECIMAL(18,2),
intCType INT
)
CREATE TABLE #TempCredit
(
intCrDishID INT,
decCrRate DECIMAL(18,2),
decCrQty DECIMAL(18,2),
intCrType INT
)
CREATE TABLE #TempExtras
(
intDishID INT,
strDishcode VARCHAR(50),
strDishName VARCHAR(250),
strUnit VARCHAR(50),
strSegment VARCHAR(50),
decRate DECIMAL(18,2),
decQty DECIMAL(18,2),
)
CREATE TABLE #TempItemCash
(
intCDishID INT,
decCRate DECIMAL(18,2),
decCQty DECIMAL(18,2),
intCType INT
)
CREATE TABLE #TempItemCredit
(
intCrDishID INT,
decCrRate DECIMAL(18,2),
decCrQty DECIMAL(18,2),
intCrType INT
)
IF ISNULL(@FromTillNo,0)=0
BEGIN
SET @FromTillNo=0
END
IF ISNULL(@ToTillNo,0)=0
BEGIN
SET @ToTillNo=0
END
IF ISNULL(@From,0)=0
BEGIN
SET @From=0
END
IF ISNULL(@To,0)=0
BEGIN
SET @To=0
END
IF @FromTillNo<>0 AND  @ToTillNo<>0 AND @From<>0 AND @To<>0
BEGIN
	  --For select the dish details based on the segment
	  INSERT INTO #TempSalesQtyvalueRpt(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT fb_dd_dishid,fb_dd_dishcode,fb_dd_dishname,''Dish'',seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>= @From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid,seg_header_name,fb_dd_dishname,fb_dd_dishcode
	
	  --For select the Extras[Added Items] details based on the segment --fb_pd_AddedItemtype=2[Added Item]
	  INSERT INTO #TempExtras(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT itemid,ItemCode,ItemDescription+''[Extras]'',PackingTypeName,seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN apackingtype ON PackingTypeID=fb_pd_packingtypeid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid,ItemCode,ItemDescription,PackingTypeName,seg_header_name
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCash(decCQty,decCRate,intCDishID,intCType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,1
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Cash Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCash(decCQty,decCRate,intCDishID,intCType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,1
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,2
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Credit Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,2
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 AND  CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid
END
ELSE IF @FromTillNo<>0 AND  @ToTillNo<>0
BEGIN
--For select the dish details based on the segment
	  INSERT INTO #TempSalesQtyvalueRpt(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT fb_dd_dishid,fb_dd_dishcode,fb_dd_dishname,''Dish'',seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid,seg_header_name,fb_dd_dishname,fb_dd_dishcode
	
	  --For select the Extras[Added Items] details based on the segment --fb_pd_AddedItemtype=2[Added Item]
	  INSERT INTO #TempExtras(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT itemid,ItemCode,ItemDescription+''[Extras]'',PackingTypeName,seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN apackingtype ON PackingTypeID=fb_pd_packingtypeid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid,ItemCode,ItemDescription,PackingTypeName,seg_header_name
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCash(decCQty,decCRate,intCDishID,intCType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,1
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Cash Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCash(decCQty,decCRate,intCDishID,intCType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,1
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,2
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 AND till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Credit Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,2
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 AND  till_no>=@FromTillNo AND till_no<=@ToTillNo
	  GROUP BY itemid
END
IF @From<>0 AND @To<>0
BEGIN
	  --For select the dish details based on the segment
	  INSERT INTO #TempSalesQtyvalueRpt(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT fb_dd_dishid,fb_dd_dishcode,fb_dd_dishname,''Dish'',seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY fb_dd_dishid,seg_header_name,fb_dd_dishname,fb_dd_dishcode
	
	  --For select the Extras[Added Items] details based on the segment --fb_pd_AddedItemtype=2[Added Item]
	  INSERT INTO #TempExtras(intDishID,strDishcode,strDishName,strUnit,strSegment,decRate,decQty)
	  SELECT itemid,ItemCode,ItemDescription+''[Extras]'',PackingTypeName,seg_header_name,sum(fb_pd_Rate * fb_pd_reusedqty) Rate,sum(fb_pd_reusedqty) Qty
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN apackingtype ON PackingTypeID=fb_pd_packingtypeid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY itemid,ItemCode,ItemDescription,PackingTypeName,seg_header_name
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCash(decCQty,decCRate,intCDishID,intCType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,1
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Cash Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCash(decCQty,decCRate,intCDishID,intCType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,1
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=1 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY itemid
	
	  --For taking the sum of Cash Dish Qty and value based on the Segment
	  INSERT INTO #TempCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  select sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),fb_dd_dishid,2
	  from Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN fb_dishdetails ON
	  fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
	  INNER JOIN TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	  LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	  LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 and CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY fb_dd_dishid
	
	  --For taking the sum of Credit Extras[Added Items] Qty and value based on the Segment
	  INSERT INTO #TempItemCredit(decCrQty,decCrRate,intCrDishID,intCrType)
	  SELECT sum(fb_pd_reusedqty),sum(fb_pd_reusedqty*fb_pd_Rate),itemid,2
	  FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
	  fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID and poshCancelled=0 INNER JOIN aitem ON
	  itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
	  INNER JOIN dishsegmentdetail ON seg_detail_dishid=fb_pd_dishid and seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
	  INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
	  INNER JOIN Tillhistory on poshTillHistID=till_hist_id and till_id=poshTillID and till_outletid=poshShopID
	  WHERE poshbilltype <>''NP'' AND poshcashsale=0 AND  CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
	  GROUP BY itemid
END
SELECT ''Quantity and Sales Value Based on PRICE SEGMENTS'' Name,intDishID,strDishcode,strDishName,strUnit,decCQty,decCRate,decCrQty,decCrRate,strSegment,decRate,decQty,''Qty / Rate'' ColName   --<<Ref No:1>>
FROM #TempSalesQtyvalueRpt LEFT OUTER JOIN #TempCash ON intDishID=intCDishID LEFT OUTER JOIN  #TempCredit ON intCrDishID=intDishID
UNION ALL
SELECT ''Quantity and Sales Value Based on PRICE SEGMENTS'' Name,intDishID,strDishcode,strDishName,strUnit,decCQty,decCRate,decCrQty,decCrRate,strSegment,decRate,decQty,''Qty / Rate'' ColName   --<<Ref No:1>>
FROM #TempExtras LEFT OUTER JOIN #TempItemCash ON intDishID=intCDishID LEFT OUTER JOIN  #TempItemCredit ON intCrDishID=intDishID
DROP TABLE #TempSalesQtyvalueRpt
DROP TABLE #TempCash
DROP TABLE #TempCredit
DROP TABLE #TempExtras
DROP TABLE #TempItemCash
DROP TABLE #TempItemCredit
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTillEndReport]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: LAWRENCE M.
-- Create date: 14 March 2011
-- Description: For getting the Till End Stock Verification report format I have created this sp.
-- Client : Wings Service
-- =============================================
CREATE PROCEDURE [dbo].[spTillEndReport](@tillNo AS INT,@outletId AS INT)
AS
BEGIN
DECLARE @OutletName AS VARCHAR(50)
DECLARE @StartBillNo AS INT
DECLARE @EndBillNo AS INT
DECLARE @FDate AS DATETIME
DECLARE @TDate AS DATETIME
DECLARE @StartFandBNo AS VARCHAR(50)
DECLARE @EndFandBNo AS VARCHAR(50)
CREATE TABLE #TillDetails
(
OutletName VARCHAR(50),
SBillNO VARCHAR(50),
EBillNO VARCHAR(50),
FromDate DATETIME,
ToDate DATETIME,
--FromTime DATETIME,
--ToTime DATETIME
)
IF EXISTS (
SELECT *
FROM TillHistory INNER JOIN aShops ON till_outletid=shopid
where till_statusid=3 and Till_no=@tillNo)
BEGIN
SELECT @OutletName=ShopName,@FDate=till_starttime,@TDate=till_endtime
FROM TillHistory INNER JOIN aShops ON till_outletid=shopid
where till_statusid=3 and Till_no=@tillNo AND till_outletid=@outletId
END
ELSE
BEGIN
SELECT @OutletName=ShopName,@FDate=till_starttime,
@TDate=till_endtime
FROM TillHistory INNER JOIN aShops ON till_outletid=shopid
where till_statusid=2 and Till_no=@tillNo AND till_outletid=@outletId
END
SELECT @EndBillNo=till_fandbbillno
FROM TillHistory WHERE till_statusid=3 and Till_no=@tillNo AND till_outletid=@outletId
IF @EndBillNo>0
BEGIN
SELECT @EndFandBNo=poshBillNo FROM Losposfandbheader WHERE poshbillid=@EndBillNo AND poshShopID=@outletId
END
SELECT @StartBillNo=till_fandbbillno
FROM TillHistory WHERE till_statusid=2 and Till_no=@tillNo AND till_outletid=@outletId
IF @StartBillNo>0
BEGIN
SELECT @StartBillNo=min(poshbillid)  FROM TillHistory INNER JOIN Losposfandbheader ON poshTillHistID=till_hist_id and till_id=poshTillID
and till_outletid=poshShopID
where poshbillid >@StartBillNo and till_no=@tillNo and  till_outletid=@outletId
IF @StartBillNo>0
BEGIN
SELECT @StartFandBNo=poshBillNo FROM Losposfandbheader WHERE poshbillid=@StartBillNo AND poshShopID=@outletId
END
END
INSERT INTO #TillDetails(OutletName,SBillNO,EBillNO,FromDate,ToDate)
VALUES(@OutletName,@StartFandBNo,@EndFandBNo,@FDate,@TDate)
SELECT OutletName,SBillNO,EBillNO,CONVERT(VARCHAR(10),FromDate,111) FromDate,
CONVERT(VARCHAR(10),ToDate,111) ToDate,CONVERT(VARCHAR(10),FromDate,8) FTime,
CONVERT(VARCHAR(10),ToDate,8) ETime FROM #TillDetails
DROP TABLE #TillDetails
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spTillEndPriceSegment]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTillEndPriceSegment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================================
-- Author: LAWRENCE M.
-- Create date: 15 March 2011
-- Description: For getting the Till End Summary report format I have created this sp.
--     : For separating the cash and credit I have used the last column cash/credit
--     : 1-Cash ,2-Credit
-- Client   : Wings Service
-- =============================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 08 June 2011
-- Description: To add Exchange rate for converting the amount based on the company currency.
--This I changed for Till End Summary report
-- Client   : Wings Service
-- =============================================================================================
-- =============================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 30 JULY 2011
-- Description: To handle the cancelled transactions
-- Client   : Wings Service
-- =============================================================================================
CREATE PROCEDURE [dbo].[spTillEndPriceSegment](@tillNo AS INT,@outletId AS INT)
AS
BEGIN
SELECT  sum(poshBillAmount * poshExchangeRate) Amount,seg_header_id,seg_header_name,name,till_no,''Cash Sales'' COreder
FROM LosPosFAndBHeader INNER JOIN
DishSegmentHeader ON LosPosFAndBHeader.poshSegID = DishSegmentHeader.seg_header_id AND
LosPosFAndBHeader.poshCompanyID = DishSegmentHeader.seg_header_companyID INNER JOIN
TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
WHERE  poshcancelled=0 and poshbilltype <>''NP'' AND poshcashsale=1 AND till_no=@tillNo AND till_outletid=@outletId
GROUP BY seg_header_id,seg_header_name,name,till_no
UNION ALL
SELECT  sum(poshBillAmount * poshExchangeRate) Amount,seg_header_id,seg_header_name,name,till_no,''Credit Sales'' COrder
FROM LosPosFAndBHeader INNER JOIN
DishSegmentHeader ON LosPosFAndBHeader.poshSegID = DishSegmentHeader.seg_header_id AND
LosPosFAndBHeader.poshCompanyID = DishSegmentHeader.seg_header_companyID INNER JOIN
TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
LosPosFAndBHeader.poshTillID = TillHistory.till_id INNER JOIN aCompanyMaster ON CompanyID=poshCompanyID
WHERE  poshcancelled=0 and poshbilltype <>''NP'' AND poshcashsale=0 AND till_no=@tillNo AND till_outletid=@outletId
GROUP BY seg_header_id,seg_header_name,name,till_no
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSalesMarginReport]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesMarginReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ==============================================================================================
-- Author: LAWRENCE M.
-- Create date: 21 March 2011
-- Description: To show the F&B Bill details in the Sales Margin Report as per the client
--     : requested format.If the added item is exist inside the selected Till No need to show seperatly.
--     : This stored procedure is used to show the Sales Margin Report
-- Client     : Wings Service
-- ==============================================================================================
-- Modified by Aadyakumar on 16-01-2011, change date data type to varchar(10)
--spSalesMarginReport  1,3,20110901,20111101
CREATE PROCEDURE [dbo].[spSalesMarginReport] @FromTillno AS INT,@ToTillNo AS INT,
@FromDate AS varchar(10),@ToDate AS varchar(10)
AS
BEGIN
CREATE TABLE #TempMarginSale
(
intBillID INT,
strDiscode VARCHAR(50),
strDishName VARCHAR(250),
strUnit VARCHAR(50),
intQty INT,
decSP DECIMAL(18,2),
decCP DECIMAL(18,2),
decMargin DECIMAL(18,2),
decMarginPer DECIMAL(18,2)
)
IF ISNULL(@FromTillno,0)=0
BEGIN
SET @FromTillno=0
END
IF ISNULL(@ToTillNo,0)=0
BEGIN
SET @ToTillNo=0
END
IF ISNULL(@FromDate,0)=0
BEGIN
SET @FromDate=0
END
IF ISNULL(@ToDate,0)=0
BEGIN
SET @ToDate=0
END
IF @FromTillno<>0 AND  @ToTillNo<>0 AND @FromDate<>0 AND @ToDate<>0
BEGIN
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT 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_cost)* 100 MarginPer
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 ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid
where CAST(LEFT(poshBillDate,11) AS DATETIME)>=@FromDate AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=@ToDate AND till_no>=@FromTillno AND till_no<=@ToTillNo
---For Added Entry[Extras] -- Added Item fb_pd_AddedItemtype=2
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT fb_pd_processid,ItemCode ItemCode,ItemDescription +''[Extras]'' DishName,PackingTypeName,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_cost)* 100 MarginPer
FROM Losposfandbheader INNER JOIN fb_processdetail
ON fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=2 AND
fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid
INNER JOIN TILLHISTORY ON poshTillHistID=till_hist_id INNER JOIN
aitem ON ItemID=fb_pd_dishid INNER JOIN fb_DishAdds ON Fb_da_itemid=ItemID INNER JOIN
apackingtype ON PackingTypeID=fb_da_packingtypeid
where CAST(LEFT(poshBillDate,11) AS DATETIME)>=@FromDate AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=@ToDate AND till_no>=@FromTillno AND till_no<=@ToTillNo
END
ELSE IF  @FromDate<>0 AND @ToDate<>0
BEGIN
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT 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_cost)* 100 MarginPer
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 ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid
where CAST(LEFT(poshBillDate,11) AS DATETIME)>=@FromDate AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=@ToDate
---For Added Entry[Extras]
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT fb_pd_processid,ItemCode ItemCode,ItemDescription +''[Extras]'' DishName,PackingTypeName,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_cost)* 100 MarginPer
FROM Losposfandbheader INNER JOIN fb_processdetail
on fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=2 AND
fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid
INNER JOIN TILLHISTORY ON poshTillHistID=till_hist_id INNER JOIN
aitem ON ItemID=fb_pd_dishid INNER JOIN fb_DishAdds ON Fb_da_itemid=ItemID INNER JOIN
apackingtype ON PackingTypeID=fb_da_packingtypeid
WHERE CAST(LEFT(poshBillDate,11) AS DATETIME)>=@FromDate AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=@ToDate
END
ELSE IF @FromTillno<>0 AND  @ToTillNo<>0
BEGIN
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT 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_cost)* 100 MarginPer
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 ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid
WHERE till_no>=@FromTillno AND till_no<=@ToTillNo
---For Added Entry[Extras]
INSERT INTO #TempMarginSale(intBillID,strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer)
SELECT fb_pd_processid,ItemCode ItemCode,ItemDescription +''[Extras]'' DishName,PackingTypeName,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_cost)* 100 MarginPer
FROM Losposfandbheader INNER JOIN fb_processdetail
on fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=2 AND
fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid
INNER JOIN TILLHISTORY ON poshTillHistID=till_hist_id INNER JOIN
aitem ON ItemID=fb_pd_dishid INNER JOIN fb_DishAdds ON Fb_da_itemid=ItemID INNER JOIN
apackingtype ON PackingTypeID=fb_da_packingtypeid
WHERE till_no>=@FromTillno AND till_no<=@ToTillNo
END
SELECT strDiscode,strDishName,strUnit,intQty,decSP,decCP,decMargin,decMarginPer
FROM #TempMarginSale ORDER BY intBillID
DROP TABLE #TempMarginSale
END' 
END
GO
/****** Object:  View [dbo].[vwItemSplit]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSplit]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 12/12/02, 17/10/2003, 02/12/2003
-- Modified by		: leo, Hariharan R, Kishore
-- Comments		: v3, Added detail itemcode
--                      : Added UnitCode, SplitUnitCode
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwItemSplit] AS
select ish.ishid ,ish.ishno ,ish.ishgodownid,ish.ishdate,ish.ishremarks,
a1.itemdescription splititem,a2.itemdescription item ,ish.ishactualqty,
isd.isdqty,a.itemrate,ash.sShipmentNO,ah.ahArrivalNo,au.UnitName, au.UnitCode,
ausp.unitname SplitUnitName, ausp.UnitCode SplitUnitCode,
a1.code, asp.itemcode detItemCode
from LoiItemSplitHeader ish left outer join LoiItemSplitdetail isd
on ish.ishid=isd.isdid
and ish.ishgodownid=isd.isdgodownid
left outer join loiarrivalheader ah
on ish.ishgodownid = ah.ahLocalGodownID
and ish.ishArrivalID = ah.ahArrivalID left outer join ashipment ash
on ish.ishshipmentid = ash.sShipmentID
left outer join aitem a on ish.ishSplititemid = a.itemid
left outer join aitem asp on isd.isditemid = asp.itemid
left outer join vwitemdescription a1 on ish.ishSplititemid = a1.itemid
left outer join vwitemdescription a2 on isd.isditemid = a2.itemid
left outer join aunit au on a.unitsid = au.UnitID
left outer join aunit ausp on asp.unitsid = ausp.UnitID'
GO
/****** Object:  View [dbo].[vwTotallcpayable]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotallcpayable]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 25/01/03
-- Modified by   : leo
-- comments	: included the departmentid in the result
CREATE view [dbo].[vwTotallcpayable] as
select vw.pohcompanyid companyid, vw.phdepartmentid, pohLCNumber, max(pohLCdueon) lcdueon,
max(lcaccountdesc) accountdesc, max(symbol) symbol, sum(amount - paid) amount  from
vwlcoutstandingage vw
group by pohcompanyid, vw.phdepartmentid, pohLCNumber having sum(amount - paid) > 0'
GO
/****** Object:  View [dbo].[vwtoolsallocation]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtoolsallocation]'))
EXEC dbo.sp_executesql @statement = N'
--comments : crated for tools allcoation transaction report
--venki 040803
CREATE view [dbo].[vwtoolsallocation] as
select h.alchShopid,s.shopname,h.alchid,h.alchdate,h.alchno,d.alcdtoolsid,f.assetname,d.alcdtechnicianid,p.spername,
alcdfrom,alcdto,h.alchtechnicianid
from LosserToolsallocationheader h,ashops s,
LosserToolsallocationDetail d left outer join fixedasset f on FixedAssetID=alcdtoolsid,
asalespersonmaster p where h.alchid=d.alcdid
and h.alchCompanyId=d.alcdCompanyId and s.shopid=h.alchShopid and h.alchShopid=d.alcdShopid
and h.alchCancelled=0
and h.alchshopid=d.alcdShopid and d.alcdtechnicianid=p.sperid'
GO
/****** Object:  View [dbo].[vwTillhistory]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTillhistory]'))
EXEC dbo.sp_executesql @statement = N'
--Created by Jothish
/*create  view vwTillhistory as
select till_th_tillid,  till_th_tillname + ''_'' +    convert(varchar(5),till_starttime,108)+ ''-'' +  convert(varchar(5),till_endtime,108) TillName ,till_endtime,till_hist_id
,isnull(till_no,0)till_no from TillHistory th ,TillHeader ti where   till_starttime is not  null and till_endtime is not null
and till_id=till_th_tillid and till_statusid=3  */
CREATE view [dbo].[vwTillhistory] as
select till_th_tillid,  till_th_tillname + ''_'' + convert(varchar(6),till_no) TillName,
till_endtime,till_hist_id,till_no ,till_outletid  shopid from TillHistory th ,TillHeader ti where   till_starttime is not  null and till_endtime is not null
and till_id=till_th_tillid and till_statusid=3'
GO
/****** Object:  View [dbo].[vwTill]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTill]'))
EXEC dbo.sp_executesql @statement = N'
--Created by Jothish
CREATE view [dbo].[vwTill] as
select  till_th_tillid HistoryID ,till_th_tillname TillName,till_id TillID ,cast(till_no as varchar)+''-''+till_th_tillname TillNo,ti.till_th_outletid outletid from
TillHistory th ,TillHeader ti where   till_starttime is not  null-- and till_endtime is not null
and till_id=till_th_tillid and ti.till_th_outletid=th.till_outletid and  till_statusid=2 and
till_no is not null  and till_no not in (
select till_no from TillHistory where till_statusid=3 and till_no is not null )'
GO
/****** Object:  View [dbo].[vwBills]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBills]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
/****** Object:  View [dbo].[vwbillpopulategrid]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillpopulategrid]'))
EXEC dbo.sp_executesql @statement = N'
CREATE    view [dbo].[vwbillpopulategrid] as
-- =============================================
-- Added by:  Praveen
-- Create date: 10th August 2010
-- Description: To populate Bill Grid
-- =============================================
SELECT lph.poshshopid,lph.poshcompanyid,lph.poshbillid, lph.poshBillNo ,
lph.poshBillDate,lph.poshBillAmount,case lph.poshcancelled when 1 then
isnull(lph.poshRecModifyUser,'''') +'' - ''+isnull(cast(lph.updatetime as char),'''')  when 0
then isnull(vw.aUser,'''') end CancelEdit,Case lph.poshCancelled When 1 then ''Yes'' else ''No''
End Cancelled,  Case lph.poshposted When 1 then ''Yes'' else ''No'' End Posted,
Case lph.closebill When 1 then ''No'' else ''Yes'' End Closedbill
From vwCancelEditUser vw ,LosPosFAndBHeader lph
INNER JOIN aShops s ON
lph.poshShopID = s.ShopID AND lph.poshCompanyID = s.companyid
Where lph.poshbillid=vw.poshbillid and lph.poshShopID=vw.poshShopID'
GO
/****** Object:  View [dbo].[vwTransactionListAson15062011]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransactionListAson15062011]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on         : 11/12/02
-- Modified by   : leo
-- Comments  : v3
----------------------------------------------------------------------------------------------
-- Modified on          : 22/12/2002
-- Modified by          : Hariharan R
-- Comment              : Added rexporting
----------------------------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 13/06/2003
-- Comments  : AccountDesc column added
--                (on comparison with V2)
----------------------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 27/06/2003
-- Comments             : The bug in ServiceInvoice corrected
----------------------------------------------------------------------------------------------
-- Modified by          : Kishore, Hariharan R
-- Modified on          : 13/11/2003, 10/01/2004
-- Comments             : Added Service Booking, Service Income and Parts sold in service
--                        transactions
--   : acustomermaster link removed from loscallbookingheader
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by          : Nidheesh P V
-- Modified on          : 18/11/2010
-- Comments             : Added F&B
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwTransactionListAson15062011] AS
--pos
select poshBillId, poshShopId, poshBillDate, poshBillNo,
poshbillamount * poshexchangerate Total,
poshBillAmount * poshDepExRate DepTotal,
poshcancelledremarks Remarks, ''POS'' Type,
poshCustomerName, AccountDesc
from losposheader, aAccountMaster
where poshcancelled = 0
and poshCashAccid = accountid
and poshCompanyID = CompanyId
union all
--credit invoice
select ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks, ''Credit Invoice'' type, CustomerName, ''''
from losinvoiceheader, acustomermaster
where ihcancelled = 0
and ihcustomerid = customerid
and ihproforma = 0
and ihtype = ''i''
union all
--------------------------------------------------
/*
--special invoice
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1
union all
*/
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Cash'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 and   IhBankcashAccID is not null  --Cash Invocie
and ihNoofOCDetails=0 and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Credit'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 and IhBankcashAccID is null--Credit invocie
and ihNoofOCDetails=0 and -- ToConfirm not Return Before Despatch
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Return Before Despatch'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 and   IhBankcashAccID is not null  --Cash Invocie
and ihNoofOCDetails<>0 and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Return After Despatch'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 --and   IhBankcashAccID is not null  --Cash Invocie
and ihNoofOCDetails=0
and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1)> 0
--and ihinvoiceno=''08/DSD/SW/RAD/6''
--select * from losspecialinvoiceheader where ihinvoiceno=''08/DSD/SW/RAD/6''
union all
-------------------------------------------------------
-- serviceinvoice
select aih.aiinvoiceid, aih.aiShopId, aih.aiinvoicedate, aih.aiinvoiceno,
(sum(aid.siamount * aid.siServiceQty) - (isnull(aih.aidiscount, 0))) * min(aiexchangerate) total,
(sum(aid.siamount * aid.siServiceQty) - (isnull(aih.aidiscount, 0))) * min(aiDepExRate) DepTotal,
airemarks remarks, ''Service Invoice'' type, CustomerName, isnull(AccountDesc,'''')
from losaccountsinvoiceheader aih left outer join losserviceinvoicedetails aid
on aih.aiShopId=aid.siShopId
and aih.aiinvoiceid=aid.siinvoiceid
left outer join aAccountMaster a
on aih.aiBankCashID = a.accountid, acustomermaster
where aih.aicancelled = 0  and aih.aiproforma=0
and aicustomerid = customerid
group by aih.aiShopId, aih.aiinvoicedate,aih.aiinvoiceno,
aih.aiinvoiceid, AccountDesc, aiexchangerate, aih.aidiscount, airemarks, CustomerName
union ALL
--Hp invoice
SELECT hpqhQuotationID,hpqhShopID,hpqhQuotationDate,hpqhQuotationNo,
hpqhInstPrice,hpqhInstPrice,
hpqhRemarks remarks,''HP Invoice'' type,hpCustNAme,''''
FROM loshpInvoiceHeader,loshpCustomerDetails
WHERE hpqhCustomerID=hpCustID AND hpqhtype=''I''
AND hpqhCancel=0
UNION all
--receipt in shop
select drid, drShopId, drdate, drno,
dramount * drexchangerate total,
dramount * drDepExRate DepTotal,
drremarks remarks,''Receipts'' Type ,CustomerName, ''''
from losdummyreceiptheader, acustomermaster
where drcancelled=0 and drcustomerid = customerid
UNION ALL
SELECT hprhReceiptID,hprhShopID,hprhReceiptDate,hprhReceiptNo,
hprhReceiptAmount,hprhReceiptAmount,
hprhRemarks remarks,''HP Receipts'' TYPE,hpCustName,''''
FROM loshpReceiptHeader,loshpCustomerdetails
WHERE hprhCustomerid=hpCustID AND hprhCancel=0
union all
--payments
select phpaymentid, phShopId,phpaymentdate,phpaymentno,
phamount * phExchangeRate total,
phamount * phDepExRate DepTotal,
phremarks remarks ,''Payments'' type,  --bb
vendorname, ''''
from lospaymentvoucherheader, avendormaster
where phcancelled=0 and phvendorid=vendorid
union all
-- goods return note header
select GrnhGoodsreturnnoteID, grnhShopId, GrnhGoodsreturnnoteDate, GrnhGoodsreturnnoteNO,
sum(d.GRNDunitprice * grnhExchangeRate)  total,
sum(d.GRNDunitprice * grnhdepExRate)  DepTotal,
GrnhRecommendedby remarks,        --bb
''Goods Return'' as Type, c.CustomerName, ''''
from losgoodsreturnnoteheader h, LosGoodsReturnNoteDetail d,
acustomermaster c where h.GrnhGoodsreturnnoteID = d.GRNDReturnNoteID and
h.grnhShopId=d.grndShopId and h.grnhcustomerid = c.customerid group by
grnhShopId, GrnhGoodsreturnnoteDate, GrnhGoodsreturnnoteNO,GrnhGoodsreturnnoteID,
c.CustomerName,
GrnhRecommendedby,grnhExchangeRate
union all
--exchange
select sehexchangeid, sehShopId, sehexchangedate, sehExchangeno,
sehexchangebillamount * sehexchangerate total,
sehexchangebillamount * sehDepExRate DepTotal,
sehremarks remarks, ''Exchange'' type, h.sehExchangerName, AccountDesc
from losposexchangeheader h, aAccountMaster a
where sehcancelled = 0
and sehCashAccID = a.accountid
and sehCompanyId = a.CompanyId
union all
--local purchase
--hari010817 removed lpditemquantity * since item amount is stored in lpditemunitprice
select lphbillid, lphShopId, lphBillDate , lphBillno,
sum(lpdItemUnitPrice * lphexchangerate) total,
sum(lpdItemUnitPrice * lphDepExRate) DepTotal,
lphremarks remarks, ''Local Purchase'' type, v.vendorname,
isnull(AccountDesc, '''')
from loslocalpurchaseheader h left outer join aAccountMaster a
on lphBankcashAccID = a.AccountID, loslocalpurchasedetail d, avendormaster v
where lphcancelled = 0
and lphvendorid = v.vendorid
and h.lphbillid = d.lpdbillid
and h.lphShopId = d.lpdShopId
group by lphShopId, lphBillDate, lphBillno, lphbillid,
AccountDesc, lphexchangerate,
lphremarks, v.vendorname
union all
--ReExporting
select rehExportid, rehShopId, rehExportdate, rehExportNo,
rehExportamount * rehexchangerate total,
rehExportamount * rehDepExRate DepTotal,
rehremarks remarks,''Re-Export To Customer'' type, CustomerName, ''''
from losExportHeader,
acustomermaster
where rehcancelled = 0
and rehcustomerid = customerid
and rehproforma = 0
and rehtype =''i''
union all
--Reexporting
select rehExportid, rehShopId, rehExportdate, rehExportNo,
rehExportamount * rehexchangerate total,
rehExportamount * rehDepExRate DepTotal,
rehremarks remarks, ''Re-Export To Vendor''  type, VendorName, ''''
from losExportHeader,
avendormaster
where rehcancelled = 0
and rehvendorid = vendorid
and rehproforma = 0
and rehtype = ''i''
Union All
-- Booking Advance
select serCallBkhid, serCallBkhshopid, serCallBkhdate, serCallBkhno,
serBookAdvanceAmount * serbookhcmpexrate Total,
serBookAdvanceAmount * serbookhresexrate DepTotal,
serBookhRemarks Remarks, ''Service Booking Advance'' Type, sercallBkhRecvdFrom CustomerName, a.AccountDesc
from  losServiceBookingHeader serBookh,
aAccountMaster a,  losCallBookingHeader serCallBkh
where serBookhCashAcc = a.AccountId
And serBookhId = serCallBkhId
And serBookhShopId = serCallBkhshopid
And serBookAdvanceAmount <> 0
And serCallBkhcancelled = 0
Union All
-- Service income
select serinvhId, serinvhShopId, serinvhDate, serinvNo,
serinvhServiceAmt * serinvhcmpexrate Total,
--serinvhServiceAmt * serinvhresexrate DepTotal,
serinvhServiceAmt * seinvhdepexrate DepTotal,
serinvhRemarks Remarks, ''Service Income'' Type, serinvhcustname, a.AccountDesc
From losServiceInvHeader serinvh Left Outer Join aAccountMaster a
On serinvhcashacc = a.AccountId
Where serinvhServiceAmt <> 0
And serinvhCancelled = 0
Union All
-- Parts Replaced In Service
select serinvhId, serinvhShopId, serinvhDate, serinvNo,
serinvhPartsAmt * serinvhcmpexrate Total,
--serinvhPartsAmt * serinvhresexrate DepTotal,
serinvhPartsAmt * seinvhdepexrate DepTotal,
serinvhRemarks Remarks, ''Parts Replaced In Service'' Type, serinvhcustname, a.AccountDesc
from  losServiceInvHeader serinvh Left Outer Join aAccountMaster a
On serinvhcashacc = a.AccountId
Where serinvhPartsAmt <> 0
And serinvhCancelled = 0
union all
--F&B--
select poshBillID,h.poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshBillNo,
COnvert(numeric(18,2),(poshbillamount))amount,
COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)Depamount,
poshremarks remarks,''F&B'' As type,poshcustomername,AccountDesc  --bb
from  losposfandbheader h
inner join aaccountmaster on poshCashAccID=accountid and CompanyID=poshCompanyID
where poshCancelled=0
and poshCashSale=1
union all
select poshBillID,h.poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshBillNo,
COnvert(numeric(18,2),(poshbillamount))amount,
COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)Depamount,
poshremarks remarks,''F&B'' As type,poshcustomername,poshcustomername  --bb
from  losposfandbheader h
where poshCancelled=0
and poshCashSale=0
--F&B--'
GO
/****** Object:  View [dbo].[vwTransactionList]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransactionList]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on         : 11/12/02
-- Modified by   : leo
-- Comments  : v3
----------------------------------------------------------------------------------------------
-- Modified on          : 22/12/2002
-- Modified by          : Hariharan R
-- Comment              : Added rexporting
----------------------------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 13/06/2003
-- Comments  : AccountDesc column added
--                (on comparison with V2)
----------------------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 27/06/2003
-- Comments             : The bug in ServiceInvoice corrected
----------------------------------------------------------------------------------------------
-- Modified by          : Kishore, Hariharan R
-- Modified on          : 13/11/2003, 10/01/2004
-- Comments             : Added Service Booking, Service Income and Parts sold in service
--                        transactions
--   : acustomermaster link removed from loscallbookingheader
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by          : Nidheesh P V
-- Modified on          : 18/11/2010
-- Comments             : Added F&B
------------------------------------------------------------------------------------------					  		
-- Modified by : Bijesh.B
-- Date        : 18/06/2011
-- RefNo       : RefNo-2
-- Comments    : PD Cheque feature added
------------------------------------------------------------------------------------------					  		
-- Modified by : Bijesh.B
-- Date        : 04/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        : 29/07/2011
-- RefNo       : RefNo-4
-- Comments    : Bugsheet-Need to show Return Before despatch-credit details
------------------------------------------------------------------------------------------
-- Modified by : Nidheesh P V
-- Date        : 31/08/2011
-- RefNo       : RefNo-5
-- Comments    : Corrected the Service booking advance date in the section ''Service Booking Advance''.
------------------------------------------------------------------------------------------
-- Modified by : Benzigar S D
-- Date        : 28/10/2011
-- RefNo       :
-- Comments    : Added prefix for GrnhGoodsreturnnoteDate
-------------------------------------------------------------------------------
CREATE view [dbo].[vwTransactionList] AS
--pos
select poshBillId, poshShopId, poshBillDate, poshBillNo,
poshbillamount * poshexchangerate Total,
poshBillAmount * poshDepExRate DepTotal,
poshcancelledremarks Remarks, ''POS'' Type,
poshCustomerName, AccountDesc
from losposheader, aAccountMaster
where poshcancelled = 0
and isnull(PosPostDate,0)<>1  --RefNo-2
and poshCashAccid = accountid
and poshCompanyID = CompanyId
--RefNo-2  start --------------
union all
--pos After deducting PD cheque amt
select ph.poshBillId, ph.poshShopId, poshBillDate, poshBillNo,
Convert(numeric(18,2), (poshBillAmount - PDCheque.PosBankAmount) * poshexchangerate) As Total,
Convert(numeric(18,2),(poshBillAmount - PDCheque.PosBankAmount) * poshdepexrate)  As DepTotal,
poshcancelledremarks Remarks, ''POS'' Type,
poshCustomerName, AccountDesc
from losposheader ph, aAccountMaster,losPosChequeDetails PDCheque
where poshcancelled = 0
and isnull(PosPostDate,0)=1
and PDCheque.PoshBillID = ph.poshBillID and PDCheque.PoshShopID = ph.poshShopID
and poshCashAccid = accountid
and poshCompanyID = CompanyId
union all
-- pos PD Cheque Amt only
select PH.poshBillId, PH.poshShopId, poshBillDate, poshBillNo,
Convert(numeric(18,2), CHQ.PosBankAmount * poshexchangerate) As Total,
Convert(numeric(18,2), CHQ.PosBankAmount * poshdepexrate)  As DepTotal,
poshcancelledremarks Remarks, ''PD CHEQUE'' Type,
poshCustomerName, AccountDesc
from losposheader PH, aAccountMaster,losPosChequeDetails CHQ
--,ahqPostDatedChequeDetails PdChqDet   --RefNo-3
where poshcancelled <> 1  and
PH.poshBillID = CHQ.PoshBillID  AND isnull(PH.PosPostDate,0)=1
AND PH.poshShopID = CHQ.PoshShopID
--and PdChqDet.PoshBillID = PH.poshBillID AND isnull(PdChqDet.Cancel,0)=0 --RefNo-3
and poshChequeAccID = accountid
and poshCompanyID = aAccountMaster.CompanyId
--RefNo-2  ends --------------
union all
--credit invoice
select ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks, ''Credit Invoice'' type, CustomerName, ''''
from losinvoiceheader, acustomermaster
where ihcancelled = 0
and ihcustomerid = customerid
and ihproforma = 0
and ihtype = ''i''
union all
--------------------------------------------------
/*
--special invoice
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1
union all
*/
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Cash'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 and   IhBankcashAccID is not null  --Cash Invocie
and ihNoofOCDetails=0 and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Credit'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 and IhBankcashAccID is null--Credit invocie
and ihNoofOCDetails=0 and -- ToConfirm not Return Before Despatch
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Return Before Despatch'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1
--and   IhBankcashAccID is not null  --Cash Invocie   -- RefNo-4  commented
and ihNoofOCDetails<>0 and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1) = 0
union all
select
ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,
ihinvoiceamount * ihexchangerate total,
ihinvoiceamount * ihDepExRate DepTotal,
ihremarks remarks,''Special Invoice-Return After Despatch'' type, CustomerName, isnull(accountdesc,'''')
from losspecialinvoiceheader left outer join aAccountMaster ac
on IhBankcashAccID = ac.accountid
and ihCompanyid = ac.CompanyId, acustomermaster
where ihcancelled=0 and ihcustomerid=customerid
and ihtransfinished=1 --and   IhBankcashAccID is not null  --Cash Invocie
and ihNoofOCDetails=0
and
(select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId  and idratetype = 1)> 0
--and ihinvoiceno=''08/DSD/SW/RAD/6''
--select * from losspecialinvoiceheader where ihinvoiceno=''08/DSD/SW/RAD/6''
union all
-------------------------------------------------------
-- serviceinvoice
select aih.aiinvoiceid, aih.aiShopId, aih.aiinvoicedate, aih.aiinvoiceno,
(sum(aid.siamount * aid.siServiceQty) - (isnull(aih.aidiscount, 0))) * min(aiexchangerate) total,
(sum(aid.siamount * aid.siServiceQty) - (isnull(aih.aidiscount, 0))) * min(aiDepExRate) DepTotal,
airemarks remarks, ''Service Invoice'' type, CustomerName, isnull(AccountDesc,'''')
from losaccountsinvoiceheader aih left outer join losserviceinvoicedetails aid
on aih.aiShopId=aid.siShopId
and aih.aiinvoiceid=aid.siinvoiceid
left outer join aAccountMaster a
on aih.aiBankCashID = a.accountid, acustomermaster
where aih.aicancelled = 0  and aih.aiproforma=0
and aicustomerid = customerid
group by aih.aiShopId, aih.aiinvoicedate,aih.aiinvoiceno,
aih.aiinvoiceid, AccountDesc, aiexchangerate, aih.aidiscount, airemarks, CustomerName
union ALL
--Hp invoice
SELECT hpqhQuotationID,hpqhShopID,hpqhQuotationDate,hpqhQuotationNo,
hpqhInstPrice,hpqhInstPrice,
convert(varchar(250),hpqhRemarks)remarks,''HP Invoice'' type,convert(varchar(250),hpCustNAme),''''
FROM loshpInvoiceHeader,loshpCustomerDetails
WHERE hpqhCustomerID=hpCustID AND hpqhtype=''I''
AND hpqhCancel=0
UNION all
--receipt in shop
select drid, drShopId, drdate, drno,
dramount * drexchangerate total,
dramount * drDepExRate DepTotal,
drremarks remarks,''Receipts'' Type ,CustomerName, ''''
from losdummyreceiptheader, acustomermaster
where drcancelled=0 and drcustomerid = customerid
UNION ALL
SELECT hprhReceiptID,hprhShopID,hprhReceiptDate,hprhReceiptNo,
hprhReceiptAmount,hprhReceiptAmount,
convert(varchar(250),hprhRemarks)remarks,''HP Receipts'' TYPE,convert(varchar(250),hpCustName) ,''''  --bb
FROM loshpReceiptHeader,loshpCustomerdetails
WHERE hprhCustomerid=hpCustID AND hprhCancel=0
union all
--payments
select phpaymentid, phShopId,phpaymentdate,phpaymentno,
phamount * phExchangeRate total,
phamount * phDepExRate DepTotal,
phremarks remarks ,''Payments'' type,
vendorname, ''''
from lospaymentvoucherheader, avendormaster
where phcancelled=0 and phvendorid=vendorid
union all
-- goods return note header
select GrnhGoodsreturnnoteID, grnhShopId, h.GrnhGoodsreturnnoteDate, GrnhGoodsreturnnoteNO,
sum(d.GRNDunitprice * grnhExchangeRate)  total,
sum(d.GRNDunitprice * grnhdepExRate)  DepTotal,
GrnhRecommendedby remarks,
''Goods Return'' as Type, c.CustomerName, ''''
from losgoodsreturnnoteheader h, LosGoodsReturnNoteDetail d,
acustomermaster c where h.GrnhGoodsreturnnoteID = d.GRNDReturnNoteID and
h.grnhShopId=d.grndShopId and h.grnhcustomerid = c.customerid group by
grnhShopId, h.GrnhGoodsreturnnoteDate, h.GrnhGoodsreturnnoteNO,h.GrnhGoodsreturnnoteID,
c.CustomerName,
GrnhRecommendedby,grnhExchangeRate
union all
--exchange
select sehexchangeid, sehShopId, sehexchangedate, sehExchangeno,
sehexchangebillamount * sehexchangerate total,
sehexchangebillamount * sehDepExRate DepTotal,
sehremarks remarks, ''Exchange'' type, h.sehExchangerName, AccountDesc
from losposexchangeheader h, aAccountMaster a
where sehcancelled = 0
and sehCashAccID = a.accountid
and sehCompanyId = a.CompanyId
union all
--local purchase
--hari010817 removed lpditemquantity * since item amount is stored in lpditemunitprice
select lphbillid, lphShopId, lphBillDate , lphBillno,
sum(lpdItemUnitPrice * lphexchangerate) total,
sum(lpdItemUnitPrice * lphDepExRate) DepTotal,
lphremarks remarks, ''Local Purchase'' type, v.vendorname,
isnull(AccountDesc, '''')
from loslocalpurchaseheader h left outer join aAccountMaster a
on lphBankcashAccID = a.AccountID, loslocalpurchasedetail d, avendormaster v
where lphcancelled = 0
and lphvendorid = v.vendorid
and h.lphbillid = d.lpdbillid
and h.lphShopId = d.lpdShopId
group by lphShopId, lphBillDate, lphBillno, lphbillid,
AccountDesc, lphexchangerate,
lphremarks, v.vendorname
union all
--ReExporting
select rehExportid, rehShopId, rehExportdate, rehExportNo,
rehExportamount * rehexchangerate total,
rehExportamount * rehDepExRate DepTotal,
rehremarks remarks,''Re-Export To Customer'' type, CustomerName, ''''
from losExportHeader,
acustomermaster
where rehcancelled = 0
and rehcustomerid = customerid
and rehproforma = 0
and rehtype =''i''
union all
--Reexporting
select rehExportid, rehShopId, rehExportdate, rehExportNo,
rehExportamount * rehexchangerate total,
rehExportamount * rehDepExRate DepTotal,
rehremarks remarks, ''Re-Export To Vendor''  type, VendorName, ''''
from losExportHeader,
avendormaster
where rehcancelled = 0
and rehvendorid = vendorid
and rehproforma = 0
and rehtype = ''i''
Union All
-- Booking Advance
select serCallBkhid, serCallBkhshopid,serbookadvancedate, --serCallBkhdate, ---RefNo-5
serCallBkhno, serBookAdvanceAmount * serbookhcmpexrate Total,
serBookAdvanceAmount * serbookhresexrate DepTotal,
serBookhRemarks Remarks, ''Service Booking Advance'' Type, sercallBkhRecvdFrom CustomerName, a.AccountDesc
from  losServiceBookingHeader serBookh,
aAccountMaster a,  losCallBookingHeader serCallBkh
where serBookhCashAcc = a.AccountId
And serBookhId = serCallBkhId
And serBookhShopId = serCallBkhshopid
And serBookAdvanceAmount <> 0
And serCallBkhcancelled = 0
Union All
-- Service income
select serinvhId, serinvhShopId, serinvhDate, serinvNo,
serinvhServiceAmt * serinvhcmpexrate Total,
--serinvhServiceAmt * serinvhresexrate DepTotal,
serinvhServiceAmt * seinvhdepexrate DepTotal,
serinvhRemarks Remarks, ''Service Income'' Type, serinvhcustname, a.AccountDesc
From losServiceInvHeader serinvh Left Outer Join aAccountMaster a
On serinvhcashacc = a.AccountId
Where serinvhServiceAmt <> 0
And serinvhCancelled = 0
Union All
-- Parts Replaced In Service
select serinvhId, serinvhShopId, serinvhDate, serinvNo,
serinvhPartsAmt * serinvhcmpexrate Total,
--serinvhPartsAmt * serinvhresexrate DepTotal,
serinvhPartsAmt * seinvhdepexrate DepTotal,
serinvhRemarks Remarks, ''Parts Replaced In Service'' Type, serinvhcustname, a.AccountDesc
from  losServiceInvHeader serinvh Left Outer Join aAccountMaster a
On serinvhcashacc = a.AccountId
Where serinvhPartsAmt <> 0
And serinvhCancelled = 0
union all
--F&B--
select poshBillID,h.poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshBillNo,
COnvert(numeric(18,2),(poshbillamount))amount,
COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)Depamount,
poshremarks remarks,''F&B'' As type,poshcustomername,AccountDesc
from  losposfandbheader h
inner join aaccountmaster on poshCashAccID=accountid and CompanyID=poshCompanyID
where poshCancelled=0
and poshCashSale=1
union all
select poshBillID,h.poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshBillNo,
COnvert(numeric(18,2),(poshbillamount))amount,
COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)Depamount,
poshremarks remarks,''F&B'' As type,poshcustomername,poshcustomername
from  losposfandbheader h
where poshCancelled=0
and poshCashSale=0
--F&B--'
GO
/****** Object:  View [dbo].[vwposgrnamount]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposgrnamount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwposgrnamount    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwposgrnamount    Script Date: 14/09/2002 12:48:07 AM ******/
/****** Object:  View dbo.vwposgrnamount    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwposgrnamount    Script Date: 20/11/2001 9:59:05 AM ******/
/****** Object:  View dbo.vwposgrnamount    Script Date: 17/11/2001 9:21:49 PM ******/
CREATE view [dbo].[vwposgrnamount] as
select grnh.GrnCompanyID, grnh.grnhShopid, grnh.GrnhGoodsreturnnoteID,
isnull(sum(round((grnd.grndUnitPrice),2)),0) as grnamt from
LOsGoodsReturnNoteHeader grnh left outer join LosGoodsReturnNoteDetail grnd
on grnh.GrnhGoodsreturnnoteID = grnd.GRNDReturnNoteID and grnh.grnhShopid = grnd.GRNDShopid
left outer join LOsInvoiceDetail invd on grnh.GrnhInvoiceID = invd.idinvoiceid and
grnh.grnhShopid = invd.idshopid
where invd.iditemid = grnd.grnditemid
group by grnh.GrnCompanyID, grnh.grnhShopid, grnh.GrnhGoodsreturnnoteID'
GO
/****** Object:  View [dbo].[vwPosExchangeDetailsWithMarginWithOutGST]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsWithMarginWithOutGST]'))
EXEC dbo.sp_executesql @statement = N'
--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 [dbo].[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
/****** Object:  View [dbo].[vwPosExchangeDetailsWithMargin]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsWithMargin]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[vwPosExchangeDetailsWithMargin]   as
select
sehExchangeID,shopname, sehshopid, sehexchangedate, convert(numeric(18,2),
sum(sedunitprice )) cashsales, convert(numeric(18,2),
sum(sedunitprice * sehdepexrate)) dcashsales,convert(numeric(18,2),
sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedquantity) margin, convert(numeric(18,2), sum(sedunitprice* sehdepexrate)) -
sum(sedcostprice * sedquantity) * sehdepexrate dmargin, convert(numeric(18,2),
sum(sedunitprice * sehexchangerate )) - sum(sedcostprice * sedquantity)
* sehexchangerate  cmargin,departmentname, sehdepartmentid departmentid
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,2),
-sum(sedunitprice )) cashsales, convert(numeric(18,2),
-sum(sedunitprice * sehdepexrate)) dcashsales, convert(numeric(18,2),
-sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedExchangeQty)) margin, -(convert(numeric(18,2), sum(sedunitprice )) -
sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin, -(convert(numeric(18,2),
sum(sedunitprice )) - sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,
departmentname, sehdepartmentid departmentid
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
/****** Object:  View [dbo].[vwPosExchangeDetailsGSTSepartely]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetailsGSTSepartely]'))
EXEC dbo.sp_executesql @statement = N'
--Created by : Bijesh.B
--Date       : 05-10-2012
--------------------------------------------------------------------
create View [dbo].[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
/****** Object:  View [dbo].[vwPosExchangeDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosExchangeDetails]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View [dbo].[vwPosExchangeDetails] As
Select sehexchangeid,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 cash,''c''  As transtype, sehdepartmentid departmentid
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,2),-Sum(sedunitprice)) As amount,
COnvert(numeric(18,2),-Sum(sedunitprice) * sehdepexrate) As damount,
COnvert(numeric(18,2),-Sum(sedunitprice) * sehexchangerate) As camount, 1,
''c'' As transtype, sehdepartmentid  departmentid
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'
GO
/****** Object:  View [dbo].[vwsalespersonperformance]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalespersonperformance]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------
--Last Modified on  : 22/12/02
--Modified by  : Hariharan R
--Comments  : v3
--Added the reexport transaction details
-----------------------------------------------------------------------------
--Modified on   : 07/08/2003
--Modified by  : R Harikrishnan
--Comments  : Credit Invoice other charges changes
--Modified on   : 07/08/2003
--Modified by  : R Harikrishnan
--Comments  : Credit Invoice other charges changes
--Modified by  : venki181203
--Comments  : specialinvoice transaction finsihed chking
--Verified by       : Hariharan
--Verified Date      : 03/05/2004 (verified From Client DB)
-----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwsalespersonperformance] AS
SELECT
sperid, ISNULL(Spername,''GENERAL'') salesperson, poshbillno, poshbilldate, poshbillid,
poshshopid, posditemid, posdquantity, posdpquantity, CONVERT(NUMERIC(18,2),posdunitprice)
salesvalue, CONVERT(NUMERIC(18,2),(posdunitprice*poshdepexrate)) dsalesvalue,
CONVERT(NUMERIC(18,2), (posdunitprice*poshexchangerate)) csalesvalue,
CONVERT(NUMERIC(18,2), (posdcostprice * posdquantity)) costvalue,
CONVERT(NUMERIC(18,2), (posdcostprice * posdquantity * poshdepexrate)) dcostvalue,
CONVERT(NUMERIC(18,2), (posdcostprice * posdquantity * poshexchangerate)) ccostvalue,
CONVERT(NUMERIC(18,2),(posdunitprice - (posdcostprice * posdquantity))) profit,
CONVERT(NUMERIC(18,2), (posdunitprice - (posdcostprice * posdquantity))* poshdepexrate) dprofit,
CONVERT(NUMERIC(18,2), (posdunitprice  - (posdcostprice * posdquantity))* poshexchangerate) cprofit,
vw.itemdescription, shopname,''CASH'' invType,ISNULL(poshcustomerid,-1) CustomerID,
CASE ISNULL(poshcustomerid,-1) WHEN -1 THEN ''General Customers'' ELSE cm.CustomerName END CustomerName
FROM
losposheader h
LEFT OUTER JOIN asalespersonmaster sm ON poshsalespersonid=Sperid
LEFT OUTER JOIN aCustomerMaster cm ON  h.poshcustomerid=cm.CustomerID,
losposdetail d, vwitemdescription vw, ashops s
where
h.poshbillid = d.posdbillid AND h.poshshopid = d.posdshopid AND
h.poshcancelled=0 AND posditemid = vw.itemid AND h.poshshopid = s.shopid
UNION ALL
SELECT
sperid, ISNULL(Spername,''GENERAL'') salesperson, ihinvoiceno, ihinvoicedate,
ihinvoiceid,  ihshopid, iditemid, idquantity, idpquantity,
CONVERT(NUMERIC(18,2),(ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0))) salesvalue,
CONVERT(NUMERIC(18,2),(ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0))*ihdepexrate) dsalesvalue,
CONVERT(NUMERIC(18,2),(ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0))*ihexchangerate) csalesvalue,
CONVERT(NUMERIC(18,2), ISNULL((idcostprice * idquantity ),0)) costvalue,
CONVERT(NUMERIC(18,2), ISNULL((idcostprice * idquantity ),0) * ihdepexrate) dcostvalue,
CONVERT(NUMERIC(18,2), ISNULL((idcostprice * idquantity ),0) * ihexchangerate) ccostvalue,
CONVERT(NUMERIC(18,2),((ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0)) -
ISNULL((idcostprice * idquantity ),0))) profit,
CONVERT(NUMERIC(18,2), ((ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0)) -
(ISNULL((idcostprice * idquantity ),0)))* ihdepexrate) dprofit,
CONVERT(NUMERIC(18,2), ((ISNULL(d.idunitprice,0)+ISNULL(ocd.ioAmount,0)) -
(ISNULL((idcostprice * idquantity ),0))) * ihexchangerate) cprofit, vw.itemdescription, shopname,''CREDIT'' invType,
ihCustomerID CustomerID,cm.CustomerName
FROM
losinvoiceheader h
LEFT OUTER JOIN asalespersonmaster sm
ON ihsalespersonid=Sperid
LEFT OUTER JOIN aCustomerMaster cm ON  h.ihCustomerID=cm.CustomerID
LEFT OUTER JOIN losinvoicedetail d
ON h.ihinvoiceid = d.idinvoiceid AND h.ihshopid = d.idshopid
LEFT OUTER JOIN losInvoiceOC ocd
ON h.ihshopid = ocd.ioshopid AND h.ihinvoiceid = ocd.ioinvoiceid ,
vwitemdescription vw, ashops s
WHERE
ihtype =''i'' AND h.ihcancelled=0 AND iditemid = vw.itemid AND idshopid = shopid
UNION ALL
SELECT
sperid, ISNULL(Spername,''GENERAL'') salesperson, ihinvoiceno, ihinvoicedate,
ihinvoiceid,  ihshopid, iditemid, idquantity, idpquantity,
CONVERT(NUMERIC(18,2), idunitprice) salesvalue,
CONVERT(NUMERIC(18,2), idunitprice* ihdepexrate) dsalesvalue,
CONVERT(NUMERIC(18,2), idunitprice* ihexchangerate) csalesvalue,
CONVERT(NUMERIC(18,2), idcostprice * reqqty) costvalue,
CONVERT(NUMERIC(18,2), idcostprice * reqqty * ihdepexrate) dcostvalue,
convert(numeric(18,2), idcostprice * reqqty * ihexchangerate) ccostvalue,
convert(numeric(18,2), (idunitprice - (idcostprice * reqqty))) profit,
convert(numeric(18,2), (idunitprice  - (idcostprice * reqqty)) * ihdepexrate) dprofit,
convert(numeric(18,2), (idunitprice  - (idcostprice * reqqty)) * ihexchangerate) cprofit,
vw.itemdescription, shopname,CASE IhCashInvoice WHEN 1 THEN ''CASH'' WHEN 0 THEN ''CREDIT'' END invType,
ISNULL(IhCustomerID,-1) CustomerID,CASE ISNULL(IhCustomerID,-1) WHEN -1 THEN ''General Customer'' ELSE cm.CustomerName END CustomerName
from
losspecialinvoiceheader h
left outer join asalespersonmaster sm
on ihsalespersonid=Sperid
LEFT OUTER JOIN aCustomerMaster cm ON  h.IhCustomerID=cm.CustomerID
, losspecialinvoicedetail d,
vwitemdescription vw, ashops s
where
h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and
h.ihcancelled=0 and idratetype=0 and iditemid = vw.itemid and idshopid = shopid
and ihtransfinished=1
union all
select
sperid, isnull(Spername,''GENERAL'') salesperson, ihinvoiceno, ihinvoicedate,
ihinvoiceid,  ihshopid, iditemid, idquantity, idpquantity,
convert(numeric(18,2), -(idunitprice)) salesvalue,
convert(numeric(18,2), -(idunitprice* ihdepexrate)) dsalesvalue,
convert(numeric(18,2), -(idunitprice* ihexchangerate)) csalesvalue,
convert(numeric(18,2), idcostprice *  reqqty) costvalue,
convert(numeric(18,2), idcostprice *  reqqty * ihdepexrate) dcostvalue,
convert(numeric(18,2), idcostprice *  reqqty * ihexchangerate) ccostvalue,
convert(numeric(18,2), -((idunitprice) - (idcostprice * (-1 * reqqty)))) profit,
convert(numeric(18, 2), -((idunitprice) - (idcostprice * (-1 * reqqty)))*ihdepexrate) dprofit,
convert(numeric(18,2), -((idunitprice) - (idcostprice * (-1 * reqqty)))*ihexchangerate) cprofit,
vw.itemdescription, shopname,CASE IhCashInvoice WHEN 1 THEN ''CASH'' WHEN 0 THEN ''CREDIT'' END invType,
ISNULL(IhCustomerID,-1) CustomerID,CASE ISNULL(IhCustomerID,-1) WHEN -1 THEN ''General Customer'' ELSE cm.CustomerName END CustomerName
from
losspecialinvoiceheader h
left outer join asalespersonmaster sm
on ihsalespersonid=Sperid
LEFT OUTER JOIN aCustomerMaster cm ON  h.IhCustomerID=cm.CustomerID,
losspecialinvoicedetail d,vwitemdescription vw, ashops s
where
h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and
h.ihcancelled=0 and idratetype=1 and iditemid = vw.itemid and ihshopid = shopid
and  ihtransfinished=1
union all
select
sperid, isnull(Spername,''GENERAL'') salesperson, sehexchangeno, sehexchangedate,
sehexchangeid,  sehshopid, seditemid, sedquantity, sedpquantity,
convert(numeric(18,2), sedunitprice) salesvalue, convert(numeric(18,2), sedunitprice * sehdepexrate) dsalesvalue,
convert(numeric(18,2), (sedunitprice * sehexchangerate)) csalesvalue,
convert(numeric(18,2), sedcostprice * sedquantity) costvalue,
convert(numeric(18,2), sedcostprice * sedquantity * sehdepexrate) dcostvalue,
convert(numeric(18,2), sedcostprice * sedquantity * sehexchangerate) ccostvalue,
convert(numeric(18,2), (sedunitprice) - (sedcostprice * sedquantity)) profit,
convert(numeric(18,2), ((sedunitprice) - (sedcostprice * sedquantity))*sehdepexrate) dprofit,
convert(numeric(18,2), ((sedunitprice) - (sedcostprice * sedquantity))*sehexchangerate) cprofit,
vw.itemdescription, shopname,''CASH'' invType, -1 CustomerID,ISNULL(sehExchangerName,''General Customer'') CustomerName
from
losposexchangeheader h
left outer join asalespersonmaster sm
on sehsalespersonid=Sperid, losposexchangedetail d,
vwitemdescription vw, ashops s
where
h.sehexchangeid = d.sedexchangeid and h.sehshopid = d.sedshopid and
h.sehcancelled=0 and d.sedbillorexchange = ''E'' and seditemid = vw.itemid and
sehshopid = shopid
union all
select
sperid, isnull(Spername,''GENERAL'') salesperson, sehexchangeno, sehexchangedate,
sehbillid, sehshopid, seditemid, sedExchangeQty, sedExchangePQty,
convert(numeric(18,2), -sedunitprice ) salesvalue,
convert(numeric(18,2), -(sedunitprice * sehdepexrate)) dsalesvalue,
convert(numeric(18,2), -(sedunitprice * sehexchangerate)) csalesvalue,
convert(numeric(18,2), -(sedcostprice * sedExchangeQty)) costvalue,
convert(numeric(18,2), -(sedcostprice * sedExchangeQty* sehdepexrate)) dcostvalue,
convert(numeric(18,2), -(sedcostprice * sedExchangeQty* sehexchangerate)) ccostvalue,
convert(numeric(18,2), -((sedunitprice) - (sedcostprice * sedExchangeQty))) profit,
convert(numeric(18,2), -((sedunitprice) - (sedcostprice * sedExchangeQty))*sehdepexrate) dprofit,
convert(numeric(18,2), -((sedunitprice) -
(sedcostprice * sedExchangeQty))*sehexchangerate) cprofit,
vw.itemdescription, shopname,''CASH'' invType,-1 CustomerID,ISNULL(sehExchangerName,''General Customer'') CustomerName
from
losposexchangeheader h
left outer join asalespersonmaster sm
on sehsalespersonid=Sperid,
losposexchangedetail d , vwitemdescription vw, ashops s
where
h.sehexchangeid = d.sedexchangeid and h.sehshopid = d.sedshopid and
h.sehcancelled=0 and d.sedbillorexchange = ''B'' and seditemid = vw.itemid and
sedshopid = shopid
union all
-- REXPORTING TRANSACTION DETAILS
select
sperid, isnull(Spername,''GENERAL'') salesperson, rehExportno, rehExportdate,
rehExportid,  rehshopid, reditemid, redquantity, redpquantity,
convert(numeric(18,2), redunitprice)
salesvalue, convert(numeric(18,2), (redunitprice*rehdepexrate)) dsalesvalue,
convert(numeric(18,2), (redunitprice*rehexchangerate))
csalesvalue, convert(numeric(18,2), redcostprice * redquantity )costvalue,
convert(numeric(18,2), redcostprice * redquantity * rehdepexrate) dcostvalue,
convert(numeric(18,2), redcostprice * redquantity * rehexchangerate) ccostvalue,
convert(numeric(18,2), (redunitprice) - (redcostprice * redquantity)) profit,
convert(numeric(18,2), ((redunitprice) - (redcostprice * redquantity))*rehdepexrate)
dprofit, convert(numeric(18,2), ((redunitprice) - (redcostprice * redquantity)) *rehexchangerate) cprofit,
vw.itemdescription, shopname, CASE rehCashInvoice WHEN 1 THEN ''CASH'' WHEN 0 THEN ''CREDIT'' END invType,
ISNULL(rehcustomerid,-1) CustomerID,CASE ISNULL(rehcustomerid,-1) WHEN -1 THEN ''General Customer'' ELSE cm.CustomerName END CustomerName
from
losexportheader h
left outer join asalespersonmaster sm on rehsalespersonid=Sperid
LEFT OUTER JOIN aCustomerMaster cm ON  h.rehcustomerid=cm.CustomerID,
losExportDetail d,vwitemdescription vw, ashops s
where
h.rehExportID = d.redExportID and h.rehshopid = d.redshopid and rehtype =''i'' and
h.rehcancelled=0 and reditemid = vw.itemid and redshopid = shopid'
GO
/****** Object:  View [dbo].[vwSalesHistory]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesHistory]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view returns all sales details.
-- This sales is displayed in Item Properties interface.
--------------------------------------------------------------------------------
-- Coded By: Regin T.
-- Coded On: 10-05-2010
--------------------------------------------------------------------------------
CREATE view [dbo].[vwSalesHistory] AS
-- 1 CASH SALES (POS)
select
''Cash Sales'' as Type, poshShopID ShopId, poshbillID TransId, poshBillNo TransNo,
poshBilldate Date, updatetime [Time],
0 CustomerId, poshCustomerName CustomerName,
posditemid ItemId, posdquantity Quantity,
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) UnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) dUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) cUnitPrice,
ShopName, s.DepartmentID DepartmentId
from
losposdetail inner join losposheader
on poshBillid = posdBillid and poshShopid = posdshopid
inner join aShops s on poshShopID=s.ShopId
where
poshCancelled = 0
union all
-- 2 CREDIT SALES
select
''Credit Sales'' as Type, IhShopid ShopId, ihInvoiceID TransId, ihInvoiceNo TransNo,
ihInvoicedate Date, updatetime [Time],
ihCustomerID CustomerId, c.CustomerName,
iditemid ItemId, idquantity Quantity,
convert(numeric(18,2), (idUnitPrice / idquantity)) UnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,
ShopName, s.DepartmentID
from
losinvoiceheader ih inner join losinvoicedetail invd
on ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid
inner join aCustomerMaster c on ih.ihCustomerID=c.CustomerID
inner join aShops s on ihShopID=s.ShopId
where
IHCANCELLED = 0 and ihproforma = 0 and ihtype = ''I''
union all
--3 GOODS EXCHANGE
select
''Goods Exchange'' as Type, sehShopID, sehExchangeID, sehExchangeNo,
sehExchangeDate, updatetime,  0 CustomerId, sehExchangerName,
seditemid, sedquantity Quantity,
convert(numeric(18,2),(sedUnitPrice / sedquantity) ) UnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehDepExRate) dUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehExchangeRate) cUnitPrice,
ShopName, s.DepartmentID
from
losposexchangeheader inner join losposexchangedetail
on sedExchangeid = sehExchangeID and sedShopID = sehShopid
inner join aShops s on sehShopID=s.ShopId
where
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
union all
-- 4 GODOWN DESPATCH SALES
select
case IhCashInvoice when 1 then ''Godown Despatch Sales (Cash)'' else
''Godown Despatch Sales (Credit)'' end as Type,
IhShopid, ihInvoiceID, ihInvoiceNo,
ihInvoicedate Date, updatetime [Time],
IhCustomerID CustomerId, c.CustomerName,
iditemid , reqqty Quantity,
convert(numeric(18,2),(idUnitPrice / reqqty)) UnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
ShopName, s.DepartmentID
from
losspecialinvoicedetail inner join losspecialinvoiceheader
on ihInvoiceid = idInvoiceid  and ihshopid = idshopid
inner join aShops s on idShopid=s.ShopId
left outer join aCustomerMaster c on IhCustomerID=c.CustomerId
where
IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0
and IhTransFinished = 1 and ihNoofOCDetails=0'
GO
/****** Object:  View [dbo].[vwsalesdetail]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesdetail]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By : Benzigar S D
-- Created On : 29-11-2008
CREATE VIEW [dbo].[vwsalesdetail] AS
--pos
select poshBillId, poshShopId, poshBillDate, poshBillNo,
posditemid,code,itemdescription,posdpquantity,posdunitprice totalamount,posdunitprice/posdpquantity unitprice,posdactualunitprice,posdcostprice,
(posdactualunitprice*posdpquantity)- posdunitprice TotalDiscount,
(((posdactualunitprice*posdpquantity)- posdunitprice)/(posdactualunitprice*posdpquantity))*100 Discper,
poshcancelledremarks Remarks,
poshCustomerName, AccountDesc
from losposheader, aAccountMaster,losposdetail,vwitemdescription
where poshcancelled = 0
and poshCashAccid = accountid
and poshCompanyID = CompanyId
and poshBillId=posdbillid
and poshShopId=posdshopid
and itemid=posditemid
Union all
--credit invoice
select ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,iditemid,
code,itemdescription,
idPQuantity,idunitprice totalamount,idunitprice/idPQuantity unitprice,idActualUnitPrice,idcostprice,
(idactualunitprice*idpquantity)- idunitprice TotalDiscount,
case when idactualunitprice*idpquantity<> 0 then(((idactualunitprice*idpquantity)- idunitprice)/(idactualunitprice*idpquantity))*100  end Disper,
ihremarks remarks,CustomerName, ''Credit Invoice'' AccountDesc
from losinvoiceheader, acustomermaster,losinvoicedetail,vwitemdescription
where ihcancelled = 0
and ihcustomerid = customerid
and ihproforma = 0
and ihtype = ''i''
and ihinvoiceid=idinvoiceid
and ihshopid=idshopid
and itemid=iditemid
Union all
--exchange
select sehexchangeid, sehShopId, sehexchangedate, sehExchangeno,seditemid,
code,itemdescription,sedPQuantity,sedunitprice totalamount,
sedunitprice/sedPQuantity unitprice, sedActualUnitPrice,sedcostprice,
(sedactualunitprice*sedpquantity)- sedunitprice TotalDiscount,
case when sedactualunitprice*sedpquantity<> 0 then(((sedactualunitprice*sedpquantity)- sedunitprice)/(sedactualunitprice*sedpquantity))*100  end Disper,
sehremarks remarks, h.sehExchangerName, AccountDesc
from losposexchangeheader h, aAccountMaster a,losposexchangedetail e,vwitemdescription
where sehcancelled = 0
and sehCashAccID = a.accountid
and sehCompanyId = a.CompanyId
and sehexchangeid=sedexchangeid
and sedBillorExchange=''E''
and itemid=seditemid'
GO
/****** Object:  View [dbo].[vwpdcreceipts]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpdcreceipts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpdcreceipts    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 28/12/02
--Modified by 		: dheena
--Comments 		: add depid
CREATE view [dbo].[vwpdcreceipts] as
select jh.companyid, journaldate receiptdate, referenceno receiptno, ''op'' cbreferenceno,
''opening'' receivedfrom, left(remarks,patindex(''%;%'',remarks)-1)
as chequedetails, jd.amount , chequedate, jd.accountid bankcashaccountid,
case cancel when 1 then ''Yes'' else ''No'' end cancelled,jd.DepartmentID deptid  from moaJournalHeader jh,
moajournaldetails jd  where
jh.companyid = jd.companyid and jh.journalid = jd.journalid and
financialid =0 and type =''R'' and journaldate <> chequedate and jd.journalcredit = 0
union all
select CompanyID, ReceiptDate, ReceiptNo, cbreferenceno, ReceivedFrom, chequedetails,
amount, chequedate, BankCashAccountID,
case cancelled when 1 then ''Yes'' else ''No'' end cancelled,DepartmentID
from receiptvoucherheader where chequedate > receiptdate'
GO
/****** Object:  View [dbo].[vwSelingPriceAfterEachShipment]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSelingPriceAfterEachShipment]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on 		: 12/12/02
-- Modified by		: leo
-- Comments		: v3
------------------------------------------------------------------------------------
-- Modified by		: Kishore
-- Modified on		: 11/06/2003
-- Comments		: Removed the cancelled entries
-- 			  (On comparison with v2)
------------------------------------------------------------------------------------
-- Modified by		: venki
-- Modified on		: 18/08/2003
-- Comments		: added departmentid
----------------------------------------------
CREATE VIEW [dbo].[vwSelingPriceAfterEachShipment] AS
SELECT bh.pbhBillID, isnull(pbdsellingPrice,0) sellingprice, cd.cdItemQuantity,
cd.cdNewItemCostPrice, ai.ItemCode, vid.ItemDescription, pbddetailid,
isnull(pbdwholesalePrice,0) wholesaleprice,
isnull(pbddiscountPrice,0) discountprice ,pbhdepartmentid
FROM acompanymaster a,
acurrencymaster c, LOspPurchaseBillHeader bh, loacostingdetail cd, aitem ai,
vwitemdescription vid, LOspPurchaseBillDetail bd,
loacostingheader ch
where bh.pbhbillid = bd.pbdbillid
and cd.cdcostingid = ch.chcostingid
and cditemid = ai.itemid
and cditemid = pbditemid
and pbhbillid = chbillid
and ai.itemid = vid.itemid
and a.companyid = c.companyid
and a.currencyid = c.currencyid
and a.companyid = pbhcompanyid
and bh.pbhCancelled = 0
and ch.chCancelled = 0'
GO
/****** Object:  View [dbo].[vwshipmentexpense]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentexpense]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentexpense    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshipmentexpense] as
select po.pohpono, po.pohpodate, s.sshipmentno, sshipmentdate,cad.cadaccountid,
ch.chcostingid, chcostingdate, cad.caddescription,
cad.cadcostingtype, cad.cadamount, c.symbol from loacostingheader ch,
loacostingaccountdetails cad,ashipment s, aaccountmaster a, acurrencymaster c,
lopurchaseorderheader po, losppurchasebillheader pbh
where ch.chcostingid = cad.cadcostingid and ch.chcompanyid = cad.cadcompanyid
and s.sbillid=ch.chbillid and cad.cadaccountid = a.accountid and
cad.cadcompanyid= a.companyid and a.companyid=c.companyid and a.currencyid=c.currencyid
and ch.chbillid=pbh.pbhbillid and pbh.pbhpoid=po.pohpoid and ch.chcancelled =0'
GO
/****** Object:  View [dbo].[vwPurchaseOrderTracking3]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderTracking3]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwPurchaseOrderTracking3] as
select vw.pohpoid,vw.pohshopid, case when vw.ShopRequetNO is not null then vw.ShopRequetNO else mos.Grhrequestno end as ShopRequetNO,
vw.HQRequestNo,vw.QuotationNO,vw.PrePurchaseNo
from vwPurchaseOrderTracking2 vw left outer join mosgoodsrequestheader mos
on vw.pohrequestid=mos.grhrequestid and vw.pohshopid =mos.grhshopid'
GO
/****** Object:  View [dbo].[vwCreditInvoice_BillWise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditInvoice_BillWise]'))
EXEC dbo.sp_executesql @statement = N'
Create  view [dbo].[vwCreditInvoice_BillWise] as
---Created by :Jyothish.SR
--- Date :12.04.2012
--- CreditInvoice-BillWise Report
select lh.ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,CustomerName,ihCustomerID,ItemDescription,PackingTypeName,idPQuantity,idQuantity
,idUnitPrice,lphBillID, lphBillNo,lphBillDate,VendorName,lpdItemQuantity,lpdItemUnitPrice from losInvoiceheader lh ,losInvoiceDetail lt
,LosLocalPurchaseHeader dh , LosLocalPurchaseDetail dt ,acustomermaster c ,aVendorMaster v ,aitem it ,aPackingType p where  lh.ihShopID=lt.idShopID
and ihCancelled=0 and ihType=''I'' and dh.lphBillID=dt.lpdBillID and lt.idBillID is not null and dh.lphBillID=dt.lpdBillID and dh.lphCancelled=0
and lt.idBillID=dh.lphBillID and lh.ihInvoiceID=lt.idInvoiceID and dh.lphShopID=dt.lpdShopID and lt.idItemID=dt.lpdItemID
and c.CustomerID=ihCustomerID   and v.VendorID=lphVendorID and it.ItemID=idItemID and p.PackingTypeID=idPackingTypeID'
GO
/****** Object:  View [dbo].[vwCostSheet_summery]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostSheet_summery]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : MANUNADH.U
-- Create date : 25/05/2011
-- Description : To CREATE the Shipment wise price sheet detail report [Ticket-SBN-169211]
--   --  jyothish corrected 10062011
create VIEW [dbo].[vwCostSheet_summery] AS
SELECT distinct bh.pbhBillID, isnull(bd.pbdsellingPrice,0) sellingprice, (cd.cdItemQuantity/ cd1.Quantity  )cdItemQuantity,cd.cdNewItemCostPrice,
ai.ItemCode, vid.ItemDescription, bd.pbddetailid,isnull(bd.pbdwholesalePrice,0) wholesaleprice,
isnull(bd.pbddiscountPrice,0) discountprice ,bh.pbhdepartmentid
,p.packingtypename ,(isnull(sd.Sellingprice,0))  sellingpriceNew
,cast(cast(( ( cd.cdNewItemCostPrice/
(
select exdS.SellingRate from apackagesettings pS
INNER JOIN aAccountMaster amS ON pS.inventoryid=amS.AccountID
INNER JOIN exchangeratedetail exdS ON exdS.CurrencyID=amS.CurrencyID
)
)* ( select SellingRate from exchangeratedetail where
CurrencyID=isnull(cm.CurrencyId,cm2.CurrencyId)
)
)* cd1.Quantity as decimal(18,2)) as varchar(20)) ''CostPrice''
FROM acompanymaster a,acurrencymaster c, LOspPurchaseBillHeader bh, loacostingdetail cd, aitem ai,
vwitemdescription vid, LOspPurchaseBillDetail bd,loacostingheader ch
,apackingtype p,aitempackingdetail pd
left outer join  losshopitemshipmentdetail sd on pd.itemid=sd.itemid and pd.packingtypeid= sd.packingtypeid
left Outer Join aCurrencyMaster cm on  sd.Currencyid = cm.CurrencyId , aCurrencyMaster cm2
,aPackingTypeCapacityDetail cd1
where bh.pbhbillid = bd.pbdbillid and cd.cdcostingid = ch.chcostingid and cditemid = ai.itemid
and cditemid = pbditemid and pbhbillid = chbillid and ai.itemid = vid.itemid and a.companyid = c.companyid
and a.currencyid = c.currencyid and a.companyid = pbhcompanyid and bh.pbhCancelled = 0 and ch.chCancelled = 0
and cditemid=pd.itemid and p.packingtypeid=pd.packingtypeid
and cd1.packingtypeid = pd.packingtypeid  and cd1.unitsid = ai.unitsid  and pd.Active = 1
and bd.pbdPackingTypeID=pd.PackingTypeID'
GO
/****** Object:  View [dbo].[vwCostSheet]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostSheet]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author  : MANUNADH.U
-- Create date : 25/05/2011
-- Description : To CREATE the Shipment wise price sheet detail report [Ticket-SBN-169211]
--  jyothish corrected 10062011
CREATE  VIEW [dbo].[vwCostSheet] AS
SELECT distinct bh.pbhBillID, isnull(bd.pbdsellingPrice,0)*cd1.Quantity  sellingprice, (cd.cdItemQuantity/ cd1.Quantity  )cdItemQuantity,cd.cdNewItemCostPrice,
ai.ItemCode, vid.ItemDescription, bd.pbddetailid,isnull(bd.pbdwholesalePrice,0)*cd1.Quantity wholesaleprice,
isnull(bd.pbddiscountPrice,0) *cd1.Quantity  discountprice ,bh.pbhdepartmentid
,p.packingtypename ,(isnull(sd.Sellingprice,0))  sellingpriceNew
, cd.cdNewItemCostPrice*cd1.Quantity ''CostPrice''
FROM acompanymaster a,acurrencymaster c, LOspPurchaseBillHeader bh, loacostingdetail cd, aitem ai,
vwitemdescription vid, LOspPurchaseBillDetail bd,loacostingheader ch
,apackingtype p,aitempackingdetail pd
left outer join  losshopitemshipmentdetail sd on pd.itemid=sd.itemid and pd.packingtypeid= sd.packingtypeid
left Outer Join aCurrencyMaster cm on  sd.Currencyid = cm.CurrencyId , aCurrencyMaster cm2
,aPackingTypeCapacityDetail cd1
where bh.pbhbillid = bd.pbdbillid and cd.cdcostingid = ch.chcostingid and cditemid = ai.itemid
and cditemid = pbditemid and pbhbillid = chbillid and ai.itemid = vid.itemid and a.companyid = c.companyid
and a.currencyid = c.currencyid and a.companyid = pbhcompanyid and bh.pbhCancelled = 0 and ch.chCancelled = 0
and cditemid=pd.itemid and p.packingtypeid=pd.packingtypeid
and cd1.packingtypeid = pd.packingtypeid  and cd1.unitsid = ai.unitsid  and pd.Active = 1'
GO
/****** Object:  View [dbo].[vwCostingDifference]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCostingDifference]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwCostingDifference] as
---Created by  :jyothish
----Date :02-12-2012
select h.chCostingID,chCostingNo,chCostingDate,av.ItemID,ItemDescription,av.OldStock ExistingStock ,dt.cdOldItemCostPrice ExistingCostPrice,cdItemQuantity NewStock,
dt.cdCostingPrice NewCostPrice,cdNewItemCostPrice AvgCostPrice from losCosAvlStock av ,loacostingheader h , loacostingdetail dt ,
aitem  at where h.chCostingID=dt.cdCostingID and h.chCancelled=0 and
av.CostingID=h.chCostingID  and at.ItemID=dt.cdItemID and av.ItemID=dt.cdItemID and av.OldStock<0'
GO
/****** Object:  View [dbo].[vwquotationtracking3]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwquotationtracking3]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwquotationtracking3] as
select a.pohpoid,
vwq.ShopRequetNO as ShopRequetNO,vwq.hqrequestno as HQRequestNo,
vwq.QuotationNo as QuotationNo from loPurchaseOrderHeader a
left outer join vwquotationtracking2 vwq on a.pohpoid=vwq.pohpoid and a.pohshopid=vwq.pohshopid'
GO
/****** Object:  View [dbo].[vwreceiptCLbankwise]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptCLbankwise]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwreceiptCLbankwise    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on  : 10/12/02
--Modified by   : dheena
--Comments   : add depid
CREATE view [dbo].[vwreceiptCLbankwise] as
select rh.companyid, receiptid, receiptdate, receiptno, cbreferenceno,
receivedfrom, bankcashaccountid, amount, case when cancelled =1 then ''Yes''
else ''No'' end as cancelled, cancelledremarks, a.accountdesc,rh.departmentid ,ChequeDetails
from receiptvoucherheader rh, aaccountmaster a where rh.companyid = a.companyid and
bankcashaccountid = a.accountid'
GO
/****** Object:  View [dbo].[vwReceiptsCheckList]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptsCheckList]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 10/12/02
-- Modified by 		: dheena
-- Comments 		: add depid
---------------------------------------------------------------------------------------
-- Modified on		: 31/08/2003
-- Modified by          : Kishore
-- Comments             : Added UpdateTime field
--Verified by 	    	: Hariharan
--Verified Date     	: 04/05/2004 (verified From Dev Server(Fies))
---------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwReceiptsCheckList] AS
select rh.CompanyID, rh.ReceiptID, ReceiptNo, ReceiptDate, Receivedfrom,
case when (rh.customerid is not null)
then ''Customer''
when (rh.vendorid is not null) then ''Vendor''
else ''Others'' end as caption,
case when (rh.customerid is not null)
then cm.customername
when (rh.vendorid is not null)
then vm.vendorname else ''N/A'' end as custorven,
bacc.accountdesc,
remarks, chequedetails as chequeno, posted,
cancelled, amount, cbreferenceno as bankrefno,
exchangerate, receipttype as paymentmode,
customeramount, dacc.accountdesc debitaccount,
debitamount, dm.departmentname,rh.departmentid, UpdateTime
from ReceiptVoucherHeader rh left outer join aaccountmaster dacc
on rh.companyid = dacc.companyid
and rh.debitaccountid = dacc.accountid
left outer join acustomermaster cm
on rh.companyid = cm.companyid
and rh.customerid = cm.customerid
left outer join avendormaster vm
on rh.companyid = vm.companyid
and rh.vendorid = vm.vendorid, aaccountmaster bacc,
adepartmentmaster dm
where rh.companyid = bacc.companyid
and rh.bankcashaccountid = bacc.accountid
and rh.companyid = dm.companyid
and rh.departmentid = dm.departmentid'
GO
/****** Object:  View [dbo].[vwreceiptswithcontrolaccs]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptswithcontrolaccs]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on	: 10/12/2002
--comments	: included 2 fields BankCashAccountID, exchangerates
-- added maindepid <> h.departmentid condition to avoid control accounts
--for the current department
--last modified : venki 280803
--comments	: chking done for refering single receipt in multiple dept
--last modified : venki 030903
--comments	: added cancel chking , multi department population enabled
CREATE view [dbo].[vwreceiptswithcontrolaccs] as
select  h.receiptno, h.receiptid, h.receiptDate, h.Remarks, dep.departmentname,
maindepid, h.companyid, d.accountid, a.accountdesc, d.amount, 1 credit, BankCashAccountID,
exchangerates from adepcontrolaccounts ca, adepartmentmaster dep,
aaccountmaster a, receiptvoucherheader h,ReceiptVoucherCreditDetails d
where ca.companyid = d.companyid and ca.controlaccid = d.accountid  and ca.companyid=d.companyid
and d.accountid = a.accountid and d.companyid=a.companyid and h.companyid=dep.companyid
--and refdcnid is null
and h.departmentid = dep.departmentid
and maindepid <> h.departmentid  and  h.cancelled=0 and
h.receiptid = d.receiptid and ca.maindepid  not in
(select Journaltransheader.departmentid from
Journaltransheader where receiptid = h.Receiptid and cancelled = 0
union all
select phdepartmentid from ahqPaymentVoucherHeader where refreceiptid = h.Receiptid and
cancelled = 0
union all
select dcndepartmentid from debitcreditnote where
parentreceiptid = h.Receiptid and dcncancelled = 0
union all
select 0)'
GO
/****** Object:  View [dbo].[VWLOSSPECIALINVOICEDETAIL]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWLOSSPECIALINVOICEDETAIL]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------
/*
CREATED BY : PRASANTH JOSEPH
CREATED ON : 01-08-2009
CREATED REASON : IN RETURN AFTER DESPATCH, ITS IDENTIFICATION BIT ''IDRATETYPE'' ONLY IN DETAIL TABEL
SO NEED TO ADD GROUP BY CLAUSE.
*/
----------------------------------------------------------------------------
CREATE VIEW [dbo].[VWLOSSPECIALINVOICEDETAIL]
AS
SELECT
IDINVOICEID,IDSHOPID,IDRATETYPE
FROM
LOSSPECIALINVOICEDETAIL
GROUP BY
IDINVOICEID,IDSHOPID,IDRATETYPE'
GO
/****** Object:  View [dbo].[VwMaintenceContractOutletDtls]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwMaintenceContractOutletDtls]'))
EXEC dbo.sp_executesql @statement = N'
--modify By 	: venki , Hariharan R
--modified date :181203 , 26/12/2003
--COmments	:chking specialinvoice trans finished
CREATE view [dbo].[VwMaintenceContractOutletDtls] as
select companyid,shopid,shopprocessid,shopnos,type,a.itemid,serialno,Itemdescription
,itemcode,part_code,Processdate,custid, CustomerName from(
select distinct poshcompanyid companyid,poshShopID shopid,poshBillID  shopprocessid,
poshBillNo shopnos,''B'' type,posdItemID Itemid,posdSerialNo serialno,poshBillDate Processdate
,poshcustomerid custid, case isnull(poshcustomerid,'''') when '''' then poshCustomerName
else CustomerName End CustomerName from losposheader left outer Join aCustomerMaster on
PoshCustomerId = CustomerId and poshCompanyID = CompanyId, losposdetail
where poshShopID=posdShopID and poshBillID=posdBillID
and poshCancelled=0 and (ltrim(rtrim(posdSerialNo))<>'''' and posdSerialNo is not null)
union all
select distinct ihCompanyId, ihShopID,ihInvoiceID ,ihInvoiceNo,''I''
,idItemID,idSerialNo,ihInvoiceDate,ihCustomerID,
CustomerName  from losinvoiceheader
left outer Join aCustomerMaster on
ihCustomerId = CustomerId and ihCompanyID = CompanyId,losinvoicedetail
where ihShopID=idShopID and ihInvoiceID=idInvoiceID and ihCancelled=0 and
ihType="I" and (ltrim(rtrim(idSerialNo)) <>'''' and idSerialNo is not null)
union all
select distinct sehCompanyid,sehShopID,sehExchangeID ,sehExchangeNo,''E'',
sedItemID,sedSerialNo,sehExchangeDate,poshcustomerid,
case isnull(poshcustomerid,'''') when '''' then sehExchangerName
else CustomerName End CustomerName
from losposExchangeHeader left outer join losposheader on
sehShopID=poshShopID and sehBillID=poshBillID and poshCancelled=0
left outer Join aCustomerMaster on
PoshCustomerId = CustomerId and poshCompanyID = CompanyId
,losposExchangedetail where
sehShopID=sedShopID and sehExchangeID=sedExchangeID and
sehCancelled=0 and (ltrim(rtrim(sedserialno)) <> '''' and sedserialno is not null)
union all
select distinct ihcompanyid,IhShopID,IhInvoiceID ,IhInvoiceNo,''S''
,idItemID,idSerialNo,IhInvoiceDate,IhCustomerID, CustomerName
from losSpecialInvoiceheader left outer Join aCustomerMaster on
ihCustomerId = CustomerId and ihCompanyID = CompanyId,losSpecialInvoicedetail where
IhShopID=IdShopID and IhInvoiceID=IdInvoiceID and IhCancelled=0 and ihtransfinished=1 and
(ltrim(rtrim(idSerialNo))<>'''' and idSerialNo is not null))a ,aitem b
where a.itemid=b.itemid'
GO
/****** Object:  View [dbo].[vwShopLocationWiseStock]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopLocationWiseStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By       : Hariharan
-- Created Date     : 24/12/2002
------------------------------------------
-- lastmodified by  : Kishore
-- Last modified on : 24/04/2003
-- description 	    : adding locationid
--                    Added the cancel = 0 condition (24/04/2003)
--------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopLocationWiseStock] as
select shopname, ladshopid,laditemid, ItemDescription, Code, lLocationName, LgGroupName,
sum(Stock ) Stock ,lLocationID from
(select shopname, ladshopid, laditemid, ItemDescription, Code, lLocationName, LgGroupName,
laditemqty Stock,li.lLocationID from loslocationarrivaldetails ad,
vwitemdescription vw, loslocation li, loslocationgroup lg, ashops s
where ad.laditemid = vw.itemid and ladlocationid = li.llocationid
and ladShopId = li.lShopID and lgroupid = Lggroupid and lcompanyid = Lgcompanyid
and lShopID = lgShopID  and li.lshopid = s.shopid and li.lcompanyid = s.companyid
and ladCancel = 0
union all
select shopname, lidshopid, liditemid, ItemDescription, Code, lLocationName, LgGroupName,
-liditemqty Stock,lLocationID from loslocationIssuedetails ad,
vwitemdescription vw, loslocation li, loslocationgroup lg, ashops s
where ad.liditemid = vw.itemid and lidlocationid = li.llocationid
and lidShopId = li.lShopID and lgroupid = Lggroupid and lcompanyid = Lgcompanyid
and lShopID = lgShopID  and li.lshopid = s.shopid and li.lcompanyid = s.companyid
and lidCancel = 0)
locstock group by shopname, ladshopid, LgGroupName,
itemDescription, laditemid, Code, llocationname,lLocationID'
GO
/****** Object:  View [dbo].[vwshoplocationstock]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoplocationstock]'))
EXEC dbo.sp_executesql @statement = N'
--Created on 	: 22/02/03
--Created by 	: leo
CREATE view [dbo].[vwshoplocationstock] as
select ladshopid, ladlocationid, laditemid, sum(quantity) stock from
(select ladshopid, ladlocationid, laditemid, sum(laditemqty) quantity from loslocationarrivaldetails where
ladcancel = 0 group by ladshopid, ladlocationid, laditemid
union all
select lidshopid, lidlocationid, liditemid, - sum(liditemqty) quantity  from loslocationissuedetails where
lidcancel = 0 group by lidshopid, lidlocationid, liditemid) s group by ladshopid, ladlocationid, laditemid'
GO
/****** Object:  View [dbo].[vwshopsaleinvoiceamount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopsaleinvoiceamount]'))
EXEC dbo.sp_executesql @statement = N'
--modified by  : Hariharan R
--MOdified Date : 23/12/2003
--==========================
--Ref No:1
--modified by	: MANUNADH.U
--Modified Date : 31/10/2011
--Purpose		: To add Taxamount which should be listed in Receipt
CREATE view [dbo].[vwshopsaleinvoiceamount] as
select aicompanyid companyid, aishopid shopid, aidepartmentid, aiinvoiceid,aiinvoiceno invoiceno,
aiinvoicedate, dateadd(day,aidueperiod,aiinvoicedate) duedate, aicustomerid, aiReferenceno,
case convert(int, aiCashPaidByshop) when 1 then
(
	sum(siserviceqty * siamount) + sum(isnull(siClearingCommAmt,0))
) - isnull(aidiscount,0)+ ISNULL(inv.aiTaxAmount,0) --<<Ref No:1>>
else
(
sum(siserviceqty * siamount) - isnull(aidiscount,0)
+ ISNULL(inv.aiTaxAmount,0) --<<Ref No:1>>
) end invoiceamt,
0.0 as settledamt,
case convert(int, aiCashPaidByshop) when 1 then ((sum(siserviceqty * siamount) + sum(isnull(siClearingCommAmt,0))) - isnull(aidiscount,0)) * aiexchangerate
else (sum(siserviceqty * siamount) - isnull(aidiscount,0) * aiexchangerate) end cinvoiceamt,
case convert(int, aiCashPaidByshop) when 1 then
((sum(siserviceqty * siamount) + sum(isnull(siClearingCommAmt,0))) -
isnull(aidiscount,0)) * aidepexrate else
(sum(siserviceqty * siamount) - isnull(aidiscount,0) * aidepexrate) end dinvoiceamt
from losaccountsinvoiceheader inv , losserviceinvoicedetails sd
where  inv.aicompanyid=sd.sicompanyid and inv.aishopid = sd.sishopid and
inv.aiinvoiceid = sd.siinvoiceid and
aiproforma =0 and aicashinvoice =0 and aicancelled = 0 and aiinvoicetype =''CS''
group by
aicompanyid, aishopid, aiinvoiceid, aidepartmentid, aiinvoiceno, aiinvoicedate,
aicustomerid, aidiscount,aidueperiod, aiexchangerate, aidepexrate,aiReferenceno,
convert(int, aiCashPaidByshop),inv.aiTaxAmount
union all
select aicompanyid companyid, aishopid shopid, aidepartmentid, aiinvoiceid,aiinvoiceno invoiceno,
aiinvoicedate, dateadd(day,aidueperiod,aiinvoicedate) duedate, aicustomerid, aiReferenceno,
(sum(siserviceqty * siamount) - isnull(aidiscount,0)+ ISNULL(inv.aiTaxAmount,0) --<<Ref No:1>>
) invoiceamt,
0.0 as settledamt,
(sum(siserviceqty * siamount) - isnull(aidiscount,0) * aiexchangerate) cinvoiceamt,
(sum(siserviceqty * siamount) - isnull(aidiscount,0) * aidepexrate) dinvoiceamt
from losaccountsinvoiceheader inv ,losserviceinvoicedetails sd
where  inv.aicompanyid=sd.sicompanyid and inv.aishopid = sd.sishopid and
inv.aiinvoiceid = sd.siinvoiceid and
aiproforma =0 and aicashinvoice =0 and aicancelled = 0 and aiinvoicetype =''PS''
group by
aicompanyid, aishopid, aiinvoiceid, aidepartmentid, aiinvoiceno, aiinvoicedate,
aicustomerid, aidiscount,aidueperiod, aiexchangerate, aidepexrate,aiReferenceno
,inv.aiTaxAmount'
GO
/****** Object:  View [dbo].[vwImportShortageExcess]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwImportShortageExcess]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on 	: 12/12/02, 03/12/2003
--Modified by		: leo, hariharan
--Comments		: v3
--			: departmentid added
CREATE view [dbo].[vwImportShortageExcess] AS
select    po.pohpono, po.pohpodate, vendorname, dhdespatchnoteno, ah.aharrivalno,
ah.aharrivaldate,ah.ahlocalgodownid, s.sshipmentno, ad.aditemid,
vi.itemdescription,PD.PODQTY poqty,ad.adreceivedqty recevdqty, ad.adDespatchedQty despqty,
pbdItemQuantity billqty, pbdItemUnitPrice fobprice, ahdepartmentid
from loiarrivalheader ah,loiarrivaldetail ad
,ahqdespatchnoteheader dh, ashipment s,vwitemdescription vi, ahqdespatchnotemain mn,
losppurchasebillheader pb, avendormaster v, lopurchaseorderheader po, lopurchaseorderdetail pd,
losppurchasebilldetail pbd
where ah.AHARRIVALID=AD.ADARRIVALID AND ah.ahlocalgodownid=ad.adgodownid
and ah.ahDespatchNoteID=dh.dhdespatchnoteid and ah.ahlocalgodownid=dh.dhGodownid and
pd.podQty <> ad.adReceivedQty and ah.ahshipmentid=s.sshipmentid and
ad.aditemid=vi.itemid and ah.ahcancelled=0 and ah.ahtransfinished=1
and dhdespatchnotemainid=mn.dnmdespatchnoteid and mn.dnmbillid=pb.pbhbillid and
pb.pbhvendorid = v.vendorid and pb.pbhcompanyid = v.companyid
and po.pohpoid=pd.podpoid and pb.pbhpoid = po.pohpoid and ad.aditemid=pd.poditemid
and pbhbillid=pbdbillid and pbditemid=poditemid'
GO
/****** Object:  View [dbo].[vwAsstdisposalTransdetail]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAsstdisposalTransdetail]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  by Venkitesh 120403
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
CREATE view [dbo].[vwAsstdisposalTransdetail] as
SELECT disphno, disphexrate,
dispdamount, DisAstSaleValue,disphcancelled,disphdate,disphdepartmentid,disphcompanyid,
disdepeBalamt, disUptoDepAmt,
Remarks, assetcode,assetname,disp.accountdesc DispAccDesc,
case when  lasttoaccid is null then FixedAssetAccId else
lasttoaccid end AssetAccid,AsstAcc.accountdesc AstAccDesc
FROM
assetdisposalheader a,assetdisposaldetail b
LEFT OUTER JOIN aAccountMaster disp ON
dispdaccid  = AccountID AND  dispdcompanyid = disp.CompanyID
left outer join Fixedasset  Fix on
	dispdasstid = FixedAssetID AND
dispdcompanyid = Fix.CompanyID
LEFT OUTER JOIN aAccountMaster AsstAcc ON
isnull(lasttoaccid,FixedAssetAccId)=asstacc.AccountID
and asstacc.companyid= fix.companyid
where
disphid=dispID and
disphcompanyid=dispdcompanyid'
GO
/****** Object:  StoredProcedure [dbo].[spInsertTillDetail]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertTillDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---Create Procedure spInsertTillDetail
---------------------------------------------------------
--Created By : Praveen S
--Created On : 29-09-2010
--Purpose    : To insert details to the TillDetail Table
---------------------------------------------------------
CREATE PROCEDURE [dbo].[spInsertTillDetail]
@tilldetailid INT,
@tillid INT,
@tillcurrencyid INT,
@tillamount INT,
@tillcompanyid INT,
@tilloutletid INT
AS BEGIN
	 SET NOCOUNT ON
	 INSERT INTO TillDetail(till_td_detailid,till_td_tillid,till_td_currencyid,till_td_amount,
	 till_td_companyid,till_td_outletid)
	 VALUES
	 (@tilldetailid,@tillid,@tillcurrencyid,@tillamount,@tillcompanyid,@tilloutletid)
		
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[vwReceiptDetailsDebit]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptDetailsDebit]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwReceiptDetailsDebit]
as
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 06/08/2008
-- Created by      : Jyothish
-- Comments        :
-------------------------------------------------------------------------------------------------------------------------
-- Modified on      :
-- Modified by      :
-- Comments         :
-------------------------------------------------------------------------------------------------------------------------
select Rh.ReceiptID,Rh.ReceiptNo,Rh.ReceiptDate,am.AccountDesc  from receiptvoucherheader Rh
left outer join aAccountmaster am  on am.AccountID=Rh.debitaccountid'
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSDetail]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInsertPOSDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created On : 14-09-2006
--Purpose    : To insert/update details to the POS Detail Table [losPosDetail]
-----------------------------------------------------------------------------------------------------------------------------
--Upgraded By : Regin T.
--Upgraded On : 22-07-2009
--Purpose     : To insert/update "Kit Item" details to the POS Detail Table [losPosDetail]
-----------------------------------------------------------------------------------------------------------------------------
--Upgraded By : Nidheesh P V
--Upgraded On : 10-01-2010
--Purpose     : increeased the length of decimals(up to 5 numbrs) of the variable @intBillQty
-----------------------------------------------------------------------------------------------------------------------------
--Upgraded By : Nidheesh P V
--Upgraded On : 10-01-2010
--Purpose     : added posdItemTaxPercentage,posdItemTaxAmount,posdItemTaxCategory                             posdServWarrantyUpto,posdPartsWarrantyUpto
-----------------------------------------------------------------------------------------------------------------------------
--Upgraded By : SHINE DAS
--Upgraded On : 04-08-2011
--Purpose     : added posdServWarrantyUpto,posdPartsWarrantyUpto
-----------------------------------------------------------------------------------------------------------------------------
--Upgraded By : AADYAKUMAR D V
--Upgraded On : 14-09-2011
--Purpose     : Old Sp is rollbacked,which i had modified for Kit item,related modification is added to source,
--            : see the references RefNo-136 and RefNo-143
-----------------------------------------------------------------------------------------------------------------------------
--Modified by   : Bijesh.B
--Date Modified : 12/10/2011
--Description   : changed @NumItemTaxAmount as  Numeric(18,2) to @NumItemTaxAmount as  Numeric(18,8)
-----------------------------------------------------------------------------------------------------------------------------
--Modified by   : SHINE DAS
--Date Modified : 24/11/2011
--Description   : Added new variable @intBillDetailID and field posdbilldetailid
-----------------------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spInsertPOSDetail]
@intBillId As Int,
@intShopId As Int,
@intItemId As int,
@intPackId As Int,
@intUnitId As Int,
@intPQty As Numeric(18,3),
@intBillQty As Numeric(18,5),
@intUnitPrice As Numeric(18,8),
@intRateType As Int,
@intActUP As Numeric(18,2),
@intCostPrice As Numeric(18,2),
@strNotes As Varchar(250),
@intBlockPrice As Numeric(18,2),
@intGuarantee As Varchar(250),
@intFreeQty As Numeric(18,3),
@intSerialNo As Varchar(250),  -- This parameter is Not used. But SlNo is generated in the SP.
@intItemSlno As Int,
-- @intItemVarFlag As Int,
-- @intCmpVarFlag As Int
@strItemType as varchar(10) = ''I'',
@NumItemTaxPercentage as Numeric(18,2),
@NumItemTaxAmount as  Numeric(18,8),
@intItemTaxCatId as int,
@dtServWarrantyUpto as datetime=null,
@dtPartsWarrantyUpto as datetime=null,
@intBillDetailID as int
As
Begin
set nocount on
declare @numExRateFactor as numeric(18,6)  -- Since Exchange Rate Factor is very sensitive, precision is set to 6.
declare @intSlNo as int
-- Finding the maximum serial number of items in the bill
select @intSlNo=isnull(max(posdItemSerialNo),0)
from losPosDetail
where posdShopID=@intShopId and posdBillID=@intBillId
if @strItemType = ''I'' -- Normal Item
begin
Insert InTo losPosDetail
(posdShopID, posdBillID, posdItemID, posdPackingTypeID, posdPUnitID, posdPQuantity, posdQuantity, posdUnitPrice,
posdRateType, posdActualUnitPrice, posdcostprice, posddescription, posdblockprice, posdguarantee, rowguid,
posdSerialNo, posdFreeQuantity, posdItemSerialNo, posdItemType, posdKitID, posdKitQuantity, posdKitActualPrice,
posdItemTaxPercentage,posdItemTaxAmount,posdItemTaxCategory,posdServWarrantyUpto,posdPartsWarrantyUpto,posdbilldetailid)
Values
(@intShopId,@intBillId,@intItemId,@intPackId,@intUnitId,@intPQty,@intBillQty,
@intUnitPrice,@intRateType,@intActUP,@intCostPrice,@strNotes,@intBlockPrice,@intGuarantee,NewId(),@intSerialNo,
@intFreeQty, @intSlNo, @strItemType, 0, 0, 0,@NumItemTaxPercentage,@NumItemTaxAmount,@intItemTaxCatId,@dtServWarrantyUpto,@dtPartsWarrantyUpto,@intBillDetailID) --,@intItemVarFlag,@intCmpVarFlag)
end
else if @strItemType = ''K''  -- Kit Item
begin
------------------------------------------------------------
-- How Kit Item is stored in losPosDetail table?
------------------------------------------------------------
-- Even though Kit Item is shown as a single item in POS interface,
-- Kit Item is a collection of normal items.
-- So the items of given Kit is separately stored in the losPosDetail table,
-- so that the inventory would be properly accounted.
-- The list of items in the kit is taken from the aKitItemDetail table.
-- PackQuantity as well as BillQty are computed based on KitQuantity and Kit Capacity.
-- The UnitPrice of those items is taken from aKitItemDetail
-- assuming Discount is not allowed for Kit Item.
-- Actual Unit Price of those items in the kit is found using spSellingPriceFetchWOPriceChange.
-- Finding actual unit price is bit complicated, since Stored Procedure is used to find.
-- Cost Price is taken from aItem table.
------------------------------------------------------------
-- Written By: Regin T.
-- Written On: 22-07-2009
------------------------------------------------------------
---------------------------------------------------------------------------
-- Finding the Selling Price of all items of selected Kit -- Starts Here --
create table #ItemSellingPrice
(ispSlNo int IDENTITY(1,1),
ispItemID int,
ispPackID int,
ispSellingPrice numeric(18,2))
-- Below table stores the result of spSellingPriceFetchWOPriceChange
create table #TableTemp
(SP numeric(18,2),
DP numeric(18,2),
WP numeric(18,2),
DpQty numeric(18,2),
WpQty numeric(18,2),
ForSales int,
ItemDesc varchar(250))
--Step1: To get all Item ID of selected Kit
insert into #ItemSellingPrice(ispItemID,ispPackID)
select kd.ItemID, kd.PackingTypeId
from aKitItemMaster km, aKitItemDetail kd
where km.KitID=kd.KitID and km.KitID=@intItemId
--Step2: To get the selling price of each items using spSellingPriceFetchWOPriceChange
declare @intItemIDTemp as int,
@intPackIDTemp as int,
@intCashAccCurrencyID as int
-- To get the Currency ID of selected Cash Account of Sale. This is an argument to find Selling Price.
select @intCashAccCurrencyID = a.CurrencyID from losPosHeader, aAccountMaster a
where poshCashAccID=a.AccountID and poshBillID = @intBillId
declare curSP cursor for
select ispItemID, ispPackID from #ItemSellingPrice
open curSP
fetch next from curSP into @intItemIDTemp, @intPackIDTemp
while @@Fetch_Status = 0
begin
insert into #TableTemp
exec spSellingPriceFetchWOPriceChange 1,@intShopId,0,@intItemIDTemp,@intPackIDTemp,1,@intCashAccCurrencyID
--spSellingPriceFetchWOPriceChange @intCompanyId as int, @intShopid as int, @intCustomerId as int=0,
--@intitemid as int, @intpackid as int, @intCash as int =1, @intCurrencyID as int
update #ItemSellingPrice
set ispSellingPrice = (select isnull(SP,0) from #TableTemp)
delete from #TableTemp
fetch next from curSP into @intItemIDTemp, @intPackIDTemp
end
close curSP
deallocate curSP
-- Finding the Selling Price of all items of selected Kit -- Ends Here --
---------------------------------------------------------------------------
-- All values should be stored in Cash Account Currency.
-- So values are converted from Inventory Currency to Cash Account Currency.
-- Exchage Rate Factor needs to computed for this conversion.
-- This exchange rate factor will be multiplied with those values in Inv Curr.
select @numExRateFactor=sum(ToExRate)/sum(FromExRate) from (
select SellingRate FromExRate, 0 ToExRate from aPackageSettings s, aAccountMaster a, ExchangeRateDetail e
where s.InventoryID=a.AccountID and a.CurrencyID=e.CurrencyID
union all
select 0 FromExRate, SellingRate ToExRate from ExchangeRateDetail
where CurrencyID=@intCashAccCurrencyID ) a
-----------------to get tax details---------------------------
declare @tempItemTax as table
(
IntItemId int,
TaxPercentage numeric(18,2),
--@TaxRate numeric(18,2)
TaxCateId int
)
insert into @tempItemTax
select kd.ItemID,TaxPercentage,TaxId from aKitItemDetail kd inner join aitem i
on kd.ItemID=i.ItemID and kd.KitID=@intItemId
inner join ataxcategorymaster tc
on i.TaxCategoryId=tc.TaxId
------------------------------------------------
Insert InTo losPosDetail
(posdShopID, posdBillID, posdItemID, posdPackingTypeID, posdPUnitID, posdPQuantity, posdQuantity, posdUnitPrice,
posdRateType, posdActualUnitPrice, posdcostprice, posddescription, posdblockprice, posdguarantee, rowguid,
posdSerialNo, posdFreeQuantity, posdItemSerialNo, posdItemType, posdKitID, posdKitQuantity, posdKitActualPrice,
posdItemTaxPercentage,posdItemTaxAmount,posdItemTaxCategory,posdbilldetailid)
select
@intShopId                          ShopID,
@intBillId                          BillID,
kd.ItemID                           ItemID,
kd.PackingTypeId                    PackID,
kd.UnitId                           UnitID,
kd.PackingTypeQty*@intPQty          PackQty,
kd.Qty*@intPQty                     BillQty,
-- Since all rates are rounded to 2 precision numbers in Pos,
-- the results of below calculations are rounded to 2 precision numbers.
round(round(@numExRateFactor*(kd.Price+(kd.Price*isnull(it.TaxPercentage,0)/100))*kd.PackingTypeQty,2)*@intPQty,2) UnitPrice, -- Amount for all quanties, not the price of single item.
-------kd.Price--->kd.Price+(kd.Price*@TaxPercentage/100)-Item Price+Tax of Item Price
@intRateType                        RateType,
p.ispSellingPrice                   ActualUnitPrice,
i.ItemRate*@numExRateFactor         CostPrice,
@strNotes                           Note,
kd.Price*@numExRateFactor           BlockPrice,  -- Block Price is set to UnitPrice since no discount is allowed for kit item.
@intGuarantee                       Guarantee,
NewId()                             GlobalID,
@intSerialNo                        SerialNo,
0                                   FreeQty,
@intSlNo + p.ispSlNo                ItemSlNo,
@strItemType                        ItemType,
@intItemId                          KitID,       -- @intItemID is nothing but KitID
@intPQty                            KitQuantity,  -- @intPQty is nothing but KitQuantity
round(@numExRateFactor*km.SellingPrice, 2) KitActualPrice,
isnull(it.TaxPercentage,0)      ItemTaxPercentage,
round(round(@numExRateFactor*(kd.Price*isnull(it.TaxPercentage,0)/100)*kd.PackingTypeQty,2)*@intPQty,2) ItemTaxAmount,
isnull(it.TaxCateId,0)       ItemTaxCatId,@intBillDetailID
from aKitItemMaster km
inner join aKitItemDetail kd on km.KitID=kd.KitID and km.KitID=@intItemId
inner join aItem i  on kd.ItemID=i.ItemID
inner join #ItemSellingPrice p on kd.ItemID=p.ispItemID
left outer join @tempItemTax it on kd.ItemID=it.IntItemId
drop table #TableTemp
drop table #ItemSellingPrice
end -- End of Kit Item Save
set nocount off
End
-----------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spHPDebtorAgeRecivableDifference]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spHPDebtorAgeRecivableDifference]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spLocalPurchaseSerilNumer]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLocalPurchaseSerilNumer]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author     :	AADYAKUMAR.D.V
-- Create date: 25/01/2012
-- Description:	THIS STORED PROCEDURE IS CREATED
--            : FOR SHOWING SERIAL NUMER OF ITEMS IN LOCAL PURCHAE
-- =============================================
--spLocalPurchaseSerilNumer ''20111018'',''20111018'',4
create PROCEDURE [dbo].[spLocalPurchaseSerilNumer]
@FromDate AS varchar(10),
@ToDate AS varchar(10),
@intShopId as int
AS
BEGIN
	select lphBillNo,lphBillDate,VendorName,sadSerialNo,I.ItemCode,I.ItemDescription from LosLocalPurchaseHeader H
	INNER JOIN  losLocalPurchaseDetail D
	on H.lphShopID=D.lpdShopId AND H.lphBillID=D.lpdBillID and lphCancelled=0
	INNER JOIN losSerialArrivalDetails S
	ON H.lphShopID=S.sadShopID AND H.lphBillID=S.sadtransactionid
	   AND D.lpdItemID = S.sadItemID AND S.sadInterfaceID=1511
	INNER JOIN aVendorMaster V
	ON H.lphVendorID=V.VendorID
	INNER JOIN aitem I
	ON  D.lpdItemID=I.ItemID
	where H.lphBillDate>=@FromDate and H.lphBillDate<=@ToDate and H.lphShopID=@intShopId
END' 
END
GO
/****** Object:  View [dbo].[vwBillOtherCharges]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillOtherCharges]'))
EXEC dbo.sp_executesql @statement = N'
/*
Created By Prasanth
Created For to get Billwise other charge details
*/
---------------------------
CREATE  View [dbo].[vwBillOtherCharges] as
select ch.chbillid,cadDescription, isnull(cadamount,0) otherc
from loacostingaccountdetails cad, loacostingheader ch, apackagesettings where
ch.chcostingid = cad.cadcostingid and ch.chcancelled = 0 and cadaccountid<>customsaccid
--group by ch.chbillid,cadDescription'
GO
/****** Object:  View [dbo].[vwBasketSales]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBasketSales]'))
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : SREEJITH G A
--CREATED ON : 20101103
--PURPOSE : TO USE IN SPBASKETVALUEANALYSIS
--Altered By : Nidheesh P V
--Altered on : 09/11/2010
--Comments   : Added goods exchange ,goods return,special invoice
--Added ComSaleAmount & DepSaleAmount seperately
------------------------------------------------------------------
--Ref.No:1
--Altered By : AADYAKUMAR.D.V
--Altered on : 07/02/2012
--Comments   : As per Ticket:PDH-447797 mismatch found,
--           : between Basket Sales and Shop Sales ByHour report
--           : Goods exchange part modified
------------------------------------------------------------------
--Ref.No:2
--Altered By : AADYAKUMAR.D.V
--Altered on : 20/02/2012
--Comments   : As per Ticket:PDH-447797,when doing invoice amount doubled,
--Reason     : flag ihtype=''I'' not used,so other transaction like Quatation,Order also shown
------------------------------------------------------------------
CREATE VIEW [dbo].[vwBasketSales]
AS
SELECT POSHCOMPANYID,POSHSHOPID, POSHBILLID ,POSHBILLDATE,
convert(numeric(18, 2),(poshBillAmount*poshExchangeRate))ComSaleAmount,
convert(numeric(18, 2),(poshBillAmount*poshDepExRate))DepSaleAmount
FROM LOSPOSHEADER WHERE POSHCANCELLED=0
UNION ALL
SELECT IHCOMPANYID,ihShopID, ihInvoiceID ,ihInvoiceDate,
convert(numeric(18,2),(ihInvoiceAmount*ihExchangeRate))ComInvoiceAmount,
convert(numeric(18,2),(ihInvoiceAmount*ihDepExRate))DepInvoiceAmount
FROM LOSINVOICEHEADER WHERE IHCANCELLED=0
and ihtype=''I''   --Ref.No:2
UNION ALL
select sehCompanyID,sehshopid,sehexchangeid,sehExchangeDate,
--Ref.No:1
--convert(numeric(18,2),((-sehExchangeBillAmount)*sehexchangerate))ComExchAmount,
--convert(numeric(18,2),((-sehExchangeBillAmount)*sehDepExRate))DepExchAmount
convert(numeric(18,2),((-sehExchangeBillAmount)*sehexchangerate))ComExchAmount,
convert(numeric(18,2),((-sehExchangeBillAmount)*sehDepExRate))DepExchAmount
--Ref.No:1
From losposexchangeheader ph  where sehcancelled=0
UNION ALL
Select GrnCompanyID,grnhshopid,GrnhGoodsreturnnoteID,GrnhGoodsreturnnoteDate,
convert(numeric(18,2),-Sum(grndunitprice*grnhExchangeRate))Comamount,
convert(numeric(18,2),-Sum(grndunitprice*grnhDepExRate))Depamount
From losGoodsReturnNoteHeader ih inner join losGoodsReturnNoteDetail invd  on ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID
where grnhCancel = 0 group by GrnCompanyID,grnhshopid,GrnhGoodsreturnnoteID,GrnhGoodsreturnnoteDate
UNION ALL
--Special Invoice
select IhCompanyId,ihshopid,ihInvoiceid,IhInvoiceDate,
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)ComAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)DepAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0 and IhTransFinished = 1 and ihNoofOCDetails=0
union all
--special invoice return before despatch
select IhCompanyId,ihshopid,ihInvoiceid,IhInvoiceDate,
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)ComAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)DepAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0 and IhTransFinished = 1 and ihNoofOCDetails<>0
union all
--special invoice return after despatch
select IhCompanyId,ihshopid,ihInvoiceid,IhInvoiceDate,
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)cAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)dAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 1 and ihproforma = 0 and IhTransFinished = 1
------  union all
--Service Invoice is commented because there is no time filed(so avoided in shop sales by hour report also)--------
------  --Service Invoice header
------  select serinvhshopid,serinvhid,'''','''',
------  convert(numeric(18, 2),serinvhpartsamt * seinvhDepExRate)ComAmount,
------  convert(numeric(18, 2),serinvhpartsamt * serinvhcmpexrate)DepAmount
------  from losserviceinvheader where serinvhcancelled = 0
--Service Invoice is commented because there is no time filed--------'
GO
/****** Object:  StoredProcedure [dbo].[spShopSalesByHour]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopSalesByHour]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
/*
Created By : Manu Nadh
Created On : 25/10/2010
Altered by : Nidheesh P V
Altered on : 09/11/2010
Comments   : Added goods return and goods exchange,special invoice
Added @intDeptId parameter--Added ComSaleAmount & DepSaleAmount seperately
@intDeptId<>0 for pos report & for P&C report in dept login, and @intDeptId=0 for P&C report in company login
spShopSalesByHour 9,1,''20120209'',''20120209'',0
Altered by : SHINE DAS
Altered on : 15/07/2011
Comments   : As on date report was existed. Change it to date range. @fromDate field added. Here
previously existed parameter "@OnDate" keeps as the same and used intead of @toDate.
*/
------------------------------------------------------------------
--Ref.No:1
--Altered By : AADYAKUMAR.D.V
--Altered on : 20/02/2012
--Comments   : As per Ticket:PDH-447797,when doing invoice amount doubled,
--Reason     : flag ihtype=''I'' not used,so other transaction like Quatation,Order also shown
------------------------------------------------------------------
CREATE procedure [dbo].[spShopSalesByHour]
(
@intShopId int,
@intCompanyId int,
@OnDate varchar(12),
@fromDate varchar(12),
@DeptId as int
)
as
begin
select SalesDetails.*,s.departmentid into tempSales from
(
--Pos Cash sales
select poshBillID,poshShopID,poshBilltime,datepart(hh,poshBilltime)Hourr,
convert(numeric(18, 2),(poshBillAmount*poshExchangeRate))ComSaleAmount,
convert(numeric(18, 2),(poshBillAmount*poshDepExRate))DepSaleAmount
--from losposheader where (poshShopID =@ShopId or @ShopId=0) and poshBillDate =@fromDate
from losposheader where (poshShopID =@intShopId or @intShopId=0) and poshBillDate between @fromDate and @OnDate
and  poshCancelled=0  and poshCompanyID=@intCompanyId and poshBilltime is not null
union all
--Credit Invoice
select ihInvoiceID,ihShopID,ihInvoiceTime,datepart(hh,ihInvoiceTime),
convert(numeric(18,2),(ihInvoiceAmount*ihExchangeRate))ComInvoiceAmount,
convert(numeric(18,2),(ihInvoiceAmount*ihDepExRate))DepInvoiceAmount
--from losinvoiceheader where (ihShopID =@ShopId or @ShopId=0) and ihInvoiceDate = @fromDate
from losinvoiceheader where (ihShopID =@intShopId or @intShopId=0) and ihInvoiceDate  between @fromDate and @OnDate
and ihCancelled=0  and ihCompanyId=@intCompanyId and ihInvoiceTime is not null
and ihtype=''I'' --Ref.No:1
union all
--Pos goods Exchange
select sehexchangeid,sehshopid,updatetime,datepart(hh,updatetime),
convert(numeric(18,2),((-sehExchangeBillAmount)*sehexchangerate))ComExchAmount,
convert(numeric(18,2),((-sehExchangeBillAmount)*sehDepExRate))DepExchAmount
From losposexchangeheader ph  where sehcancelled=0 and (sehshopid =@intShopId or @intShopId=0)
--and sehExchangeDate=@fromDate and sehCompanyID=@CompanyId
and sehExchangeDate between @fromDate and @OnDate and sehCompanyID=@intCompanyId
union all
--Pos goods Return
Select distinct GrnhGoodsreturnnoteID,grnhshopid,updatetime,datepart(hh,updatetime),
convert(numeric(18,2),-Sum(grndunitprice*grnhExchangeRate)over(partition by grnhshopid,GrnhGoodsreturnnoteID))Comamount,
convert(numeric(18,2),-Sum(grndunitprice*grnhDepExRate)over(partition by grnhshopid,GrnhGoodsreturnnoteID))Depamount
From losGoodsReturnNoteHeader ih inner join losGoodsReturnNoteDetail invd  on ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID and grnhCancel = 0
--where (grnhshopid =@ShopId or @ShopId=0) and GrnhGoodsreturnnoteDate=@fromDate and GrnCompanyID=@CompanyId
where (grnhshopid =@intShopId or @intShopId=0) and GrnhGoodsreturnnoteDate  between @fromDate and @OnDate  and GrnCompanyID=@intCompanyId
union all
--Special Invoice
select ihInvoiceid,ihshopid,updatetime,datepart(hh,updatetime),
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)ComAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)DepAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0 and IhTransFinished = 1 and ihNoofOCDetails=0
--and (ihshopid =@ShopId or @ShopId=0) and IhInvoiceDate=@fromDate and IhCompanyId=@CompanyId
and (ihshopid =@intShopId or @intShopId=0) and IhInvoiceDate between @fromDate and @OnDate and IhCompanyId=@intCompanyId
union all
--special invoice return before despatch
select ihInvoiceid,ihshopid,updatetime,datepart(hh,updatetime),
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)ComAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)DepAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0 and IhTransFinished = 1 and ihNoofOCDetails<>0
--and (ihshopid =@ShopId or @ShopId=0) and IhInvoiceDate=@fromDate and IhCompanyId=@CompanyId
and (ihshopid =@intShopId or @intShopId=0) and IhInvoiceDate between @fromDate and @OnDate and IhCompanyId=@intCompanyId
union all
--special invoice return after despatch
select ihInvoiceid,ihshopid,updatetime,datepart(hh,updatetime),
convert(numeric(18, 2),IhInvoiceAmount * ihExchangeRate)cAmount,
convert(numeric(18, 2),IhInvoiceAmount * ihDepExRate)dAmount
from  losspecialinvoiceheader inner join losspecialinvoicedetail on  ihInvoiceid = idInvoiceid  and ihshopid = idshopid
where IHCANCELLED = 0 and idratetype = 1 and ihproforma = 0 and IhTransFinished = 1
--and (ihshopid =@ShopId or @ShopId=0) and IhInvoiceDate=@fromDate and IhCompanyId=@CompanyId
and (ihshopid =@intShopId or @intShopId=0) and IhInvoiceDate between @fromDate and @OnDate and IhCompanyId=@intCompanyId
------  union all
--Service Invoice is commented because there is no time filed--------
------  --Service Invoice header
------  select serinvhshopid,serinvhid,'''','''',
------  convert(numeric(18, 2),serinvhpartsamt * seinvhDepExRate)ComAmount,
------  convert(numeric(18, 2),serinvhpartsamt * serinvhcmpexrate)DepAmount
------  from losserviceinvheader where serinvhcancelled = 0
--Service Invoice is commented because there is no time filed--------
)SalesDetails inner join ashops s on s.shopid=poshShopID and (s.departmentid=@DeptId or @DeptId=0)
select distinct Hint,HRange,case when @DeptId <>0 then isnull(ts.departmentid,0) else '''' end departmentid,case when @intShopId <>0 then isnull(poshShopID,0) else '''' end shopid,
case when @intShopId<>0 then count(poshbillid)over (partition by datepart(hh,poshBilltime),poshShopID)
when (@DeptId<>0 and @intShopId=0) then count(poshbillid)over (partition by datepart(hh,poshBilltime),departmentid)
when @DeptId=0 then count(poshbillid)over (partition by datepart(hh,poshBilltime)) end TotalSales,
case when @intShopId <>0 then sum(isnull(ComSaleAmount,0))over (partition by datepart(hh,poshBilltime),poshShopID)
when (@DeptId<>0 and @intShopId=0) then sum(isnull(ComSaleAmount,0))over (partition by datepart(hh,poshBilltime),departmentid)
when @DeptId=0 then sum(isnull(ComSaleAmount,0))over (partition by datepart(hh,poshBilltime)) end ComTotaBillAmount,
case when @intShopId <>0 then sum(isnull(DepSaleAmount,0))over (partition by datepart(hh,poshBilltime),poshShopID)
when (@DeptId<>0 and @intShopId=0) then sum(isnull(DepSaleAmount,0))over (partition by datepart(hh,poshBilltime),departmentid)
when @DeptId=0 then sum(isnull(DepSaleAmount,0))over (partition by datepart(hh,poshBilltime)) end DepTotaBillAmount
from dbo.fnHourRange(0,23) left outer join
tempSales ts on Hint=ts.Hourr
where ((poshShopID=@intShopId or @intShopId=0) or poshShopID is null)
order by Hint
drop table tempSales
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on	: 26/08/2003
-- Created by	: Kishore
-- Comments	: This sp sets the Expiry stock of all items, which
--                are not verified in a total stock verification,
--                to zero
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]
				(@intSvdId as int,
				 @intGodownId as int,
				 @intExpiryIssueDetailId as int OUTPUT,
				 @intExpiryArrivalDetailId as int OUTPUT) AS
Begin
	Declare @intItemId as int
	Declare @numcurExpiryStock as Numeric(18, 2)
	Declare @dtExpiryDate as DateTime
	
	-- cursor to loop through the non-verified items
	Declare curNonVerifiedItems Cursor For
		SELECT gsItemId FROM moiGodownStock
		WHERE gsGodownId = @intGodownId
		AND gsItemId NOT IN
			(SELECT svdItemId FROM loiStockVerificationDetail
			WHERE svdId = @intSvdId
			AND svdGodownId = @intGodownId)
	
	-- cursor to loop through distinct expiry dates
	Declare curExpiry Cursor For
		SELECT DISTINCT ExpiryDate FROM
			(SELECT eadExpiryDate ExpiryDate FROM loiExpiryArrivalDetails
			WHERE eadGodownId = @intGodownId
			AND eadCancel = 0
			UNION ALL
			SELECT eidExpiryDate ExpiryDate FROM loiExpiryIssueDetails
			WHERE eidGodownId = @intGodownId
			AND eidCancel = 0) a		
	Open curExpiry
	Open curNonVerifiedItems
	
	-- get first non-verified itemid
	Fetch Next From curNonVerifiedItems Into @intItemID
	While @@fetch_status = 0
	Begin
		Fetch Next From curExpiry Into @dtExpiryDate
		
		-- check the item id in each Expiry
		While @@fetch_status = 0
		Begin
			-- first get the currect Expiry stock
		SELECT @numcurExpiryStock = qty
		FROM
	         	(SELECT ExpiryDate, GodownId,
			ItemId, SUM(qty) qty
	        	FROM
	       		(SELECT eadExpiryDate ExpiryDate,
			eadGodownId GodownId, eadItemId ItemId , SUM(eadItemQty) qty
		FROM loiExpiryArrivalDetails
	       		WHERE eadGodownId = @intGodownId
		AND eadItemId =  @intItemId
	       		AND eadCancel = 0
			AND eadExpiryDate = @dtExpiryDate
			GROUP BY eadExpiryDate, eadGodownId, eadItemId
	        	UNION ALL
			SELECT eidExpiryDate, eidGodownId, eidItemId, - SUM(eidItemQty)
	        	FROM loiExpiryIssueDetails
	        	WHERE eidGodownId = @intGodownId
		        AND eidItemId = @intItemId
			AND eidCancel = 0
			AND eidExpiryDate = @dtExpiryDate
		        GROUP BY eidExpiryDate, eidGodownId, eidItemId) a
		        GROUP BY ExpiryDate, GodownId, ItemId
		        HAVING SUM(qty) <> 0 ) b
		WHERE b.ItemId = @intItemId  -- for extra safety
		
			-- if stock > 0, insert to issue details
			-- otherwise insert to arrival details
			-- to make the net stock zero
			-- Do this only if stock <> 0
			If @numcurExpiryStock > 0
			Begin
				INSERT INTO loiExpiryIssueDetails
				(eidinterfaceid, eidGodownid, eidTransactionId, eiddetailid,
				eidExpiryDate, eiditemid, eiditemqty, eidpackingtypeid,
				eidpackingqty, eidcancel, eidadjustment)
				VALUES
				(8010, @intGodownId, @intSvdId, @intExpiryIssueDetailId,
				@dtExpiryDate, @intItemId,
				ABS(@numcurExpiryStock), 1, ABS(@numcurExpiryStock), 0, 1)
				Set @intExpiryIssueDetailId = @intExpiryIssueDetailId + 1
			End
			Else If @numcurExpiryStock < 0
			Begin
				INSERT INTO loiExpiryArrivalDetails
				(eadinterfaceid, eadGodownid, eadtransactionid, eaddetailid,
				eadExpiryDate, eaditemid, eaditemqty, eadpackingtypeid,
				eadpackingqty, eadcancel, eadadjustment)
				VALUES
				(8010, @intGodownId, @intSvdId, @intExpiryArrivalDetailId,
				@dtExpiryDate, @intItemId,
				ABS(@numcurExpiryStock), 1, ABS(@numcurExpiryStock), 0, 1)
				Set @intExpiryIssueDetailId = @intExpiryIssueDetailId + 1
			End		
			Fetch Next From curExpiry Into @dtExpiryDate
		End
		
		Fetch Next From curNonVerifiedItems Into @intItemID
	End
	Close curExpiry
	Deallocate curExpiry
	Close curNonVerifiedItems
	Deallocate curNonVerifiedItems
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRemoveTillDetails]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemoveTillDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 30/Sep/2010
--Created by	: Praveen S
--Comments	: For Removing the TillDetails
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spRemoveTillDetails]
@tillid INT,
@tilloutletid INT,
@tillcompanyid INT
AS BEGIN
	 SET NOCOUNT ON
	 DELETE FROM TillDetail
	 WHERE till_td_tillid = @tillid AND
	 till_td_outletid = @tilloutletid AND
	 till_td_companyid 	= @tillcompanyid
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created on	: 26/08/2003
-- Created by	: Kishore
-- Comments	: This sp sets the location stock of all items, which
--                are not verified in a total stock verification,
--                to zero
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]
				(@intSvdId as int,
				 @intShopId as int,
				 @intIssueDetailId as int OUTPUT,
				 @intArrivalDetailId as int OUTPUT) AS
Begin
	Declare @intItemId as int
	Declare @numCurLocationStock as Numeric(18, 2)
	Declare @intLocationId as int
	
	-- cursor to loop through the non-verified items
	Declare curNonVerifiedItems Cursor For
		SELECT ItemId FROM mosShopStock
		WHERE ShopId = @intShopId
		AND ItemId NOT IN
			(SELECT ItemId FROM losStockVerificationDetail
			WHERE svdId = @intSvdId
			AND svdShopId = @intShopId)
	
	-- cursor to loop through locations
	Declare curLocations Cursor For
		SELECT lLocationId FROM losLocation
	Open curLocations
	Open curNonVerifiedItems
	
	-- get first non-verified itemid
	Fetch Next From curNonVerifiedItems Into @intItemID
	While @@fetch_status = 0
	Begin
		Fetch Next From curLocations Into @intLocationId
		
		-- check the item id in each location
		While @@fetch_status = 0
		Begin
			-- first get the currect location stock
		SELECT @numCurLocationStock = qty
		FROM
	         	(SELECT LocationId, ShopId,
			ItemId, SUM(qty) qty
	        	FROM
	       		(SELECT ladLocationId LocationId,
			ladShopId ShopId, ladItemId ItemId , SUM(ladItemQty) qty
		FROM losLocationArrivalDetails
	       		WHERE ladShopId = @intShopId
		AND ladItemId =  @intItemId
	       		AND ladCancel = 0
			AND ladLocationId = @intLocationId
			GROUP BY ladLocationId, ladShopId, ladItemId
	        	UNION ALL
			SELECT lidLocationId, lidShopId, lidItemId, - SUM(lidItemQty)
	        	FROM losLocationIssueDetails
	        	WHERE lidShopId = @intShopId
		        AND lidItemId = @intItemId
			AND lidCancel = 0
			AND lidLocationId = @intLocationId
		        GROUP BY lidLocationId, lidShopId, lidItemId) a
		        GROUP BY LocationId, ShopId, ItemId
		        HAVING SUM(qty) <> 0 ) b,
		        losLocation
		WHERE b.LocationId = losLocation.lLocationId
		        AND b.ShopId = losLocation.lShopId		
			AND b.ItemId = @intItemId  -- for extra safety
		
			-- if stock > 0, insert to issue details
			-- otherwise insert to arrival details
			-- to make the net stock zero
			-- Do this only if stock <> 0
			If @numCurLocationStock > 0
			Begin
				INSERT INTO losLocationIssueDetails
				(lidinterfaceid, lidShopid, lidTransId, liddetailid,
				lidlocationid, liditemid, liditemqty, lidpackingtypeid,
				lidpakingqty, lidcancel, lidadjustment)
				VALUES
				(1900, @intShopId, @intSvdId, @intIssueDetailId,
				@intLocationId, @intItemId,
				ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
				Set @intIssueDetailId = @intIssueDetailId + 1
			End
			Else If @numCurLocationStock < 0
			Begin
				INSERT INTO losLocationArrivalDetails
				(ladinterfaceid, ladShopid, ladtransid, laddetailid,
				ladlocationid, laditemid, laditemqty, ladpackingtypeid,
				ladpakingqty, ladcancel, ladadjustment)
				VALUES
				(1900, @intShopId, @intSvdId, @intArrivalDetailId,
				@intLocationId, @intItemId,
				ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
				Set @intIssueDetailId = @intIssueDetailId + 1
			End		
			Fetch Next From curLocations Into @intLocationId
		End
		
		Fetch Next From curNonVerifiedItems Into @intItemID
	End
	Close curLocations
	Deallocate curLocations
	Close curNonVerifiedItems
	Deallocate curNonVerifiedItems
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShopTotalStockVerification]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShopTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on  : 26/08/2003
-- Created by  : Kishore
-- Comments    : Does the stock updattion
--               and insertion of records to losStockVerificationDetails
--   Taken from v2
---------------------------------------------------------------------------------------------------------------
--RefNo-1
--Modified By : Yogesh Joe
--Modified On : 17-03-2010
--Purpose : To reset the bad stock field to zero.We used the value in it for calculating the actual stock.
--If we store the values in it, it will give wrong figures.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--RefNo-2
--Modified By : Yogesh Joe
--Modified On : 17-03-2010
--Purpose : Used vwinquiryshopstock instead of mosShopStock, to get the correct stock details.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--RefNo-3
--Modified By : Shine Das
--Modified On : 22-02-2011
--Purpose : changed the formula from svdVerifiedStock = svdVerifiedBadStock - @numSumOut + @numSumIn
-- to svdVerifiedStock = svdVerifiedStock - @numSumOut + @numSumIn
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spShopTotalStockVerification] (@intSvdId as int, @intShopId as int) AS
Begin
Declare @dtUpdate as DateTime
Declare @intItemId as int
Declare @numSumOut as Numeric(18, 3)
Declare @numSumIn as Numeric(18, 3)
Declare @intCount as Int
Declare @intArrivalDetailId as int
Declare @intIssueDetailId as int
Declare @intExpiryArrivalDetailId as int
Declare @intExpiryIssueDetailId as int
-- initilize detail id variables
Set @intArrivalDetailId = 1
Set @intIssueDetailId = 1
Set @intExpiryArrivalDetailId = 1
Set @intExpiryIssueDetailId = 1
SELECT @intArrivalDetailId = ISNULL(MAX(ladDetailId), 0) + 1
FROM losLocationArrivalDetails
WHERE ladShopId = @intShopId
AND ladTransId = @intSvdId
AND ladInterfaceId = 1900
--AND ladCancel = 1
SELECT @intExpiryArrivalDetailId =  ISNULL(MAX(eadDetailId), 0) + 1
FROM losExpiryArrivalDetails
WHERE eadShopId = @intShopId
AND eadTransactionId = @intSvdId
AND eadInterfaceId = 8010
AND eadCancel = 1
-- get the UpdateTime
SELECT @dtUpdate = UpdateTime FROM losStockVerificationHeader
WHERE svhId = @intSvdId
AND svhShopId = @intShopId
-- open the cursor
Declare curDetails Cursor For
SELECT svdItemId FROM losStockVerificationDetail
WHERE svdId = @intSvdId
AND svdShopId = @intShopId
Open CurDetails
Fetch Next From CurDetails Into @intItemId
While @@Fetch_Status = 0
Begin
-- get sum qty transacted out
-- after starting the ''total stock verification''
SELECT @numSumOut = ISNULL(SUM(TransQty), 0) FROM vwShopBinCardAudit
WHERE ItemId = @intItemId
AND UpdateTime >= @dtUpdate
AND Type IN (''Cash Sales'', ''Credit Sales'',
''Exchange Out'', ''Parts Replaced'')
AND ShopId = @intShopId
-- get sum qty transacted in
-- after starting the ''total stock verification''
SELECT @numSumIn = ISNULL(SUM(TransQty), 0) FROM vwShopBinCardAudit
WHERE ItemId = @intItemId
AND UpdateTime >= @dtUpdate
AND Type IN (''Exchanged In'', ''Special Invoice Return'', ''Goods Return'')
AND ShopId = @intShopId
Set @numSumOut = ISNULL(@numSumOut, 0)
Set @numSumIn = ISNULL(@numSumIn, 0)
-- update verified stock with verified bad stock (stock entered by user)
-- minus quantity transacted out sales plus quantity in
------------UPDATE losStockVerificationDetail
------------ SET svdVerifiedStock = svdVerifiedBadStock - @numSumOut + @numSumIn
------------ WHERE svdId = @intSvdId
------------ AND svdShopId = @intShopId
------------ AND svdItemId = @intItemId
UPDATE losStockVerificationDetail
SET svdVerifiedStock = svdVerifiedStock - @numSumOut + @numSumIn
WHERE svdId = @intSvdId
AND svdShopId = @intShopId
AND svdItemId = @intItemId
-- update location wise stock
--print ''Starting spShopLocationTotalStockVerification...''
Execute spShopLocationTotalStockVerification @intItemId, @intShopId,
@intSvdId, @dtUpdate, @intArrivalDetailId,
@intIssueDetailId
-- update expiry date wise stock
--print ''Starting spShopExpiryTotalStockVerification...''
Execute spShopExpiryTotalStockVerification @intItemId, @intShopId,
@intSvdId, @dtUpdate, @intExpiryArrivalDetailId,
@intExpiryIssueDetailId
-- set the location stock of all items which are not verified to zero
--print ''Starting spSetZeroLocationStockForNonVerifiedItemsInShop...''
Execute spSetZeroLocationStockForNonVerifiedItemsInShop @intSvdId,
@intShopId, @intIssueDetailID OUTPUT,
@intArrivalDetailId OUTPUT
-- set the expiry stock of all items which are not verified to zero
--print ''Starting spSetZeroExpiryStockForNonVerifiedItemsInShop...''
Execute spSetZeroExpiryStockForNonVerifiedItemsInShop @intSvdId,
@intShopId, @intExpiryIssueDetailID OUTPUT,
@intExpiryArrivalDetailId OUTPUT
Fetch Next From CurDetails Into @intItemId
End
Close CurDetails
Deallocate CurDetails
-- update to stock verified items
UPDATE mosShopStock
SET Stock = svdVerifiedStock
FROM losStockVerificationDetail
WHERE svdId = @intSvdId
AND svdShopId = @intShopId
AND ShopId = svdShopId
AND ItemId = svdItemId
-- insert to stock items
-- which do not exist in stock
INSERT INTO mosShopStock
(ShopID, StockDate, ShipmentID,
ItemID, OpeningStock, Stock, OpeningBadStock,
BadStock, ItemCostPrice)
(SELECT svdShopId, GetDate(),
svdShipmentId, svdItemId, 0, svdVerifiedStock,
0, 0, ItemRate
FROM losStockVerificationDetail v
LEFT OUTER JOIN mosShopStock s
ON v.svdShopId = s.ShopId
AND v.svdItemId = s.ItemId, aItem
WHERE v.svdId = @intSvdId
AND svdShopId = @intShopId
AND svdItemId = aItem.ItemId
AND ShopId IS NULL)
-- insert to stockverification details
-- items which are not verified by user
--RefNo-2------------Starts---------------------------
--RefNo-2(a)
INSERT INTO losStockVerificationDetail
(svdId, svdShopId, svdShipmentId,
svdItemId, svdAvailStock, svdVerifiedStock,
svdAvailBadStock, svdVerifiedBadStock, svdCostPrice)
(SELECT @intSvdId, @intShopId, 1,
vwinquiryshopstock.ItemId, ISNULL(stock,0), 0, ISNULL(badstock,0), 0, ItemRate
FROM vwinquiryshopstock LEFT OUTER JOIN losStockVerificationDetail
ON ItemId = svdItemId
AND @intSvdId = svdId
AND ShopId = svdShopId, aItem
WHERE svdItemId IS NULL
AND ShopId = @intShopId
AND vwinquiryshopstock.ItemId = aItem.ItemId)
--RefNo-2(c)
--INSERT INTO losStockVerificationDetail
--(svdId, svdShopId, svdShipmentId,
--svdItemId, svdAvailStock, svdVerifiedStock,
--svdAvailBadStock, svdVerifiedBadStock, svdCostPrice)
--(SELECT @intSvdId, @intShopId, 1,
--mosShopStock.ItemId, Stock, 0, 0, 0, ItemRate
--FROM mosShopStock LEFT OUTER JOIN losStockVerificationDetail
--ON ItemId = svdItemId
--AND @intSvdId = svdId
--AND ShopId = svdShopId, aItem
--WHERE svdItemId IS NULL
--AND ShopId = @intShopId
--AND mosShopStock.ItemId = aItem.ItemId)
----RefNo-2------Ends-------------------------------
-- to make the item stock 0 of items
-- which are not verified by user
UPDATE mosShopStock
SET Stock = 0
FROM losStockVerificationDetail
WHERE svdId = @intSvdId
AND svdShopId = @intShopId
AND ShopId = svdShopId
AND ItemId = svdItemId
AND svdAvailBadStock = 0
-- Update no. of records in details to
-- last 4 chars of svhFutureVc of Header
SELECT @intCount = COUNT(*) FROM losStockVerificationDetail
WHERE svdId = @intSvdId
AND svdShopId = @intShopId
--RefNo-1---Starts---------------------------------------------
--RefNo-1(a)
UPDATE losStockVerificationDetail  SET svdVerifiedBadStock = 0
WHERE svdId = @intSvdId AND svdShopId = @intShopId
--RefNo-1--Ends------------------------------------------------
UPDATE losStockVerificationHeader
SET svhFutureVc = LEFT(svhFutureVc, 2) +
REPLICATE(''0'', 5 - LEN(CAST(@intCount AS VarChar))) +
CAST(@intCount AS VarChar)
WHERE svhId = @intSvdId
AND svhShopId = @intShopId
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on	: 26/08/2003
-- Created by	: Kishore
-- Comments	: This sp sets the location stock of all items, which
--                are not verified in a total stock verification,
--                to zero
----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]
				(@intSvdId as int,
				 @intGodownId as int,
				 @intIssueDetailId as int OUTPUT,
				 @intArrivalDetailId as int OUTPUT) AS
Begin
	Declare @intItemId as int
	Declare @numCurLocationStock as Numeric(18, 2)
	Declare @intLocationId as int
	
	-- cursor to loop through the non-verified items
	Declare curNonVerifiedItems Cursor For
		SELECT gsItemId FROM moiGodownStock
		WHERE gsGodownId = @intGodownId
		AND gsItemId NOT IN
			(SELECT svdItemId FROM loiStockVerificationDetail
			WHERE svdId = @intSvdId
			AND svdGodownId = @intGodownId)
	
	-- cursor to loop through locations
	Declare curLocations Cursor For
		SELECT lLocationId FROM loiLocation
	Open curLocations
	Open curNonVerifiedItems
	
	-- get first non-verified itemid
	Fetch Next From curNonVerifiedItems Into @intItemID
	While @@fetch_status = 0
	Begin
		Fetch Next From curLocations Into @intLocationId
		
		-- check the item id in each location
		While @@fetch_status = 0
		Begin
			-- first get the currect location stock
		SELECT @numCurLocationStock = qty
		FROM
	         	(SELECT LocationId, GodownId,
			ItemId, SUM(qty) qty
	        	FROM
	       		(SELECT ladLocationId LocationId,
			ladGodownId GodownId, ladItemId ItemId , SUM(ladItemQty) qty
		FROM loiLocationArrivalDetails
	       		WHERE ladGodownId = @intGodownId
		AND ladItemId =  @intItemId
	       		AND ladCancel = 0
			AND ladLocationId = @intLocationId
			GROUP BY ladLocationId, ladGodownId, ladItemId
	        	UNION ALL
			SELECT lidLocationId, lidGodownId, lidItemId, - SUM(lidItemQty)
	        	FROM loiLocationIssueDetails
	        	WHERE lidGodownId = @intGodownId
		        AND lidItemId = @intItemId
			AND lidCancel = 0
			AND lidLocationId = @intLocationId
		        GROUP BY lidLocationId, lidGodownId, lidItemId) a
		        GROUP BY LocationId, GodownId, ItemId
		        HAVING SUM(qty) <> 0 ) b,
		        loiLocation
		WHERE b.LocationId = loiLocation.lLocationId
		        AND b.GodownId = loiLocation.lGodownId		
			AND b.ItemId = @intItemId  -- for extra safety
		
			-- if stock > 0, insert to issue details
			-- otherwise insert to arrival details
			-- to make the net stock zero
			-- Do this only if stock <> 0
			If @numCurLocationStock > 0
			Begin
				INSERT INTO loiLocationIssueDetails
				(lidinterfaceid, lidGodownid, lidTransactionId, liddetailid,
				lidlocationid, liditemid, liditemqty, lidpackingtypeid,
				lidpakingqty, lidcancel, lidadjustment)
				VALUES
				(8010, @intGodownId, @intSvdId, @intIssueDetailId,
				@intLocationId, @intItemId,
				ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
				Set @intIssueDetailId = @intIssueDetailId + 1
			End
			Else If @numCurLocationStock < 0
			Begin
				INSERT INTO loiLocationArrivalDetails
				(ladinterfaceid, ladGodownid, ladtransid, laddetailid,
				ladlocationid, laditemid, laditemqty, ladpackingtypeid,
				ladpakingqty, ladcancel, ladadjustment)
				VALUES
				(8010, @intGodownId, @intSvdId, @intArrivalDetailId,
				@intLocationId, @intItemId,
				ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
				Set @intIssueDetailId = @intIssueDetailId + 1
			End		
			Fetch Next From curLocations Into @intLocationId		End
		
		Fetch Next From curNonVerifiedItems Into @intItemID
	End
	
	Close curLocations
	Deallocate curLocations
	Close curNonVerifiedItems
	Deallocate curNonVerifiedItems
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBankUsed]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBankUsed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spBankUsed    Script Date: 18/01/2003 9:45:43 PM ******/
--modified by : Hariharan
--modofied date : 03/12/2002
CREATE proc [dbo].[spBankUsed] @intCompanyID as int, @strBankname as varchar(200) as
begin
	declare @intBankid as int
	SELECT @intBankid = accountid FROM aaccountmaster WHERE CompanyID = @intCompanyID
	and AccountDesc= @strbankname
	SELECT * FROM aaccountmaster acc, agroupmaster gm WHERE acc.CompanyID = gm.CompanyID and
	acc.groupid = gm.groupid and acc.accountid = @intbankid and acc.CompanyID = @intCompanyID
	and gm.groupid = ( SELECT bankgroupid FROM asettings WHERE CompanyID = @intCompanyID)
	if @@rowcount = 0
		return 0
	
	-- Checking in Bills
	SELECT BankCashAccID FROM Bills WHERE CompanyID = @intCompanyID and
	BankCashAccID = @intBankid
	if @@rowcount > 0
		return 1
	-- Checking in Contra
	SELECT * FROM Contra WHERE CompanyID = @intCompanyID and
	(FROMaccountid = @intBankid or toaccountid = @intBankid)
	if @@rowcount > 0
		return 1	
	-- Checking in receipts
	SELECT BankCashAccountID FROM ReceiptVoucherHeader WHERE CompanyID = @intCompanyID and
	BankCashAccountID = @intBankid
	if @@rowcount > 0
		return 1
	-- Checking in payments
	SELECT phBankCashID FROM ahqPaymentVoucherHeader WHERE phCompanyID = @intCompanyID and
	phBankCashID= @intBankid
	if @@rowcount > 0
		return 1
	-- Checking in accounts invoice
	SELECT BankCashID FROM AccountsInvoiceHeader WHERE CompanyID = @intCompanyID and
	BankCashID= @intBankid
	if @@rowcount > 0
		return 1
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spulShopConsumptionReturn]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopConsumptionReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
-- Created on : 09/02/2011
-- Created By : Nidheesh P V
-- Comment   : To post In-House Retunr transactions
-----------------------------------------------------------------------
-- Modified on : 03/04/2011
-- Modified By : Nidheesh P V
-- Comment   : Added the case of Inhouse Cons Exchange
-----------------------------------------------------------------------
CREATE  proc [dbo].[spulShopConsumptionReturn]
@intCompanyID as int, @intshop as int
as
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intswoid as int,
@intFinancialID as int,
@strswoNo as varchar(50),
@dtswoDate as datetime,
@strRemarks as varchar(500),
@intDepartmentID as int,
@numSwoAmt as numeric(18,2),
@intCompanyCurID as int,
@intinventoryaccid as int,
@dtutime as datetime,
@intfailcount as int,
@strzerorate as varchar(1),
@intExpenseAcid as int,
@numDepExRate as numeric(18, 8),
@numConExRate as numeric(18, 8),
@intCurrencyId as int,
@strExRates VarChar(250),
@numAccExRate Numeric(18, 2),
@numTransEr Numeric(18, 2),
@numAaccAmt Numeric(18, 2),
@numTemp Numeric (18, 2),
@numToDepExRate as numeric(18, 8),
@intToDepId as int,
@ItemwiseAccounting as int ,
@WriteoffQty as numeric(18,2) ,
@costprice as numeric(18,2),
@InhouseAccnt as numeric(18,2) ,
@ItemAmount as numeric(18,2),
@SstrReturnType as varchar(1),
@numSwoAmtRet Numeric(18, 2),
@numSwoAmtExch Numeric(18, 2),
@numAaccAmtRet Numeric(18, 2),
@numAaccAmtExch Numeric(18, 2)
set @numAccExRate = 0.0
set @numTransEr = 0.0
set @numAaccAmt = 0.0
set @numTemp = 0.0
-- get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster WHERE CompanyID = @intCompanyID
select @intinventoryaccid = InventoryID, @strzerorate = substring(isnull(futurevc, ''''), 1, 1) from apackagesettings
select @ItemwiseAccounting=isnull(ItemwiseAccountinginInHousecon,0) from apackagesettings --to check wheather Itemwise accounting is enabled or not
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare swoCur cursor for
SELECT IHRHID, IHRHNo, IHRHDate,  IHRHRemarks, updatetime, IHRHdepartmentid,
isnull(IHRHexpenseaccid,0)  IHRHexpenseaccid,
IHRHconexrate,IHRHdepexrate, IHRHexchangerates,IHRHotherdepid,IHRHtodepexrate
FROM LOs_InHouseCons_ReturnHeader WHERE
IHRHCancelled =0 and IHRHShopID = @intshop and IHRHposted=0
and IHRHConfirmed=1
open SwoCur
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
while @@Fetch_status = 0
begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
-- and the item master table. If so we cannot do any thing in the posting with out item rate.
-- so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
select @intFailcount = count(*) from LOs_InHouseCons_ReturnDetail, aitem where
IHRDID = @intswoiD and IHRDShopID = @intshop and IHRDItemID = itemid
and ( IHRDcostprice =null or IHRDcostprice = 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 LOs_InHouseCons_ReturnDetail set IHRDcostprice = itemrate from
aitem where ( IHRDcostprice =null or IHRDcostprice = 0) and IHRDID = @intswoiD
and IHRDShopID = @intshop and IHRDItemID = itemid
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,
@strRemarks, @intFinancialID, ''sconret'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
--------To get total amount of the items which are returned----------------
select @numSwoAmtRet = isnull(sum(round(IHRDReturnedQty * IHRDcostprice,2)),0) from
LOs_InHouseCons_ReturnDetail swod
where IHRDShopID = @intshop and IHRDID = @intswoid
select @numSwoAmtRet = @numSwoAmtRet + isnull(sum(round(sedExchangeQty * sedcostprice,2)),0) from
losInhouseExchangeDetail swod
where sedBillorExchange=''B'' and sedShopID = @intshop and sedExchangeID = @intswoid
--------To get total amount of the items which are Exchnaged----------------
select @numSwoAmtExch = isnull(sum(round(sedExchangeQty * sedcostprice,2)),0) from
losInhouseExchangeDetail swod
where sedBillorExchange=''E'' and sedShopID = @intshop and sedExchangeID = @intswoid
if @ItemwiseAccounting<> 0 --if itemwise accounting is enabled item amount is posted to corresponding account
begin
declare acntcurs cursor for select IHRDReturnedQty,IHRDcostprice,IHRDInhouseConsAccnt,IHRDRetrnOrExch
FROM LOs_InHouseCons_ReturnDetail where IHRDShopID = @intshop and IHRDID = @intswoid
open acntcurs
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt,@SstrReturnType
if isnull(@InhouseAccnt,0)= 0 --to check wheather there is unposted transaction done bofore setting the itemwise accounting
begin
while @@fetch_status=0
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @InhouseAccnt
---ref-1
set @ItemAmount=round(isnull(sum(@WriteoffQty * @costprice),0) ,2)
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@ItemAmount,@numAaccAmt output
if @SstrReturnType is null or @SstrReturnType=''B''-----INHOUSE CONS RETURN-----
begin
-- Crediting the stock consumption accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@InhouseAccnt ,
round(@ItemAmount * @numConExRate,2), round(@numAaccAmt,2),
round(@ItemAmount * @numDepExRate,2), @intToDepId)
end
if @SstrReturnType=''E''  -----INHOUSE CONS EXCHANGE-----
begin
-- Debiting the stock consumption accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@InhouseAccnt ,
round(@ItemAmount * @numConExRate,2), round(@numAaccAmt,2),
round(@ItemAmount * @numDepExRate,2), @intToDepId)
end
set @intJournalDetailID = @intJournalDetailID + 1
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt,@SstrReturnType
end
if @intDepartmentID<> @intToDepId --to post to control acc in the case of Itemwise is enabled and different departmnts
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
if @SstrReturnType is null or @SstrReturnType=''B''-----INHOUSE CONS RETURN-----
begin
-- Debiting the control accid  for the current department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- Crediting the stock consumption accid for todept
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
end
if @SstrReturnType=''E''-----INHOUSE CONS EXCHANGE-----
begin
-- Crediting the control accid  for the current department
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- Dediting the stock consumption accid for todept
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), @numAaccAmt,
round(@numSwoAmt * @numDepExRate,2), @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
end
end
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
if @SstrReturnType is null or @SstrReturnType=''B''-----INHOUSE CONS RETURN-----
begin
-- Crediting the stock consumption accid   -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), round(@numAaccAmt,2),
round(@numSwoAmt * @numDepExRate,2), @intDepartmentId)
END
if @SstrReturnType=''E''-----INHOUSE CONS EXCHANGE-----
begin
-- Dediting the stock consumption accid   -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmt * @numConExRate,2), round(@numAaccAmt,2),
round(@numSwoAmt * @numDepExRate,2), @intDepartmentId)
end
set @intJournalDetailID = @intJournalDetailID + 1
end
close acntcurs
deallocate acntcurs
end
else ---ELSE PART OF ITEMWISE ACCOUNTING CHECKING-----------
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,@numSwoAmtRet,
@numAaccAmtRet output
exec spConvertCurrency @numTransEr, @numAccExRate,@numSwoAmtExch,
@numAaccAmtExch output
if @SstrReturnType is null or @SstrReturnType=''B''-----INHOUSE CONS RETURN-----
begin
-- Crediting the stock consumption accid    -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
round(@numSwoAmtRet * @numConExRate,2), round(@numAaccAmtRet,2),
round(@numSwoAmtRet * @numDepExRate,2), @intDepartmentId)
end
if @SstrReturnType=''E''-----INHOUSE CONS EXCHANGE-----
begin
-- Dediting the stock consumption accid    -ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
round(@numSwoAmtExch * @numConExRate,2), round(@numAaccAmtExch,2),
round(@numSwoAmtExch * @numDepExRate,2), @intDepartmentId)
end
set @intJournalDetailID = @intJournalDetailID + 1
end ---END OF ITEMWISE ACCOUNTING CHECKING-----------------
if @SstrReturnType is null or @SstrReturnType=''B''-----INHOUSE CONS RETURN-----
begin
-- Debiting the inventory acc id
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount,
actualamount, DepAmount,
departmentid) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intinventoryaccid, round(@numSwoAmtRet * @numConExRate,2), round(@numSwoAmtRet,2),
round(@numSwoAmtRet * @numDepExRate,2), @intdepartmentid )
end
if @SstrReturnType=''E''-----INHOUSE CONS EXCHANGE-----
begin
-- Crediting the inventory acc id
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount,
actualamount, DepAmount,
departmentid) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intinventoryaccid, round(@numSwoAmtExch * @numConExRate,2), round(@numSwoAmtExch,2),
round(@numSwoAmtExch * @numDepExRate,2), @intdepartmentid )
end
update LOs_InHouseCons_ReturnHeader set IHRHposted = 1
WHERE IHRHID = @intswoID and IHRHShopID = @intShop
set @intJournalID = @intJournalID + 1
end -- for item rate=0 check hari 011213
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
end -- CUR END
Close swoCur
Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULShopGR]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULShopGR]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
-- Modified on : 18/07/02
-- modified by      : leo
-- Assumption     : the concept of damage qty is not handled here
-------------------------------
-- Modified on      : 01/01/2003
-- Modified by      : Kishore
-- Comments         : Added amount conversion
-------------------------------
-- Modified on      : 03/06/2003
-- Modified by      : R Harikrishnan
-- Comments         : Added @depExRate in last Fetch next
-------------------------------
-- Modified on      : 10/06/2003
-- Modified by      : Kishore
-- Comments         : Removed the multiplicaiton on grndunitprice with grndquantity
--                    as the grndunitprice it self is amount.(on comparison with v2)
--- RefNo-2
--Modified on      : 18-09-2011,10-10-2011,22-11-2011,09-01-12
--Modified by    : jyothish SR
--Comments        : added for GST ,postGruopid added  , tax varible intaily set zero
-------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spULShopGR] ( @intCompanyId as int, @intShopID as int) as
begin
Declare
@intCompanyCurID as int,
@intGrnAcId as int,
@intTransCurID as int,
@intItemID as int,
@numUnitPrice as numeric(18,2),
@numAmount as numeric(18,2),
@numTransrate as numeric(18,2),
@numBuyingRate as numeric(18,2),
@numAverageRate as numeric(18,2),
@intJournalDetailID as int,
@intFinancialID as int,
@intDepartmentId as int,
@intJournalID as int,
@intGRNID as int,
@intcustomerid as int,
@intQty as int,
@dtInvoiceDate as datetime,
@strGRNNo as varchar(50),
@intInvoiceID as int,
@dtJournalDate as datetime,
@dtGRNDate as datetime,
@numer as numeric (28,8),
@intCostOfGoodsAccId as int,
@intInventoryAccId as int,
@dtutime as datetime,
@numReturnCost as numeric(18,2) -- hari for return damage 011213
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)
--
--RefNo-2-added for gst--
declare @IntCount as int
declare @TaxCurrId as int
declare @numTaxEr as numeric(18,2)
declare @TaxAcntId as int
declare @TaxCatId as int
declare @TaxAmount as numeric(18,2)
declare @CTaxAmount as numeric(18,2)
declare @DTaxAmount as numeric(18,2)
declare @TaxAccAmount as numeric(18,2)
declare @CTotalTaxAmount as numeric(18,2)
declare @DTotalTaxAmount as numeric(18,2)
declare @TotalTaxAmnt as numeric(18,2)
declare @TotalAccTax as numeric(18,2)
-----------------------------
declare  @Taxtable table
(
taxTransId int,
taxShopId int,
taxCateId int,
taxAccntId int,
taxAmount numeric(18,2),
CtaxAmount numeric(18,2),
DtaxAmount numeric(18,2)
)
--RefNo-2-added for gst--
--RefNo-2---to insert tax cateid,tax A/C & tax amount in the table variable---
insert into @Taxtable
select GrnhGoodsreturnnoteID,grnhShopid,idItemTaxCategory,TaxAccountId,isnull(sum(idItemTaxAmount),0)as TaxAmount,
sum(isnull(idItemTaxAmount,0)* grnhExchangeRate) as ComTaxAmount,
sum(isnull(idItemTaxAmount,0)* grnhdepExRate) as DepTaxAmount
FROM losgoodsreturnnoteheader ih inner join losgoodsreturnnotedetail id
on ih.GrnhGoodsreturnnoteID = id.GRNDReturnNoteID and ih.grnhShopid = id.GRNDShopid
inner join ataxcategorymaster tc on   idItemTaxCategory=TaxId
and TaxCancelled=0 and TaxAccountable=1
WHERE GrnhCancel =0 and GrnhPosted =0
and isnull(idItemTaxCategory,0)<>0
-- and ih.ihCompanyId = @intCompanyID
and ih.grnhShopid = @intshopid
group by  idItemTaxCategory,TaxAccountId,GrnhGoodsreturnnoteID,grnhShopid
---RefNo-2----
-- to get company currencyid
SELECT @intCompanyCurID = CurrencyID
FROM aCompanyMaster
WHERE CompanyId = @intCompanyId
select @intCostOfGoodsAccId = CostOfGoodsId, @intInventoryAccId = InventoryId
from apackagesettings
where CompanyId = @intCompanyId
-- to get the maximum Journal id from journal table
SELECT @intJournalID = isnull(max(JournalID),0)
from MOajournalheader
where CompanyId = @intCompanyId
set @intJournalid = @intJournalid + 1
Declare GoodsReturnNoteHeaderCur Cursor for
SELECT grnh.grnhGoodsReturnNoteID, grnhGoodsReturnNoteNo, grnhGoodsReturnNoteDate,
grnhCustomerID, GrnReturnAccId, grnhexchangerate, updatetime, grnhDepartmentId,
grnhDepExRate,grnexchangerates
FROM LOsGoodsReturnNoteHeader grnh
WHERE grnh.grnhShopid = @intshopid and grnhPosted = 0 and grnhCancel = 0
open GoodsReturnNoteHeaderCur
fetch next from GoodsReturnNoteHeaderCur into
@intGRNID, @strGRNNo, @dtGRNDate, @intCustomerID, @intGrnAcId ,
@numer, @dtutime, @intDepartmentId, @depExRate, @strExRates
while @@fetch_status = 0
begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
SELECT @intTransCurID = CurrencyID FROM aCustomerMaster
WHERE CompanyId = @intCompanyId and customerid = @intcustomerid
exec spReturnExRate @intTransCurID, @strExRates,
@numTransEr output
select @intFinancialID = financialid from vwfinyearperiod where @dtgrnDate between
sdate and edate --and CurFinancialYear =1     hari commented
-- hari included 011213
select @numReturnCost = isnull(sum(GRNDQuantity * grncostprice), 0)
from losgoodsreturnnotedetail
where GRNDReturnNoteID=@intGRNID and GRNDShopid = @intshopid      group by GRNDShopid, GRNDReturnNoteID
--isnull(sum (GRNDunitprice*GRNDQuantity),0)
select @numAmount = isnull(sum (GRNDunitprice*1),0)
from losgoodsreturnnotedetail
where GRNDReturnNoteID=@intGRNID and GRNDShopid = @intshopid
group by GRNDShopid, GRNDReturnNoteID
insert into moaJournalHeader (JournalID, CompanyId, JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,cancel,realised, updatetime)
values (@intJournalID, @intCompanyId, @dtgrnDate, @strgrnNo,
''Goods returned'', @intFinancialID,''POSGRN'', @intTransCurID,0,0, @dtutime)
SET @numTransRate = @numer
SET @intJournalDetailID = 1
INSERT into MOaJournalDetails (JournalDetailID, JournalID, JournalCredit,
CustomerID,
Amount, ActualAmount, DepAmount, CompanyId, DepartmentId,PostGroup)
VALUES (@intJournalDetailID, @intJournalID, 1, @intCustomerId,
(@numAmount * @numTransRate), @numAmount,
@numAmount * @depExRate,
@intCompanyId, @intDepartmentId,1)
SET @intJournalDetailID = @intJournalDetailID + 1
--FOR CONVERTING AMOUNT--->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intGrnAcId
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr, @numAccEr, @NumAmount,
@numAaccAmt output
--RefNo-2--------------------------------------
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),@DTotalTaxAmount=sum(isnull(DtaxAmount,0))
from @Taxtable where taxTransId=@intGRNID and taxShopId=@intShopId group by taxTransId,taxShopId
if @TotalTaxAmnt is null
begin
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
end
--TO CONVERT INTO SALE A/C CURRENCY---
INSERT into MOaJournalDetails(JournalDetailID, JournalID, JournalCredit,
AccountID,
Amount, ActualAmount, DepAmount, CompanyId, DepartmentId,PostGroup)
VALUES (@intJournalDetailID, @intJournalID, 0, @intGrnAcId,
((@numAmount * @numTransRate))-(@CTotalTaxAmount), (@numAaccAmt-@TotalTaxAmnt),
(@NumAmount * @depExRate)-(@DTotalTaxAmount),
@intCompanyId , @intDepartmentId,1)
--RefNo-2-----------------------------------
select @IntCount=count(*) from @Taxtable
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable where taxTransId=@intGRNID and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable where taxTransId=@intGRNID and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strExRates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
/* crediting TO TAX ACCOUNT   */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@TaxAcntId, @CTaxAmount,
@TaxAccAmount,@intDepartmentID, @DTaxAmount, 1)
end
delete from @Taxtable where taxTransId=@intGRNID and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
SET @intJournalDetailID = @intJournalDetailID + 1
if @numReturnCost <> 0
begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intINVentoryAccID
exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output
exec spConvertCurrency @numTransEr, @numAccEr,  @numReturnCost,
@numAaccAmt output
/* debiting the INVENTORY with the full cost Amount with items returned with out damage*/
insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount,
DepartmentId,PostGroup)
values (@intJournalId, @intjournalDetailID, @intCompanyId, 0,
@intINVentoryAccId, @numReturnCost * @numEr, @numAaccAmt,
@numReturnCost * @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, @numReturnCost,
@numAaccAmt output
-- credit THE COST OF GOODS ACCOUNT
insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, DepartmentId,PostGroup)
values (@intJournalID, @intjournalDetailID, @intCompanyId, 1,
@intCostOfGoodsAccId, @numReturnCost * @numEr, @numAaccAmt,
@numReturnCost * @depExRate,
@intDepartmentId,2)
end
SET @intJournalID = @intJournalID + 1
update LOsGoodsReturnNoteHeader set grnhPosted = 1
WHERE GrnCompanyId = @intCompanyId and GrnhGoodsreturnnoteID = @intgrnid and
grnhShopid = @intshopid
fetch next from GoodsReturnNoteHeaderCur into
@intGRNID, @strGRNNo, @dtGRNDate, @intCustomerID, @intGrnAcId,
@numer, @dtutime, @intDepartmentId, @depExRate, @strExRates
end
close GoodsReturnNoteHeaderCur
deallocate GoodsReturnNoteHeaderCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUL_FandB_Bill]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUL_FandB_Bill]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Regin
-- Create date: 01-10-2010
-- Description: To post FandB bill
---Modifeid  : Jyothish S R
---Modifeid  : 24-11-2010
------------------------------------------------
--Ref-01
--Modified By : Benzigar S D
--Modified On : 03/08/2011
--Comment     : Corrected F&B Posting
-- =============================================
-- spUL_FandB_Bill 1, 15
Create PROCEDURE [dbo].[spUL_FandB_Bill]
@intCompanyId INT,
@intShopId INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result SETs FROM
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @intSalesAccountID AS INT
DECLARE @intCashAccountID AS INT
DECLARE @intJournalID AS INT
DECLARE @intJournalDetailID AS INT
DECLARE @intFinancialID AS INT
DECLARE @dtposDate AS DATETIME
DECLARE @strposNo AS VARCHAR(50)
DECLARE @intposid AS INT
DECLARE @intDiscountAccountID AS INT
DECLARE @intDepartmentID AS INT
DECLARE @intSubDepartmentID AS INT
DECLARE @numTotalSalesValue AS NUMERIC(18,2)
DECLARE @numtotalcostValue AS NUMERIC(18,2)
DECLARE @intComCurID AS INT
DECLARE @intinventoryaccid AS INT
DECLARE @intcostofgoodsaccid AS INT
DECLARE @numactualamt AS NUMERIC(18,2)
DECLARE @strshop AS VARCHAR(100)
DECLARE @dtUpdateTime AS DATETIME
DECLARE @straccountcode AS VARCHAR(25)
DECLARE @intpltransaccid AS VARCHAR(25)
DECLARE @intcomdeptid AS VARCHAR(25)
DECLARE @numprofittrans AS NUMERIC(7,5)
DECLARE @intcomprofitaccid AS INT
DECLARE @depsalesval AS NUMERIC(18,2)
DECLARE @depcostval AS NUMERIC(18,2)
DECLARE @actcostamt AS NUMERIC(18,2)
DECLARE @numTransEr AS NUMERIC(18,2)
DECLARE @numAccEr AS NUMERIC(18,2)
DECLARE @numAaccAmt AS NUMERIC(18,2)
DECLARE @intCurrencyid AS INT
DECLARE @strexrates AS VARCHAR(250)
DECLARE @bitCashSale AS BIT
DECLARE @intCustomerId AS INT
DECLARE @intVoucherId AS INT
-- Getting the maximum Journal ID FROM journal table
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader
WHERE CompanyID = @intCompanyID
SELECT @intcomcurid = currencyid FROM acompanymaster
WHERE companyid = @intcompanyid
SELECT @intdiscountaccountid = discountaccountid,
@numprofittrans = isnull(RevisedCostPricePercent,0)
FROM ashops WHERE shopid = @intshopid
SELECT @strshop = shopname, @intSubDepartmentID =SubDepartmentID FROM ashops WHERE shopid = @intshopid
SELECT @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid,
@intpltransaccid = profittransfercontrolacc, @intcomdeptid  = companydepartment,
@intcomprofitaccid = compprofitshareacc FROM
apackageSETtings WHERE companyid = @intcompanyid
SET @intJournalID = @intJournalID + 1
SET @numTotalSalesValue = 0.0
SET @numTotalcostValue = 0.0
DECLARE poscur CURSOR FOR
--Ref-01 commented
/* SELECT poshBillID, poshBillNo, poshBillDate, poshCashSale, isnull(poshvoucherid,0), poshCustomerId,
poshCashAccID, poshSalesAccID, isnull(sum(fb_pd_rate),0) * poshExchangeRate salesamt,
isnull(sum((KotOrder) * fb_CostPrice), 0) * poshExchangeRate costamt,
isnull(sum(fb_pd_rate),0) actsalesamt,
isnull(sum((KotOrder) * fb_CostPrice), 0) actcostamt,
UPDATEtime, AccountCode, poshDepartmentid,
isnull(sum(fb_pd_rate),0) * poshdepexrate depSalesAmt,
isnull(sum((KotOrder) * fb_CostPrice), 0) * poshdepexrate depCostAmt,
poshexchangerates
FROM losPosFandBHeader h
inner join fb_ProcessDetail d ON h.poshShopID=d.fb_pd_outletid and h.poshBillID=d.fb_pd_processid
inner join fb_Alternate a ON d.fb_pd_outletid=a.Fb_outletid and d.fb_pd_kotid=a.fb_kotID
left outer join aAccountMaster am ON h.poshCashAccID=am.AccountID
WHERE h.poshCancelled=0 and h.poshPosted = 0
and h.poshCompanyID = @intCompanyId and h.poshShopID = @intShopId
GROUP BY poshBillID, poshBillNo, poshBillDate, poshCashSale, poshvoucherid, poshCustomerId,
poshCashAccID, poshSalesAccID, poshExchangeRate, UPDATEtime, poshcashaccid,
poshDepartmentid, poshdepexrate, poshexchangerates,AccountCode */
-----------------------------------------------------------------------------
--Ref-01
SELECT poshBillID, poshBillNo, poshBillDate, poshCashSale, isnull(poshvoucherid,0), poshCustomerId,
poshCashAccID, poshSalesAccID, isnull(sum(fb_pd_rate*fb_pd_reusedqty),0) * poshExchangeRate salesamt,
isnull(sum((fb_pd_reusedqty) * fb_pd_cost), 0) * poshExchangeRate costamt,
isnull(sum(fb_pd_rate*fb_pd_reusedqty),0) actsalesamt,
isnull(sum((fb_pd_reusedqty) * fb_pd_cost), 0) actcostamt,
UPDATEtime, AccountCode, poshDepartmentid,
isnull(sum(fb_pd_rate*fb_pd_reusedqty),0) * poshdepexrate depSalesAmt,
isnull(sum((fb_pd_reusedqty) * fb_pd_cost), 0) * poshdepexrate depCostAmt,
poshexchangerates
FROM losPosFandBHeader h
inner join fb_ProcessDetail d ON h.poshShopID=d.fb_pd_outletid and h.poshBillID=d.fb_pd_processid
--inner join fb_Alternate a ON d.fb_pd_outletid=a.Fb_outletid and d.fb_pd_kotid=a.fb_kotID
left outer join aAccountMaster am ON h.poshCashAccID=am.AccountID
WHERE h.poshCancelled=0 and h.poshPosted = 0
and h.poshCompanyID = @intCompanyId and h.poshShopID = @intShopId
and poshShopID=fb_pd_outletid
and poshBillID=fb_pd_processid
GROUP BY poshBillID, poshBillNo, poshBillDate, poshCashSale, poshvoucherid, poshCustomerId,
poshCashAccID, poshSalesAccID, poshExchangeRate, UPDATEtime, poshcashaccid,
poshDepartmentid, poshdepexrate, poshexchangerates,AccountCode
-----------------------------------------------------------------------------
OPEN poscur
FETCH NEXT FROM poscur INTO @intposid, @strposNo, @dtposdate, @bitCashSale,
@intVoucherId, @intCustomerId, @intCashAccountID, @intsalesaccountid,
@numTotalSalesValue, @numTotalcostValue, @numactualamt, @actcostamt, @dtUpdateTime, @straccountcode,
@intdepartmentid, @depsalesval, @depcostval, @strexrates
WHILE @@FETCH_status = 0
BEGIN
--TO GET TRANSACTION EXCHANGE RATE ---->
SELECT @intCurrencyid = currencyid FROM aaccountmaster a WHERE
accountid = @intCashAccountID
EXEC spReturnExrate @intcurrencyid, @strexrates, @numTransEr OUTPUT
--TO GET TRANSACTION EXCHANGE RATE <----
-- to take financialid FROM afinancialyear table with curfinancialyear=1
SELECT @intFinancialID = financialid FROM vwfinyearperiod WHERE @dtposdate between sdate and edate
INSERT INTO moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, UPDATEtime) VALUES
(@intJournalID, @intCompanyID, @dtposDate,
@strposNo, ''F&B Bill'',@intFinancialID,''fbBill'', @intcomCurID,@dtposdate,  @dtUpdateTime)
SET @intJournalDetailID = 1
SELECT @intCurrencyid = currencyid FROM aaccountmaster a WHERE
accountid = @intSalesAccountID
EXEC spReturnExrate @intcurrencyid, @strexrates, @numAccEr OUTPUT
EXEC spconvertcurrency @numTransEr , @numAccEr , @numactualamt,
@numAaccAmt OUTPUT
-- If not voucher sale, credit sales account and debit either cash acc or customer.
-- Note: As cash is not received in voucher sale, cash acc and sales acc are not affected.
IF @intVoucherId = 0
BEGIN
-- 1. CREDITING SALES ACCOUNT WITH SALES VALUE
INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intSalesAccountID, @numTotalSalesValue, @numAaccAmt,@intDepartmentID,
@depsalesval ,@intSubDepartmentID)
SET @intJournalDetailID = @intJournalDetailID +1
-- 2. IF CASH SALE, DEBIT CASH ACCOUNT WITH SALES VALUE
--    ELSE, DEBIL CUSTOMER WITH SALES VALUE
if @bitCashSale=1 -- CASH SALE
BEGIN
INSERT INTO moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcashaccountid, @numTotalSalesValue , @numactualamt,
@intDepartmentID, @depsalesval, @intSubDepartmentID)
END
ELSE -- CREDIT SALE
BEGIN
INSERT INTO moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCredit, CustomerId, Amount, actualAmount,departmentID, depamount,
SubDepartmentID, PostGroup)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intCustomerId, @numTotalSalesValue , @numactualamt,
@intDepartmentID, @depsalesval, @intSubDepartmentID, 2)
END
SET @intJournalDetailID = @intJournalDetailID +1
END -- End of IF @intVoucherId = 0
SELECT @intCurrencyid = currencyid FROM aaccountmaster a WHERE
accountid = @intINVentoryAccID
EXEC spReturnExrate @intcurrencyid, @strexrates, @numAccEr OUTPUT
EXEC spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt OUTPUT
-- 3. CREDITING INVENTORY WITH COST VALUE
INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intINVentoryAccID, @numTotalcostValue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID)
SET @intJournalDetailID = @intJournalDetailID +1
SELECT @intCurrencyid = currencyid FROM aaccountmaster a WHERE
accountid = @intcostofgoodsaccid
EXEC spReturnExrate @intcurrencyid, @strexrates, @numAccEr OUTPUT
EXEC spconvertcurrency @numTransEr , @numAccEr , @actcostamt,
@numAaccAmt OUTPUT
-- 4. CREDITING THE COST OF GOODS ACCOUNT WITH COST VALUE
INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount,SubDepartmentID)
VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcostofgoodsaccid, @numtotalcostvalue, @numAaccAmt,
@intDepartmentID, @depCostVal,@intSubDepartmentID)
SET @intJournalID = @intJournalID + 1
FETCH NEXT FROM poscur INTO @intposid, @strposNo, @dtposdate, @bitCashSale,
@intVoucherId, @intCustomerId, @intCashAccountID, @intsalesaccountid,
@numTotalSalesValue, @numTotalcostValue, @numactualamt, @actcostamt, @dtUpdateTime, @straccountcode,
@intdepartmentid, @depsalesval, @depcostval, @strexrates
UPDATE losPosFandBHeader SET poshPosted =1
WHERE poshCompanyID=@intCompanyId and poshShopID=@intShopId and poshBillID=@intposid
end -- End of WHILE @@FETCH_status = 0
CLOSE poscur
DEALLOCATE poscur
-- mark the transaction as posted
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spulGodownPurchReturn]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulGodownPurchReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created 	: 18/09/02
--Created by 	: Hariharan R
-------------------------------------
-- Modified on  : 02/01/2003
-- Modified by  : Kishore
-- Comment      : Inserted DepAmount and added Amount conversion
--		: whType field is added to identify the purchase returns
-------------------------------------
CREATE proc [dbo].[spulGodownPurchReturn] @intCompanyId as int, @intGodownId as int as
begin
	Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intswoid as int,
	@intFinancialID as int,
	@strswoNo as varchar(50),
	@dtswoDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentId as int,
	@numSwoAmt as numeric(18, 2),
	@intCompanyCurID as int,
	@intInventoryAccId as int,
	@intPurchRetAccid as int,
	@dtutime as datetime,
	@strzerorate as varchar(1),
	@intFailcount as int,
	@numDepExRate as numeric(18, 8),
	@numConExRate as numeric(18, 8),
	@intCurrencyId as int,
	@strExRates VarChar(250),	
	@numAccExRate Numeric(18, 2),
	@numTransEr Numeric(18, 2),
	@numAaccAmt Numeric(18, 2)
	--get the companyCurrencyID
	SELECT @intCompanyCurID = CurrencyID
		FROM acompanymaster
		WHERE CompanyId = @intCompanyId
	select @intPurchRetAccid = PurchaseRtnAccID from aPackageSettings where
		CompanyId = @intCompanyId
	select @intInventoryAccId = InventoryID,
		@strzerorate = substring(isnull(futurevc, ''''), 1, 1)
		from aPackageSettings
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0)
		FROM moaJournalHeader
		WHERE CompanyId = @intCompanyId
	set @intJournalID = @intJournalID + 1
	Declare swoCur cursor for
		SELECT whID, whNo, whDate,  whRemarks, UpdateTime, whConExRate,
		whDepExRate, whDepartmentId, whExchangeRates
		FROM loiWriteOffHeader WHERE whCancelled = 0 and whGodownId = @intGodownId
		and whPosted = 0 and whType =''R''
	open swocur
	fetch next FROM  swoCur
		into @intswoiD, @strswono, @dtswoDate, @strRemarks,
		@dtutime, @numConExRate, @numDepExRate, @intDepartmentId, @strExRates
	while @@Fetch_status = 0	
	begin	-- cur begin
	
		select @intCurrencyId = CurrencyId
			from aAccountMaster
			where AccountId = @intInventoryAccId
			and CompanyId = @intCompanyId
		
		exec spReturnExRate @intCurrencyId, @strExRates,
			@numTransEr output	
		-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
		-- to check the no of records with item rate =0 or null in both the detail table
		-- and the item master table. If so we cannot do any thing in the posting with out item rate.
		-- so that transaction will be avoided from posting
		-- hariharan 011211
		set @intFailcount = 0
		select @intFailcount = count(*) from loiWriteOffDetail, aItem where
			wdID = @intswoiD and wdGodownId = @intGodownId and wdItemId = ItemId
			and ( wdCostPrice =null or wdCostPrice =0) and (itemrate=0 or itemrate is null)
		-- to allow to proceed if allow zero rate condition given - hari 020905
		if @strzerorate = ''z''
		begin
		 	set @intFailcount=0
		end
		if @intfailcount = 0 -- for item rate = 0 check
		begin
			-- to update the item rate to the gadCostPrice 		
			update loiWriteOffDetail set wdCostPrice = itemrate from
				aItem where ( wdCostPrice =null or wdCostPrice = 0) and wdID = @intswoiD and
				wdGodownId = @intGodownId and wdItemId = ItemId
			insert into moaJournalHeader (JournalID, CompanyId, JournalDate,
				referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
				values (@intJournalID, @intCompanyId, @dtswoDate, @strswono,
				@strRemarks, @intFinancialID, ''invret'', @intcompanycurID, @dtswoDate, @dtutime )
			set @intJournalDetailID = 1
			-- getting the total amount with qty and item cost price
			select @numSwoAmt = isnull(sum(wdwriteoffqty * wdCostPrice),0) from
				loiWriteOffDetail swod	where wdGodownId = @intGodownId and wdid = @intswoid
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intPurchRetAccId
		
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output	
										
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numSwoAmt,
					@numAaccAmt output
			-- debiting the Purchase Return accid
			insert into moaJournalDetails
				(JournalID, journaldetailID, CompanyId,
				JournalCrEDit, AccountID, Amount, actualAmount,
				DepAmount, DepartmentId)
				values
				(@intJournalID, @intjournalDetailID, @intCompanyId,
				0, @intPurchRetAccid, @numSwoAmt * @numConExRate, @numAaccAmt,
				@numSwoAmt * @numDepExRate,  @intDepartmentId)	
			set @intJournalDetailID = @intJournalDetailID + 1
			-- credit the inventory acc id
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
				JournalCrEDit, accountid, Amount, actualamount,
				DepAmount, DepartmentId)
				values
				(@intJournalID, @intjournalDetailID, @intCompanyId, 1,
				@intInventoryAccId, @numSwoAmt * @numConExRate, @numSwoAmt,
				@numSwoAmt * @numDepExRate, @intDepartmentId )
			update loiWriteOffHeader set whPosted = 1 WHERE WhID =
				@intswoID and whGodownId = @intGodownId
			set @intJournalId = @intJournalId + 1	
		end -- for item rate = 0 check
		fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate,
			@strRemarks, @dtutime, @numConExRate,
			@numDepExRate, @intDepartmentId, @strExRates
	end	-- CUR END
	Close swoCur
	Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULExchange]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULExchange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULInvSWO]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULInvSWO]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on      : 02/02/2004
-- Modified by      : Hariharan
-- Comments         : Considered the type of transaction with whType field
----------------------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spULInvSWO] @intCompanyID as int, @intgodownid as int AS
begin
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intswoid as int,
@intFinancialID as int,
@strswoNo as varchar(50),
@dtswoDate as datetime,
@strRemarks as varchar(500),
@intDepartmentID as int,
@numSwoAmt as numeric(18,2),
@intCompanyCurID as int,
@intinventoryaccid as int,
@intSwoAccId as int,
@dtutime as datetime,
@strzerorate as varchar(1),
@intFailcount as int,
@numDepExRate as numeric(18, 8),
@numConExRate as numeric(18, 8),
@intCurrencyId as int,
@strExRates VarChar(250),
@numAccExRate Numeric(18, 2),
@numTransEr Numeric(18, 2),
@numAaccAmt Numeric(18, 2),
@numTemp Numeric (18, 2),
@chrWOType as char(1),
@intPurchaseReturnAcc as int
-- get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster
WHERE CompanyID = @intCompanyID
select @intSwoAccId = stockwriteoffaccid from agodown where godownid = @intgodownid
select @intinventoryaccid = InventoryID,
@strzerorate = substring(isnull(futurevc,''''),1,1),
@intPurchaseReturnAcc = convert(int, futurenum) from apackagesettings
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare swoCur cursor for
SELECT whID, whno, whdate,  whremarks, updatetime, whdepartmentid,
whConExRate, whDepExRate, whExchangeRates,whType --substring(isnull(whFutureVc, ''w''), 1, 1)
FROM loiwriteoffheader
WHERE whcancellED = 0 and whgodownid = @intgodownid and whposted = 0
and whType = ''W''
open swocur
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate,
@strRemarks, @dtutime, @intDepartmentID, @numConExRate,
@numDepExRate, @strExRates, @chrWOType
while @@Fetch_status = 0
begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster a
where a.AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
--to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid
from vwfinyearperiod
where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
--and the item master table. If so we cannot do any thing in the posting with out item rate.
--so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
select @intFailcount = count(*) from loiwriteoffdetail, aitem where
wdID = @intswoiD and wdGodownID = @intgodownid and wdItemID = itemid
and ( wdcostprice =null or wdcostprice =0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
begin
set @intFailcount=0
end
if @intfailcount = 0 -- for item rate = 0 check
begin
-- to update the item rate to the gadcostprice
update loiwriteoffdetail set wdcostprice = itemrate from
aitem where ( wdcostprice =null or wdcostprice =0) and wdID = @intswoiD and
wdGodownID = @intgodownid and wdItemID = itemid
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,
@strRemarks, @intFinancialID, ''iswo'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
--getting the total amount with qty and item cost price
select @numSwoAmt = isnull(sum(wdwriteoffqty * wdcostprice),0) from
loiwriteoffdetail swod where wdgodownid = @intgodownid and wdid = @intswoid
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intSwoAccId
and CompanyID = @intCompanyID
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
if @chrWOType = ''w''
Begin -- Normal write off transaction
-- debiting hte stock writeoff accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount, departmentID) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intSwoAccId,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intdepartmentid )
End
Else -- if the transaction is purchase return
Begin
-- debiting hte stock purchase return accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount, departmentID) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intPurchaseReturnAcc,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intdepartmentid )
End
set @intJournalDetailID = @intJournalDetailID +1
-- credit the inventory acc id
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount,
actualamount, DepAmount, departmentid) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intinventoryaccid, @numSwoAmt * @numConExRate,
@numSwoAmt, @numSwoAmt * @numDepExRate, @intdepartmentid )
update loiwriteoffheader set whposted = 1 WHERE WhID =
@intswoID and whgodownid = @intgodownid
set @intJournalID = @intJournalID + 1
end -- for item rate = 0 check
fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
@dtutime, @intDepartmentID, @numConExRate,
@numDepExRate, @strExRates, @chrWOType
end -- CUR END
Close swoCur
Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlInvSv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvSv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on      : 07/01/2003, 18/08/2003
-- Modified by      : Hariharan R, Hariharan R
-- Comments         : Added code to insert depAmount and to convert amount
-- Verified By Hariharan on 07/01/2003
-- Cursor fetching corrected in the second statement to aviod error reported from simdi
---------------------------------------------------------------------------------
CREATE proc [dbo].[spUlInvSv] @intCompanyID as int, @intGodownId 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 agodown where GodownId = @intGodownId
	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 loiStockVerificationHeader
		WHERE svhcancelled =0 and svhGodownId = @intGodownId 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 a
			where a.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 loistockverificationdetail, aitem where
			svdid = @intsviD and svdGodownId = @intGodownId and svditemid = itemid
			and (svdcostprice=null or svdcostprice=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 hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update loistockverificationdetail set svdcostprice = itemrate from
				aitem where (svdcostprice=null or svdcostprice=0) and svdid= @intsviD
				and svdGodownId = @intGodownId and svditemid = itemid
			--getting the total amount with qty and item cost price
			select @numsvdeductAmt = isnull(sum(( svdAvailStock - svdVerifiedStock)* svdcostprice),0)
				from loistockverificationdetail svd where svdGodownId = @intGodownId and svdid = @intsvid
				and svdAvailStock > svdVerifiedStock
			select  @numsvaddAmt = isnull(sum((svdVerifiedStock - svdAvailStock )* svdcostprice),0)
				from loistockverificationdetail svd where svdGodownId = @intGodownId 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, ''isv'', @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
					-- get into a variable as expressions cannot be
					-- passed as parameters of sp					
					set @numTemp = (@numsvdeductamt - @numsvaddamt)
					exec spReturnExRate @intCurrencyId, @strExRates,
						@numAccExRate output
					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 loiStockVerificationHeader  set svhposted = 1 WHERE svhid = @intsvID and svhGodownId = @intGodownId
			set @intJournalID = @intJournalID + 1	
		end -- for item rate = 0 hari 011213
		fetch next FROM  svcur into @intsviD, @strsvno, @dtsvDate,
			@strRemarks, @dtutime, @intDepartmentID,
			@numConExRate, @numDepExRate, @strExRates
	end	-- CUR END
	Close svcur
	Deallocate svcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spulInvAssetConv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulInvAssetConv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------
--Created 	: 29/12/02
--Created by 	: Hariharan R
--------------------------------------
-- Modified on  : 02/01/2003, 02/02/2004
-- Modified by  : Kishore, Hariharan
-- Comments     : Inserted DepAmount and added amount convertion
--		: included whType condition in where condition to identify the asset conversions
--------------------------------------
CREATE proc [dbo].[spulInvAssetConv] @intCompanyId as int, @intGodownId as int as
begin
	Declare
	@intJournalID as int,
	@intJournalDetailID as int,
	@intswoid as int,
	@intFinancialID as int,
	@strswoNo as varchar(50),
	@dtswoDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentId as int,
	@numswoAmt as numeric(18,2),
	@intCompanyCurID as int,
	@intInventoryAccId as int,
	@intAssetConvID as int,
	@dtutime as datetime,
	@strZeroRate as varchar(1),
	@intFailcount as int,
	@numDepExRate as numeric(18, 8),
	@numConExRate as numeric(18, 8),
	@intCurrencyId as int,
	@strExRates VarChar(250),	
	@numAccExRate Numeric(18, 2),
	@numTransEr Numeric(18, 2),
	@numAaccAmt Numeric(18, 2)
	--get the companyCurrencyID
	SELECT @intCompanyCurID = CurrencyID
		FROM acompanymaster
		WHERE CompanyId = @intCompanyId
	select @intAssetConvID = AssetConversionAccid
		from aPackageSettings
		where CompanyId = @intCompanyId
	select @intInventoryAccId = InventoryID,
		@strZeroRate = substring(isnull(futurevc, ''''), 1, 1)
		from aPackageSettings
	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader WHERE CompanyId = @intCompanyId
	set @intJournalID = @intJournalID + 1
	Declare swoCur cursor for
		SELECT whID, whno, whdate,  whRemarks, updatetime, whDepartmentId,
		whConExRate, whDepExRate, whExchangeRates
		FROM loiWriteOffHeader
		WHERE whCancelled = 0 and whGodownId = @intGodownId and whPosted = 0
		and whType =''A''
	open swocur
		fetch next FROM swoCur into @intswoiD, @strswono, @dtswoDate,
		@strRemarks, @dtutime, @intDepartmentId, @numConExRate,
		@numDepExRate, @strExRates
	while @@Fetch_status = 0	
	begin	-- cur begin
	
		select @intCurrencyId = CurrencyId
		from aAccountMaster
		where AccountId = @intInventoryAccId
		
		exec spReturnExRate @intCurrencyId, @strExRates,
					@numTransEr output
		-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
		-- to check the no of records with item rate =0 or null in both the Detail table
		-- and the item master table. If so we cannot do any thing in the posting with out item rate.
		-- so that transaction will be avoided from posting
		-- hariharan 011211
		set @intFailcount = 0
		select @intFailcount = count(*) from loiWriteOffDetail, aItem where
			wdID = @intswoiD and wdGodownId = @intGodownId and wdItemID = itemid
			and ( wdcostprice =null or wdcostprice =0) and (itemrate=0 or itemrate is null)
		-- to allow to proceed if allow zero rate condition given - hari 020905
		if @strZeroRate = ''z''
		begin
		 	set @intFailcount=0
		end
		if @intfailcount = 0 -- for item rate = 0 check
		begin
			-- to update the item rate to the gadcostprice 		
			update loiWriteOffDetail set wdcostprice = itemrate
				from aItem where ( wdcostprice =null or wdcostprice =0) and wdID = @intswoiD and
				wdGodownId = @intGodownId and wdItemID = itemid
			insert into moaJournalHeader (JournalID, CompanyId, JournalDate,
				referenceno, Remarks, financialID, Type, CurrencyID,chequedate, updatetime )
				values (@intJournalID, @intCompanyId, @dtswoDate, @strswono,
				@strRemarks, @intFinancialID, ''invascnv'', @intcompanycurID, @dtswoDate, @dtutime )
			set @intJournalDetailID = 1
			--getting the total amount with qty and item cost price
			select @numswoAmt = isnull(sum(wdWriteOffqty * wdcostprice),0) from
				loiWriteOffDetail swod	where wdGodownId = @intGodownId and wdid = @intswoid
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intAssetConvId
		
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numSwoAmt,
					@numAaccAmt output
			--debiting hte Asset Conversion accid
			insert into moaJournalDetails (JournalId, journalDetailId, CompanyId,
				JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, DepartmentId)
				values
				(@intJournalID, @intjournalDetailID, @intCompanyId, 0, @intAssetConvId,
				@numswoAmt * @numConExRate, @numAaccAmt,
				@numSwoAmt * @numDepExRate, @intDepartmentId)	
			set @intJournalDetailId = @intJournalDetailId + 1
			-- credit the inventory acc id
			insert into moaJournalDetails (JournalID, journalDetailID, CompanyId,
				JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, DepartmentId) values
				(@intJournalID, @intjournalDetailID, @intCompanyId, 1,
				@intInventoryAccId, @numswoAmt * @numConExRate, @numSwoAmt,
				@numSwoAmt * @numDepExRate, @intDepartmentId )
			update loiWriteOffHeader set whPosted = 1 WHERE WhID =
				@intswoID and whGodownId = @intGodownId
			set @intJournalID = @intJournalID + 1	
		end -- for item rate = 0 check
		fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate,
			@strRemarks, @dtutime, @intDepartmentId, @numConExRate,
			@numDepExRate, @strExRates
	end	-- CUR END
	Close swoCur
	Deallocate swoCur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULinvGoodsArrival]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULinvGoodsArrival]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified on      : 07/01/2003, 28/12/2003
-- Modified by      : Hariharan R
-- comment          : added code to insert DepAmount and convert amount
--      : shipment arrival debit and credit given seperately
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
----------------------------------------------------------------------------------------
CREATE proc [dbo].[spULinvGoodsArrival] @intCompanyId as int, @intGodownId as int as
begin
Declare @intJournalID as int
Declare @intJournalDetailID as int
Declare @intFinancialID as int
Declare @dtgaDate as datetime
Declare @strgaNo as varchar(50)
Declare @intgaid as int
Declare @strRemarks as varchar(250)
Declare @intFromDepId as int
Declare @numDebTotalValue as numeric(18,2)
Declare @numCreditTotalValue as numeric(18,2)
Declare @intinventoryaccid as int
declare @intcomcurid as int
declare @intToDepId as int
declare @strArrivalType as char(1)
declare @bitcpf as bit
declare @dtutime as datetime
declare @intFailcount int
declare @intStockTransferAccId as int
declare @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),
@numDepAmt Numeric(18,2)
/* 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 @intInventoryaccid = InventoryId,
@intStockTransferAccId = stocktransfercontrolacc,
@strZeroRate = substring(isnull(futurevc,''''),1,1) from
aPackageSettings where CompanyId = @intCompanyId
set @intJournalID = @intJournalID + 1
Declare garrcur cursor for
SELECT ahArrivalId, ahArrivalDate, ahArrivalNo, ahremarks,
ahdepartmentid todep, ahArrivalType,
ahCostPriceFixed , updatetime, ahConExRate, ahDepExRate, ahExchangeRates
FROM LOiArrivalHeader ga
WHERE  ahCancelled = 0 and ahPosted = 0 and
ga.ahLocalGodownId = @intGodownId and ahTransFinished = 1
open garrcur
fetch next FROM garrcur into @intgaid, @dtgadate, @strgano,
@strremarks, @intToDepId, @strArrivalType,
@bitcpf, @dtutime, @numConExRate, @numDepExRate, @strExRates
while @@Fetch_status = 0
begin
select @intCurrencyId = CurrencyId
from aAccountMaster a
where a.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 @dtgadate 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
if @strArrivalType =''h''
begin
select @intFailcount = count(*) from loiarrivaldetail, aItem where
adArrivalId= @intgaid and adGodownId = @intGodownId and adItemId = ItemId
and (adCostPrice=null or adCostPrice=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
end
if @strArrivalType =''g'' or  @strArrivalType =''s''
begin
select @intFailcount = count(*) from loiArrivalShipmentDetail, aItem where
asdArrivalId= @intgaid and asdGodownId = @intGodownId and asdItemId = ItemId
and (asdCostPrice=null or asdCostPrice=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
end
if @intfailcount = 0 -- item rate = 0 check -hari 011213
begin
if (@strArrivalType = ''h'' and @bitcpf = 1)
begin
-- to update the item rate to the adCostPrice
update loiarrivaldetail set adCostPrice = itemrate
from aItem
where (adCostPrice = null or adCostPrice = 0)
and adArrivalId = @intgaid
and adGodownId = @intGodownId and adItemId = ItemId
select @intFromDepId = ch.chdepartmentid
from loiarrivalheader ah, ahqdespatchnoteheader dh,
ahqdespatchnotemain dnm, loacostingheader ch
where ah.ahlocalGodownId = dh.dhGodownId
and ah.ahDespatchNoteID = dh.dhDespatchnoteID
and dh.dhDespatchNoteMainID = dnm.dnmDespatchNoteID
and dnm.dnmbillid = ch.chBillID
and ch.chcancelled =0 and dnm.dnmcancelled = 0
and ah.ahArrivalId = @intgaid
and ah.ahlocalGodownId = @intGodownId
/*
SELECT @numDebTotalValue = sum(adReceivedQty * adCostPrice) ,
@numCreditTotalValue = sum(adDespatchedQty * adCostPrice)
FROM LOiArrivalDetail
WHERE adGodownId  = @intGodownId
and adArrivalId = @intgaid
group by adGodownId, adArrivalId
Commended by Prasanth 28-10-2008
need to get packing type qty in posting
*/
	 select  @numDebTotalValue=sum((ad.adReceivedQty * pk.quantity )* ad.adCostPrice)  ,
	 @numCreditTotalValue=  sum((ad.adDespatchedQty * pk.quantity)* ad.adCostPrice)
	 from  loiarrivalheader ah, loiarrivaldetail ad,
	 aitem ai, aPackingTypeCapacityDetail pk, aunit u
	 where ah.ahcancelled=0 and ah.ahtransfinished=1 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 ai.unitsid = u.unitid and ah.ahArrivalId = @intgaid
	      and ah.ahlocalGodownId = @intGodownId
insert into moaJournalHeader (JournalID, CompanyId,
JournalDate, referenceno, remarks,financialID,
Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyId, @dtgaDate, @strgaNo,
@strremarks, @intFinancialID,''iga'',
@intcomCurID, @dtgadate, @dtutime)
set @intJournalDetailID = 1
/* debiting the inventory account with the full on godown department*/
insert into moaJournalDetails (JournalID,
journaldetailID, CompanyId,
JournalCrEDit, AccountId, Amount, ActualAmount,
DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID,
@intCompanyId, 0,
@intInventoryaccid, @numDebTotalValue * @numConExRate,
@numDebTotalValue, @numDebTotalValue * @numDepExRate,
@intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numDebTotalValue,
@numAaccAmt output
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyId, JournalCrEDit, AccountID,
Amount, ActualAmount, DepAmount, DepartmentId)
values (@intJournalID, @intJournalDetailId,
@intCompanyId, 1, @intStockTransferAccId,
@numDebTotalValue * @numConExRate, @numAaccAmt,
@numDebTotalValue * @numDepExRate, @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
select @intCurrencyId = depCurrencyId
from adepartmentmaster
where departmentid = @intFromDepId
and companyid = @intCOmpanyid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numCreditTotalValue,
@numDepAmt output
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numCreditTotalValue,
@numAaccAmt output
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyId, JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID,
@intCompanyId, 0, @intStockTransferAccId,
@numCreditTotalValue * @numConExRate, @numAaccAmt,
@numDepAmt, @intFromDepId)
set @intJournalDetailID = @intJournalDetailID + 1
select @intCurrencyId = depCurrencyId
from adepartmentmaster
where departmentid = @intFromDepId
and companyid = @intCOmpanyid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numCreditTotalValue,
@numDepAmt output
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId =  @intInventoryaccid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numCreditTotalValue,
@numAaccAmt output
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyId, JournalCrEDit, AccountID,
Amount, actualAmount, DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID,
@intCompanyId, 1, @intInventoryaccid,
@numCreditTotalValue * @numConExRate, @numAaccAmt,
@numDepAmt, @intFromDepId)
/* mark the record as Posted */
update LOiArrivalHeader  set ahPosted  = 1
WHERE ahlocalGodownId = @intGodownId
and ahArrivalId = @intgaid
set @intJournalID = @intJournalID + 1
end -- for hq arrival
if (@strArrivalType = ''s'' or @strArrivalType = ''g'' )
begin
-- to update the item rate to the adCostPrice
update loiArrivalShipmentDetail set asdCostPrice = itemrate
from aItem where (asdCostPrice=null or asdCostPrice=0) and asdArrivalId= @intgaid
and asdGodownId = @intGodownId and asdItemId = ItemId
SELECT @numDebTotalValue = sum(asdReceivedGoodQty * asdCostPrice) FROM loiArrivalShipmentDetail
WHERE asdGodownId  = @intGodownId and asdArrivalId = @intgaid group by asdGodownId, asdArrivalId
insert into moaJournalHeader (JournalID, CompanyId, JournalDate, referenceno, remarks,
financialID,Type, CurrencyID,chequedate,updatetime) values (@intJournalID, @intCompanyId,
@dtgaDate, @strgaNo, @strremarks, @intFinancialID,''iga'', @intcomCurID,@dtgadate, @dtutime)
set @intJournalDetailID = 1
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyId, JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID,
@intCompanyId, 0, @intInventoryaccid,
@numDebTotalValue * @numConExRate, @numDebTotalValue,
@numDebTotalValue * @numDepExRate,
@intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numDebTotalValue,
@numAaccAmt output
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyId, JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID,
@intCompanyId, 1, @intStockTransferAccId,
@numDebTotalValue * @numConExRate, @numAaccAmt,
@numDebTotalValue * @numDepExRate, @intToDepId )
/* mark the record as Posted */
update LOiArrivalHeader  set ahPosted  = 1
WHERE ahlocalGodownId = @intGodownId
and ahArrivalId = @intgaid
set @intJournalID = @intJournalID + 1
end   -- for hq arrival
end    -- item rate = 0 check -hari 011213
fetch next FROM garrcur into @intgaid, @dtgadate, @strgano, @strremarks,
@intToDepId, @strArrivalType, @bitcpf, @dtutime,
@numConExRate, @numDepExRate, @strExRates
end
Close garrcur
Deallocate garrcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlInvGdnToGdnTransfer]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvGdnToGdnTransfer]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------
-- Modified on : 02/01/2002
-- Modified by : Kishore
-- Comment     : Added code to insert DepAmount and to conver amount
------------------------------
-- Last Modified on 	: 07/06/2003
-- Last Modified by	: R Harikrishnan
-- Comments		: Department Exrate Corrected
------------------------------
CREATE proc [dbo].[spUlInvGdnToGdnTransfer] @intCompanyID as int, @intGodownId as int as
begin
	Declare @intJournalID as int
	Declare @intJournalDetailID as int
	Declare @intFinancialID as int
	Declare @dttDate as datetime
	Declare @strtNo as varchar(50)
	Declare @inttid as int
	Declare @strRemarks as varchar(250)
	Declare @numtotalValue as numeric(18,2)
	Declare @intInventoryAccId as int
	declare @intcomcurid as int
	declare @intToDepId as int
	declare @dtutime as datetime
	declare @intFailcount as int
	declare @intstocktransferaccid  as int
	declare @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)
	/* 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 @intInventoryAccId = inventoryid,
		@intstocktransferaccid = stocktransfercontrolacc,
		@strzerorate = substring(isnull(futurevc,''''), 1, 1)
		from apackagesettings
		where companyid = @intcompanyid
	set @intJournalID = @intJournalID + 1
	
	Declare trincur cursor for
		SELECT gthDespatchID, gthDespatchDate, gthDespatchNo,
		gthRemarks, gthDepartmentId todep, updatetime,
		gthConExRate, gthdepexrate, gthExchangeRates
		FROM MEiGodownTransferHeader tinh
		WHERE gthCancelled = 0 and gthPosted = 0 and gthFromGodownId = @intGodownId and
		gthTransFinished = 1
	open trincur
	fetch next FROM trincur into @inttid , @dttdate, @strtno,
		@strRemarks, @intToDepId, @dtutime, @numConExRate, @numDepExRate, @strExRates
	
	while @@Fetch_status = 0
	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 @dttdate 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 MEiGodownTransferdetail , aitem where
			gtdDespatchID = @inttid and gtdGodownId = @intGodownId and gtdItemID = itemid
			and (gtdcostprice=null or gtdcostprice =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 	-- item rate=0 check hari 011213
		begin
			-- to update the item rate to the gadcostprice 		
			update MEiGodownTransferdetail  set gtdcostprice = itemrate
				from aitem
				where ( gtdcostprice =null or gtdcostprice =0) and gtdDespatchID = @inttid
				and gtdGodownId = @intGodownId and gtdItemID = itemid
			SELECT @numTotalValue = sum( gtdItemGoodQty * gtdcostprice )
				FROM MEiGodownTransferdetail   WHERE gtdGodownId  = @intGodownId and
				gtdDespatchID = @inttid group by gtdGodownId, gtdDespatchID
			insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
				referenceno, Remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
				(@intJournalID, @intCompanyID, @dttDate, @strtNo,
				@strRemarks, @intFinancialID, ''gdntogdn'', @intcomCurID,@dttdate, @dtutime)
			set @intJournalDetailID = 1		
			/* debiting the inventory account with the full */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, DepartmentId)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
				@intInventoryAccId, @numTotalValue * @numConExRate,
				@numtotalvalue, @numTotalValue * @numDepExRate, @intToDepId )		
			set @intJournalDetailID = @intJournalDetailID + 1		
			
			-- for converting the amount --->
			select @intCurrencyId = CurrencyId
					from aAccountMaster
					where AccountId = @intstocktransferaccid
		
			exec spReturnExRate @intCurrencyId, @strExRates,
					@numAccExRate output
			exec spConvertCurrency @numTransEr, @numAccExRate,
					@numTotalValue,
					@numAaccAmt output
			/* debiting the inventory account with the full */
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, AccountID, Amount, ActualAmount,
				DepAmount, DepartmentId)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
				@intstocktransferaccid, @numTotalValue * @numConExRate,
				@numAaccAmt, @numTotalValue * @numDepExRate, @intToDepId)			
			/* mark the record as Posted */
			update MEiGodownTransferHeader set gthPosted = 1
				WHERE gthFromGodownId = @intGodownId and
				gthDespatchID = @inttid
			set @intJournalID = @intJournalID + 1
		end -- item rate=0 check hari 011213
		fetch next FROM trincur into @inttid, @dttdate, @strtno, @strRemarks,
			@intToDepId, @dtutime, @numConExRate, @numDepExRate, @strExRates
	end
	Close trincur
	Deallocate trincur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownDamageClearing]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownDamageClearing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--MOdified By 	    : Venkitesh
--Modified Date	    : 17/09/2003
--COmments	    : Given insertion code to moiGodownStock if stock < 0
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE proc [dbo].[spUpdateGodownDamageClearing] @ClearID int,
@Godownid int, @Type char(1)  as
declare
@cur_ClearID int,
@cur_godownid int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_ShipmentID int ,
@intCount int
set nocount on
set @intcount=0
	declare cursor_Detail  cursor for
	select dcdClearingID, dcdGodownid, dcdItemID, dcdWriteOffQty, dcdShipmentID
	from LOiDamageClearingDetails where dcdClearingID = @ClearID and dcdGodownid = @Godownid
open cursor_Detail
fetch next from cursor_Detail into
@cur_ClearID, @cur_godownid, @cur_itemid,
@cur_itemgoodqty, @cur_ShipmentID
while @@fetch_status = 0
begin
		--added by venki forinserting empty row if itemcount=0
			select @intCount = count(*) from moigodownStock
			where gsitemid = @cur_Itemid and gsgodownid= @godownid
			if @intCount =0
			Begin
				insert moigodownStock (gsgodownID,gsStockDate, gsShipmentID, gsItemID,
				gsOpeningStock, gsStock, gsOpeningBadStock, gsBadStock)
				Select @godownid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
			End
			--
		if @TYpe=''f''
		Begin
			
			update moigodownstock set gsbadStock = gsbadStock - @cur_itemgoodqty
			where gsitemid = @cur_itemid and gsgodownid = @cur_godownid  and
			gsshipmentid = @cur_ShipmentID
		End
		Else	--@type=''r''
		Begin
			update moigodownstock set gsbadStock = gsbadStock + @cur_itemgoodqty
			where gsitemid = @cur_itemid and gsgodownid = @cur_godownid  and
			gsshipmentid = @cur_ShipmentID
		End
	fetch next from cursor_Detail into
	@cur_ClearID, @cur_godownid, @cur_itemid,
	@cur_itemgoodqty, @cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownItemSplit]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownItemSplit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified By 	: Kishore
-- Date  	: 05/06/2003
--Comments	: (V3)
--                Created on 28/12/2002
--                Updates the godown stock
--                for the transaction Item Split in godown.
--                Added the initalization of @cur_ItemGoodQty
--                and @cur_HeaderCost on 05/06/2003
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateGodownItemSplit] @SplitId int,
				   @GodownId int, @Type char(1)  AS
begin
	declare
	@cur_SplitId int,
	@cur_GodownId int,
	@cur_ItemId int,
	@cur_ItemGoodQty numeric(18, 3),
	@cur_FromTable char(1),
	@cur_cost numeric(18, 2),
	@cur_ShipmentID int,
	@cur_HeaderItemId int,
	@cur_HeaderCost numeric(18, 2),
	@recCount as int
	set nocount on
	set @cur_ItemGoodQty = 0.0
	set @cur_HeaderCost = 0.0
	declare cursor_Detail  cursor for
		select isdId isId, isdGodownId godownId, isdItemId ItemId,
		isdQty Qty, ishShipmentId ShipmentId, Item2.ItemRate ItemRate,
		Header.ishSplitItemId HeaderItemId,
		Item1.ItemRate HeaderItemRate
		from loiItemSplitDetail Detail, loiItemSplitHeader Header,
		aItem Item1, aItem Item2
		where Detail.isdId = Header.ishId
		and Detail.isdGodownId = Header.ishGodownId
		and Header.ishSplitItemId = Item1.ItemId
		and Detail.isdItemId = Item2.ItemId
		and isdId = @SplitId
		and isdGodownId = @GodownId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_SplitId, @cur_GodownId, @cur_ItemId,
		@cur_ItemGoodQty, @cur_ShipmentId,
		@cur_cost, @cur_HeaderItemId, @cur_HeaderCost
	while @@fetch_status = 0
	begin
		if @Type = ''f''
		begin
			-- update stock from details table
			-- check if the record exists in the stock table
			select @recCount = count(*) from moiGodownStock
					where gsItemId = @cur_ItemId
					and gsGodownId = @cur_GodownId
			
			-- if it does not exist
			if @recCount = 0
			begin
				-- insert to stock table
				insert moiGodownStock(gsGodownId, gsItemId,
					gsStock, gsShipmentId, gsItemCost, gsStockdate)
					select @cur_GodownId,  @cur_ItemId,
					@cur_ItemGoodQty, @cur_shipmentId, @cur_cost, getdate()
			end
			else	-- if the record exists in the stock table
			begin
				-- update stock table
				update moiGodownStock set gsStock =  gsStock + @cur_ItemGoodQty
					where gsItemId = @cur_ItemId
					and gsGodownId = @cur_GodownId
			end	
			-------------------------------------
			-- update stock from header table
			-------------------------------------
			-- check if the record exists in the stock table
			select @recCount = count(*) from moiGodownStock
					where gsItemId = @cur_HeaderItemId
					and gsGodownId = @cur_GodownId
			
			-- if it does not exist
			if @recCount = 0
			begin
				-- insert to stock table
				insert moiGodownStock(gsGodownId, gsItemId,
					gsStock, gsShipmentId, gsItemCost, gsStockdate)
					select @cur_GodownId,  @cur_HeaderItemId,
					-1 * @cur_ItemGoodQty, @cur_shipmentId,
					@cur_HeaderCost, getdate()
			end
			else	-- if the record exists in the stock table
			begin
				-- update stock table
				update moiGodownStock set gsStock =  gsStock - @cur_ItemGoodQty
					where gsItemId = @cur_HeaderItemId
					and gsGodownId = @cur_GodownId
			end		
		end
		else	-- if type is Reverse
		begin
			-- reverse detail stock
			update moiGodownStock
				set gsStock = gsStock - @cur_ItemGoodQty
				where gsItemId = @cur_ItemId
				and gsGodownId = @cur_GodownId
			
			-- reverse header stock
			update moiGodownStock
				set gsStock = gsStock + @cur_ItemGoodQty
				where gsItemId = @cur_HeaderItemId
				and gsGodownId = @cur_GodownId
		end
		
		-- get next record from cursor
		fetch next from cursor_Detail into
			@cur_SplitId, @cur_GodownId, @cur_ItemId,
			@cur_ItemGoodQty, @cur_ShipmentId,
			@cur_cost, @cur_HeaderItemId, @cur_HeaderCost
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULshopServiceInv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopServiceInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 13/01/2003, 23/12/2003, 19/01/2004
--Modified by  : leo, Hariharan R
--Verified by : Hariharan R,
--Modified by dheena amount calculate invoice type wise
--Comments  : Modified to post all poamount + commamt if cash paid by shop
--   : For normal Service invoice and commision invoice not paid by shop
--   : only invoice amount is taken
---------------------------------------------------------------------------------------------------
--Ref No		: Ref No1
--Modified By	: MANUNADH.U
--Modified On	: 07-10-2011,06-12-2011
--Comments		: Need to include Posting of GST
---------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spULshopServiceInv]
@intCompanyID as int, @intshopid as int
as
begin
Declare @intSalesAccountID as int,@intCashAccountID as int,@intAccountID as int,@intJournalID as int,
	@intJournalDetailID as int,@strSName as varchar(100),@intSAccountID as int,@intSQty as int,
	@numSAmount as numeric(18,2),@intFinancialID as int,@dtInvoiceDate as datetime,@intCustomerID as int,
	@intinvoiceid as int,@strInvoiceNo as varchar(50),@strRemarks as varchar(250),
	@intDiscountAccountID as int,@numDiscount as numeric(18,2),@intDepartmentID as int,@bitCash as bit,
	@bitProduct as bit,@numTotalInvValue as numeric(18,2),@intCompanyCurID as int,
	@numBuyingRate as numeric(28,8),@intTransCurID as int,@numAverageRate as numeric(28,8),
	@numTransRate as numeric(28,8),@dtutime as datetime,@numdepexrate as numeric(18, 8),
	@exchangerates as varchar(250),@numAccamount as numeric(18,2),@numNetAmt as numeric(18,2),
	@StrInvoiceType as varchar(4),@intPaidByShop as int,
	@intServiceTaxID INT,@intGSTOutPutAccountID INT, ---Ref No1
	@numGSTTaxAmount as numeric(18,9),@numAccGSTTaxAmount as numeric(18,9) ---Ref No1
--get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID FROM aCompanyMaster WHERE CompanyID = @intCompanyID
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0)FROM moaJournalHeader WHERE CompanyID = @intCompanyID
---Ref No1  start
select @intServiceTaxID=isnull(ServiceTaxCategoryId,0) from ashops WHERE CompanyID = @intCompanyID and shopid= @intshopid
IF (@intServiceTaxID<>0)
	Begin
	  select @intGSTOutPutAccountID=TaxAccountId from aTaxCategoryMaster where TaxId=@intServiceTaxID
	END
--- ---Ref No1  end
	
set @intJournalID = @intJournalID + 1
Declare AccInvoice cursor for
	---Ref No1  Commented below snippet
	/*
	SELECT aiInvoiceID,aiInvoiceDate,aiCustomerID,aiInvoiceNo,case when (aichequeno is null or
	  aichequeno ='''') then airemarks else aichequeno + '';'' + airemarks end as remarks,
	  aiDiscountAccountID,aiDiscount,aiDepartmentID,aiCashInvoice,aiProduct,aiFinancialID,aiBankCashID,
	  aiexchangeRate,aiSalesAccID,updatetime,aidepexrate,aidexchangerates,aiInvoiceType,aiCashPaidByshop
	FROM losAccountsInvoiceHeader WHERE aiCancelled = 0 and aiPosted = 0 and
	  aiCompanyID = @intCompanyID and aiProforma = 0  and aishopid = @intshopid
	*/
	SELECT aiInvoiceID,aiInvoiceDate,aiCustomerID,aiInvoiceNo,case when (aichequeno is null or
	  aichequeno ='''') then airemarks else aichequeno + '';'' + airemarks end as remarks,
	  aiDiscountAccountID,aiDiscount,aiDepartmentID,aiCashInvoice,aiProduct,aiFinancialID,aiBankCashID,
	  aiexchangeRate,aiSalesAccID,updatetime,aidepexrate,aidexchangerates,aiInvoiceType,aiCashPaidByshop
	  ,aiTaxAmount
	FROM losAccountsInvoiceHeader WHERE aiCancelled = 0 and aiPosted = 0 and
	  aiCompanyID = @intCompanyID and aiProforma = 0  and aishopid = @intshopid
	
open AccInvoice
	Fetch next FROM AccInvoice INTO @intInvoiceID,@dtInvoiceDate,@intCustomerID,@strInvoiceno,
	@strRemarks,@intDiscountAccountID,@numDiscount,@intDepartmentID,@bitCash,@bitProduct,@intFinancialID,
	@intCashAccountID,@numTransRate,@intsalesaccountid,@dtutime,@numdepexrate,@exchangerates,
	@StrInvoiceType,@intPaidByShop,@numGSTTaxAmount
	
	while @@Fetch_status = 0
	begin
	  exec spConvertequiamount @intcustomerid, ''c'', @intGSTOutPutAccountID, ''a'',
		@exchangerates, @numGSTTaxAmount, @numAccGSTTaxAmount output , ''''        	
	  SELECT @numTotalInvValue = sum(siServiceQty * siAmount),@numSAmount = sum(isnull(siClearingCommAmt,0))
	  FROM losServiceInvoiceDetails
	  WHERE siCompanyID = @intCompanyID and siInvoiceID = @intInvoiceID and sishopid=@intshopid
		--hari added TO Consider in case of commision invoice only
	  if @StrInvoiceType=''PS'' set @intPaidByShop = 0
	  if @intPaidByShop = 1 set @numTotalInvValue  = @numTotalInvValue + isnull(@numSAmount ,0)
	  -- get cash or crEDit
	  SELECT @intTransCurID = CurrencyID FROM aCustomerMaster
	  WHERE CompanyID = @intCompanyID and CustomerID = @intCustomerID
	  INSERT INTO moaJournalHeader(JournalID,CompanyID,JournalDate,ReferenceNo,Remarks,FinancialID,Type,
		CurrencyID,chequedate,updatetime)
	  VALUES(@intJournalID,@intCompanyID,@dtInvoiceDate,@strInvoiceNo,@strRemarks,@intFinancialID,''SAI'',
	    @intTransCurID,@dtinvoicedate,@dtutime)
	  set @intJournalDetailID = 1
	  /* check if discount allowED if allowED then post discount details */
	  if @numDiscount > 0
	  begin
		exec spConvertequiamount  @intCustomerID, ''c'', @intDiscountAccountID, ''a'',
			@exchangerates, @numDiscount, @numAccamount output, ''''
		INSERT INTO moaJournalDetails(JournalID,journaldetailID,CompanyID,JournalCredit,AccountID,Amount,
			DepAmount,ActualAmount,departmentID)
		VALUES(@intJournalID,@intjournalDetailID,@intCompanyID,0,@intDiscountAccountID,(@numDiscount *
		@numTransRate),@numDiscount * @numdepExrate,@numAccamount,@intDepartmentID)
	    set @intJournalDetailID = @intJournalDetailID +1
	  end
	  set @numNetAmt = @numTotalInvValue-@numDiscount
	  if (@intCashAccountID is null) --crEDit trans
	  begin
		exec spConvertequiamount  @intCustomerID, ''c'', @intsalesaccountid, ''a'',
			@exchangerates, @numTotalInvValue, @numAccamount output, ''''
		/* inserting the sales account with the full invoice Amount */
		INSERT INTO moaJournalDetails (JournalID, JournalDetailID, CompanyID,
			JournalCredit, AccountID, Amount, depamount, ActualAmount,departmentID)
		VALUES (@intJournalID,@intJournalDetailID,@intCompanyID,1,@intsalesaccountid,@numTotalInvValue *
			@numTransRate,@numTotalInvValue * @numdepexrate,@numAccamount,@intDepartmentID)
		
		set @intJournalDetailID = @intJournalDetailID +1
		-------------------------<<Ref No1 >>New Code
		INSERT INTO moajournaldetails (JournalID,JournalDetailID,CompanyID,JournalCredit,CustomerID,
		  Amount,DepAmount,ActualAmount,departmentID)
		VALUES (@intJournalID,@intjournalDetailID,@intCompanyID,0,@intCustomerID,
		((@numNetAmt + @numGSTTaxAmount)*@numTransRate), ((@numNetAmt+@numGSTTaxAmount)*@numdepexrate),
		@numNetAmt+@numGSTTaxAmount,@intDepartmentID)
		set @intJournalDetailID = @intJournalDetailID +1
		------------------------<<Ref No1 >>Old Code
		--INSERT INTO moaJournalDetails (JournalID,JournalDetailID,CompanyID,JournalCredit,CustomerID,
		--  Amount,DepAmount,ActualAmount,departmentID)
		--VALUES (@intJournalID,@intjournalDetailID,@intCompanyID,0,@intCustomerID,@numNetAmt *
		--  @numTransRate,@numNetAmt * @numDepExrate,@numNetAmt,@intDepartmentID)
		--  set @intJournalDetailID = @intJournalDetailID +1
		------------------------<<Ref No1 >>
	  end
	  else
	  begin
		exec spConvertequiamount  @intCashAccountID, ''a'',@intsalesaccountid, ''a'',
			@exchangerates, @numTotalInvValue, @numAccamount output, ''''
		INSERT INTO moaJournalDetails (JournalID, JournalDetailID, CompanyID,
			JournalCredit, AccountID, Amount, depamount, ActualAmount,departmentID)
		VALUES(@intJournalID,@intJournalDetailID,@intCompanyID,1,@intsalesaccountid,@numTotalInvValue *
			@numTransRate,@numTotalInvValue * @numdepexrate,@numAccamount,@intDepartmentID)
		set @intJournalDetailID = @intJournalDetailID +1
		
		-------------------------<<>>New Code
		INSERT INTO moajournaldetails (JournalID,JournalDetailID,CompanyID,
			JournalCredit,AccountID,Amount,depamount,ActualAmount,departmentID)
		VALUES (@intJournalID,@intjournalDetailID,@intCompanyID,0,@intCashAccountID,
		((@numNetAmt + @numGSTTaxAmount)*@numTransRate),((@numNetAmt+@numGSTTaxAmount)*@numdepexrate),
		@numNetAmt+@numGSTTaxAmount,@intDepartmentID)
		set @intJournalDetailID = @intJournalDetailID +1
		------------------------<<Ref No1 >>Old Code
		--INSERT INTO moaJournalDetails (JournalID, JournalDetailID, CompanyID,
		--	JournalCredit, AccountID, Amount, Depamount, ActualAmount,departmentID)
		--VALUES(@intJournalID,@intJournalDetailID,@intCompanyID,0,@intCashAccountID,@numNetAmt *
		--	@numTransRate,@numNetAmt * @numDepExrate,@numNetAmt,@intDepartmentID  )
		--set @intJournalDetailID = @intJournalDetailID +1
		------------------------<<Ref No1 >>
	  end
	  /* mark the record as postED */
	  ---Ref No1 start posting of GST amount
	  IF (@intServiceTaxID<>0)
	  Begin
		INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,
			JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
		VALUES(@intJournalID,@intJournalDetailID,@intCompanyID,1,@intGSTOutPutAccountID,
		  (@numGSTTaxAmount * @numTransRate),@numAccGSTTaxAmount,@intDepartmentID,
		  (@numGSTTaxAmount * @numDepExrate))
		set @intJournalDetailID = @intJournalDetailID +1
	  END
	 ---Ref No1 end posting of GST amount
	  UPDATE losAccountsInvoiceHeader SET aiPosted = 1
	  WHERE aiCompanyID = @intCompanyID and aishopid = @intshopid and aiInvoiceID = @intInvoiceID
	  set @intJournalID = @intJournalID + 1
	  FETCH NEXT FROM AccInvoice INTO @intInvoiceID,@dtInvoiceDate,@intCustomerID,@strInvoiceNo,
	    @strRemarks,@intDiscountAccountID,@numDiscount,@intDepartmentID,@bitCash,@bitProduct,
		@intFinancialID,@intCashAccountID,@numTransRate,@intsalesaccountid,@dtutime,@numdepExrate,
		@exchangerates,@StrInvoiceType,@intPaidByShop,@numGSTTaxAmount
end
Close AccInvoice
Deallocate Accinvoice
/* Accounts Invoice product or service End */
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlShopPurchase]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopPurchase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spUlShopPurchase 1,6
-- Modified on       : 02/01/2002
-- Modified by       : Hariharan R
-- Comment           : Added code to insert dep amount and to convert amount
--Verified By   : Hariharan R
--------------------------------------
-- Modified by : Abhishek CS.
-- Modified on : 02-08-2010
-- Modification: Added purchase bill confirmed bit for kooddoo
-- Reference   : RefNo-2
--------------------------------------
-- Reference   : RefNo-3
-- Modified by : Nidheesh P V
-- Modified on : 02-07-2011
-- Modification: Modified the part from where it selects the Transaction Currency.(Chaged to Vendor Currency from Inventory Currency.)
--Added the query to select currency and corresponding ex. rate while posting the amount to Inventory A/C.
--------------------------------------
--- RefNo-4   RefNo-5   RefNo-7
--Modified on      : 19-09-2011 01-11-2011,9-01-2012
--Modified by    : jyothish SR
--Comments        : added for GST
-- RefNo-7    :Set intila alue assign to tax vrailble
--------------------------------------
-- Reference   : RefNo-6
-- Modified by : Benzigar S D
-- Modified on : 09-11-2011
-- Modification: Set post group as NULL
--------------------------------------
CREATE  proc [dbo].[spUlShopPurchase]
@intCompanyId as int, @intShopId as int
as
begin
Declare @intpurchaseAccountID as int
Declare @intCashAccountID as int
Declare @intJournalID as int
Declare @intJournalDetailID as int
Declare @intFinancialID as int
Declare @dtpDate as datetime
Declare @strpNo as varchar(50)
Declare @intpid as int
Declare @strRemarks as varchar(250)
Declare @intDiscountAccountID as int
Declare @numDiscount as numeric(18,2)
Declare @intDepartmentID as int
Declare @numTotalValue as numeric(18,2)
Declare @intComCurID as int
Declare @intinventoryaccid as int
Declare @intcostofgoodsaccid as int
declare @strchequeno as varchar(100)
declare @bitcashpurchase as bit
declare @intvendorid as int
declare @numConExRate as numeric(28,8)
declare @dtutime as datetime,
@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)
set @intCurrencyId =0
set @strExRates = ''''
set @numAccExRate =0.0
set @numTransEr = 0.0
set @numAaccAmt = 0.0
--RefNo-4-added for gst--
declare @IntCount as int
declare @TaxCurrId as int
declare @numTaxEr as numeric(18,2)
declare @TaxAcntId as int
declare @TaxCatId as int
declare @TaxAmount as numeric(18,2)
declare @CTaxAmount as numeric(18,2)
declare @DTaxAmount as numeric(18,2)
declare @TaxAccAmount as numeric(18,2)
declare @CTotalTaxAmount as numeric(18,2)
declare @DTotalTaxAmount as numeric(18,2)
declare @TotalTaxAmnt as numeric(18,2)
declare @TotalAccTax as numeric(18,2)
-----------------------------
-----------------------------
declare  @Taxtable table
(
taxTransId int,
taxShopId int,
taxCateId int,
taxAccntId int,
taxAmount numeric(18,2),
CtaxAmount numeric(18,2),
DtaxAmount numeric(18,2)
)
--RefNo-4-added for gst--
--RefNo-4---to insert tax cateid,tax A/C & tax amount in the table variable---
insert into @Taxtable
select lphBillID,lphShopID,lpdItemTaxCategory, TaxInputAccountId as TaxAccountId,isnull(sum(lpdItemTaxAmount),0)as TaxAmount,
sum(isnull(lpdItemTaxAmount,0)* lphexchangerate) as ComTaxAmount,
sum(isnull(lpdItemTaxAmount,0)* lphdepexrate) as DepTaxAmount
FROM losLocalPurchaseHeader ih inner join loslocalpurchasedetail id
on ih.lphBillID = id.lpdBillID and ih.lphShopID = id.lpdShopID
inner join ataxcategorymaster tc on   lpdItemTaxCategory=TaxId
and TaxCancelled=0 and TaxAccountable=1
WHERE lphCancelled =0 and lphPosted =0
and isnull(lpdItemTaxCategory,0)<>0
-- and ih.ihCompanyId = @intCompanyID
and ih.lphShopID = @intshopid
group by  lpdItemTaxCategory,TaxInputAccountId ,lphBillID,lphShopID
/* 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
select @intcomcurid = currencyid from acompanymaster where companyid = @intcompanyid
select @intInventoryaccid = inventoryid from apackagesettings where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
Declare pcur cursor for
SELECT lphbillid, lphbilldate, lphbillno, lphbankcashaccid, lphpurchaseaccid,
lphdiscountaccid, lphdiscount, lphchequeno, lphfinancialid, lphdepartmentid,
lphremarks, lphcashpurchase, lphvendorid, lphExchangeRate, updatetime,
lphDepExRate, lphExchangeRates
FROM losLocalPurchaseHeader
WHERE lphcancellED = 0 and lphpostED = 0 and lphConfirmed=1 and   --RefNo-2
lphCompanyID = @intCompanyID and lphShopId = @intShopId
open pcur
fetch next FROM pcur into @intpid, @dtpdate, @strpno, @intCashAccountID,
@intpurchaseaccountid, @intdiscountaccountid, @numdiscount, @strchequeno,
@intfinancialid, @intdepartmentid, @strremarks, @bitcashpurchase,
@intvendorid, @numConExRate, @dtutime,
@numDepExRate, @strExRates
while @@Fetch_status = 0
begin
-------------------------------------------------------------
-- select @intCurrencyId = CurrencyId              --commneted --RefNo-3
-- from aAccountMaster
-- where AccountId = @intInventoryAccId
-- and CompanyId = @intCompanyId
select @intCurrencyId = CurrencyId                --Added ---RefNo-3
from aVendorMaster
where VendorId = @intVendorId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
--@intCurrencyId  referes the Account currency in which the transaction is done.
--@numTransEr  referes the Ex rate in which the transaction is done.
--The Local Purcahse bill is doing in the Vendor Account Currency.So it is needed to pass vendor currency
--to find the Transaction Ex Rate.
-------------------------------------------------------------
select @numTotalValue = sum(isnull(lpditemunitprice,0)+ isnull(lpdItemTaxAmount,0))  --removed lpditemquantity * since item amount is stored in lpditemunitprice
from loslocalpurchasedetail
where lpdShopId = @intShopId and lpdbillid  = @intpid
group by lpdShopId, lpdbillid
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,chequedate, updatetime) values
(@intJournalID, @intCompanyID, @dtpDate, @strpNo,
@strremarks, @intFinancialID, ''lp'', @intcomCurID,@dtpdate,@dtutime)
set @intJournalDetailID = 1
if (@bitCashPurchase = 1)
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCashAccountId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTotalValue,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, ActualAmount,
DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intCashAccountId, @numTotalValue * @numConExRate,
@numaAccAmt,
@numTotalValue * @numDepExRate,
@intDepartmentID )
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aVendorMaster
where VendorId = @intVendorId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTotalValue,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyId,
JournalCrEDit, VendorId, Amount, ActualAmount,
DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intvendorid, @numTotalValue * @numConExRate,
@numaAccAmt, @numTotalValue * @numDepExRate, @intDepartmentID )
end
set @intJournalDetailID = @intJournalDetailID +1
---------------------------------------------------
-- for converting the amount --->              --Added--RefNo-3
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,   --Added--RefNo-3
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,  --Added--RefNo-3
@numTotalValue,
@numAaccAmt output
-------------------------------------------
--RefNo-7
set  @CTotalTaxAmount=0
set  @DTotalTaxAmount=0
set @TotalTaxAmnt=0
--RefNo-4--------------------------------------
select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),@DTotalTaxAmount=sum(isnull(DtaxAmount,0))
from @Taxtable where taxTransId=@intpid and taxShopId=@intShopId group by taxTransId,taxShopId
--- RefNo-4- null set
if  @CTotalTaxAmount is null
begin
set  @CTotalTaxAmount=0
end
if  @DTotalTaxAmount is null
begin
set  @DTotalTaxAmount=0
end
if  @TotalTaxAmnt is null
begin
set  @TotalTaxAmnt=0
end
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount, DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intInventoryaccid, (@numTotalValue * @numConExRate)-@CTotalTaxAmount,
@numAaccAmt-@TotalTaxAmnt , (@numTotalValue * @numDepExRate)-@DTotalTaxAmount,
@intDepartmentID )
--@TotalAccTax
--RefNo-4-----------------------------------
select @IntCount=count(*) from @Taxtable
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable where taxTransId=@intpid and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable where taxTransId=@intpid and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strExRates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
/* crediting TO TAX ACCOUNT   */
insert into moaJournalDetails
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0,
@TaxAcntId, @CTaxAmount,
@TaxAccAmount,@intDepartmentID, @DTaxAmount, NULL) --RefNo-6
end
delete from @Taxtable where taxTransId=@intpid and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-4-------------------------------------------
/* mark the record as posted */
update losLocalPurchaseHeader set lphpostED = 1
where lphCompanyID = @intCompanyID
and lphShopId = @intShopId and lphbillid = @intpid and lphConfirmed=1   --RefNo-2
set @intJournalID = @intJournalID + 1
fetch next FROM pcur into @intpid, @dtpdate, @strpno, @intCashAccountID,
@intpurchaseaccountid, @intdiscountaccountid, @numdiscount, @strchequeno,
@intfinancialid, @intdepartmentid, @strremarks, @bitcashpurchase,
@intvendorid,@numConExRate,@dtutime,
@numDepExRate, @strExRates
end
Close pcur
Deallocate pcur
end' 
END
GO
/****** Object:  View [dbo].[vwAssetDisposal]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAssetDisposal]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Last modified on : 10/01/2003
-- Modified by      : Kishore
-- Modifications    : Asset Disposal Report Generated  (24/02/2003)
--                  : Added feild disphcancelled,added dispasstid (venki 090303 m)
--                  : Added the UpdateTime column (30/08/2003)
--                  : Added CurrencySymbol (10/01/2003)
--      :- Corrected currency symbol (03032004) venki
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--Modified by abhishek on 06-12-09
--add cancelled=0 to avoid cancelled disposals on condition
-------------------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwAssetDisposal] AS
select
disphId, disphNo, disphDate, disphCompanyId, disphDepartmentId,
fa.Assetname,b.AccountDesc,
case  dispdcredit when 1 then dispdAmount else 0 end CurrentValue, dispdAsstId,
case  dispdcredit when 0 then dispdAmount else 0 end CreditValue,
case dispdType when ''D'' then ''Depreciation''
when ''O'' then ''Others''
when ''S'' then ''Sales'' end DispType, disphCancelled,
UpdateTime, cm.Symbol CurrencySymbol
from
AssetDisposalHeader disph,
AssetDisposalDetail dispd left outer join aAccountMaster b
On dispdCompanyId = b.CompanyId
and dispdAccId = b.AccountID, FixedAsset fa,
adepartmentMaster am, aCurrencyMaster cm
where
disphid = dispd.dispID
and disphCompanyId = dispdCompanyId
and dispdCompanyId = fa.CompanyId
and dispdAsstId = fa.FixedAssetID
and am.departmentid=disphdepartmentid
and fa.CompanyId = am.CompanyId
and am.depCurrencyId = cm.CurrencyId
and am.CompanyId = cm.CompanyId
and disph.disphcancelled=0'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillStatus]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------
--Created on  : 13/Oct/2010
--Created by : Praveen S
--Comments : For update the status of TillHeader
--          : Insert values into Till History
-------------------------------------------------------------------------------------------
--Modified on: 24/Feb/2011
--Modified by: Lawrence M.
--Comments	 : To add till number for open and close the till in the TillHistory Table
--			 : As per the Mr.Praveen Guidance I have added this till number.
--			 : To add the last F&B bill Id for identifing bill number while open the till
-------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateTillStatus]
@tillid INT,
@tilloutletid INT,
@tillcompanyid INT,
@tillOpen INT = NULL,
@tillClose INT = NULL,
@tillstatusid INT,
@tillhisoryid INT,
@tillcashierid INT = NULL,
@tillstatusremarks VARCHAR(300),
@tillmangerid INT = NULL,
@tillcreatemodifyuserid INT = NULL,
@tillNo INT =NULL,
@tillFandBbillID INT =NULL
AS BEGIN
	SET NOCOUNT ON
	IF @tillOpen = 1
	BEGIN
		UPDATE TillHeader
		SET till_th_statusid = @tillstatusid,
		till_th_starttime = getdate(),
		till_th_cashierid = @tillcashierid
		WHERE till_th_tillid = @tillid AND
		till_th_outletid = @tilloutletid AND
		till_th_companyid = @tillcompanyid
		INSERT INTO TillHistory(till_hist_id,till_id,till_cashierid,till_starttime,
		till_outletid,till_statusid,till_companyid,till_updatettime,till_statusremarks,
		till_managerid,till_createmodify_user,till_no,till_fandbbillno)
		VALUES (@tillhisoryid,@tillid,@tillcashierid,getdate(),
		@tilloutletid,@tillstatusid,@tillcompanyid,getdate(),@tillstatusremarks,
		@tillmangerid,@tillcreatemodifyuserid,@tillNo,@tillFandBbillID)
	END
	ELSE IF @tillClose = 1
	BEGIN
		UPDATE TillHeader
		SET till_th_statusid = @tillstatusid,
		till_th_endtime = getdate(),
		till_th_cashierid = @tillcashierid
		WHERE till_th_tillid = @tillid AND
		till_th_outletid = @tilloutletid AND
		till_th_companyid = @tillcompanyid
		DECLARE @tillstime VARCHAR(30)
		SELECT  @tillstime =  convert (varchar(30),till_th_starttime,21)
		FROM TillHeader
		WHERE till_th_tillid = @tillid AND
		till_th_outletid = @tilloutletid AND
		till_th_companyid = @tillcompanyid
		INSERT INTO TillHistory(till_hist_id,till_id,till_cashierid,till_starttime,till_endtime,
		till_outletid,till_statusid,till_companyid,till_updatettime,till_statusremarks,
		till_managerid,till_createmodify_user,till_no,till_fandbbillno)
		VALUES (@tillhisoryid,@tillid,@tillcashierid,@tillstime,getdate(),
		@tilloutletid,@tillstatusid,@tillcompanyid,getdate(),@tillstatusremarks,
		@tillmangerid,@tillcreatemodifyuserid,@tillNo,@tillFandBbillID)
	END
	ELSE
	BEGIN
		UPDATE TillHeader
		SET till_th_statusid = @tillstatusid,
		till_th_cashierid = @tillcashierid
		WHERE till_th_tillid = @tillid AND
		till_th_outletid = @tilloutletid AND
		till_th_companyid = @tillcompanyid
		INSERT INTO TillHistory(till_hist_id,till_id,till_cashierid,
		till_outletid,till_statusid,till_companyid,till_updatettime,till_statusremarks,
		till_managerid,till_createmodify_user)
		VALUES (@tillhisoryid,@tillid,@tillcashierid,
		@tilloutletid,@tillstatusid,@tillcompanyid,getdate(),@tillstatusremarks,
		@tillmangerid,@tillcreatemodifyuserid)
	END
	SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgerspandcCosting]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgerspandcCosting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on : 31/05/2003, 17/06/2003
-- Modifed by       : R Harikrishnan, Hariharan R
-- Comments	    : included @lctobeaccounted checking
--		    : packingtypeqty converstion is removed from fobvalue calculation
--		    : (@numshipmentoc) Shipment other charges is calculated excluding the
--	              custom duty difference
CREATE proc [dbo].[spUpdateLedgerspandcCosting] @intCompanyID as int, @intCostingID as int as
begin
Declare @intJournalID as int,
	@strCostingno as varchar(50),
	@intJournalDetailID as int,
	@intINVAccountID as int,
	@intGITAccountid as int,
	@intFinancialID as int,
	@dtCostingDate as datetime,
	@strCostingRemarks as varchar(250),
	@intDepartmentID as int,
	@numCostingAmt as numeric(18,2),
	@dtutime as datetime,
	@intbillid as int,
	@intpoid as int,
	@bitlcopened as bit,
	@numlcmarginamt as numeric(18,2),
	@intlcmarginacccurid as int,
	@intlcmarginaccid as int,
	@intlcaccountid as int,
	@numfobvalue as numeric(18,2),
	@numshipmentoc as numeric(18,2),
	@numdiffingain as numeric(18,2),
	@intdiffaccid as int,
	@intcurrencyid as int,
	@strbillexrates as varchar(250),
	@lctobeaccounted as bit
	/* getting the maximum Journal id from journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) FROM MOaJournalHeader WHERE
	CompanyID = @intCompanyID
	select @lctobeaccounted=isnull(Lctoaccount,0) from miscsettings
	SET @intJournalID = @intJournalID + 1
	select @intdiffaccid = shipmentfixedandactualvaluediff from apackagesettings where
	companyid = @intcompanyid
	
	SELECT @dtCostingDate = chCostingDate, @strCostingRemarks=chRemarks, @intDepartmentID=
	chDepartmentID, @strcostingno = chcostingno, @intinvaccountid = chinventoryaccid,
	@intgitaccountid = chgoodsintransitaccid, @dtutime = updatetime, @intbillid = chbillid
	FROM LOaCostingHeader WHERE chPosted = 0 and chCancelled = 0 and chCompanyID =
	@intCompanyID and chcostingid = @intcostingid
	select @intcurrencyid = currencyid from aaccountmaster where companyid = @intcompanyid
	and accountid = @intinvaccountid
	set @numshipmentoc =0.0
	set @numlcmarginamt =0.0		
	set @numCostingAmt = 0.0
	set @numfobvalue  =0.0		
	set @numdiffingain =0.0
	select @intFinancialID = financialid from vwfinyearperiod where @dtcostingdate between
	sdate and edate
	
	select @intpoid = pbhpoid from losppurchasebillheader where pbhbillid = @intbillid
	select @bitlcopened = pohlcopened, @intlcmarginaccid = pohpurchaseaccountid,
	@intlcaccountid = pohlcaccountid from lopurchaseorderheader where
	pohcompanyid = @intcompanyid and pohpoid = @intpoid and pohcancel = 0
	if @bitlcopened =1 and @lctobeaccounted=1
	begin
		declare @strpymtexrates as varchar(250),
			@numpymtlcmarginexrate as numeric(18,7),
			@numpymtinvexrate as numeric(18,7),
			@numlcmarginamtinvequi as numeric(18,2)
		select @numlcmarginamt = isnull(pddamount,0), @strpymtexrates = phexchangerates
		from ahqpaymentvoucherdebitdetails pd, ahqpaymentvoucherheader ph where
		ph.phpaymentid = pd.pddpaymentid and ph.phcompanyid = pd.pddcompanyid
		and ph.phcompanyid = @intcompanyid and pd.pddhqpoid = @intpoid and
		ph.phlcpayment=''LCM'' and ph.phcancelled =0
		-- the lcmarginamt taken above is considered to be in terms of account
		-- currency, so that amount is converted to inventory account currency terms	
		select @intlcmarginacccurid = currencyid from aaccountmaster where companyid =
		@intcompanyid and accountid = @intlcmarginaccid
		exec spReturnExrate @intlcmarginacccurid, @strpymtexrates,
		@numpymtlcmarginexrate output
		exec spReturnExrate @intCurrencyId, @strpymtexrates, @numpymtinvexrate output
		
		exec spconvertcurrency @numpymtlcmarginexrate, @numpymtinvexrate, @numlcmarginamt,
		@numlcmarginamtinvequi output
	end
	-- to get the total costing amount
	select @numCostingAmt = sum(pt.quantity * bd.pbditemquantity * cd.cdcostingprice)
	, @numfobvalue = sum(pbdItemUnitPrice * bd.pbditemquantity) * pbhinvaccexrate,
	@strbillexrates = pbhexchangerates
	from loacostingdetail cd, loacostingheader ch, losppurchasebillheader bh,
	losppurchasebilldetail bd, apackingtypecapacitydetail pt, aitem i where
	ch.chcostingid = cd.cdcostingid and pt.packingtypeid = bd.pbdPackingTypeID and
	i.itemid = bd.pbditemid and i.unitsid = pt.unitsid and 	bh.pbhbillid = bd.pbdbillid
	and ch.chbillid = bh.pbhbillid and bh.pbhcancelled = 0 and cd.cditemid = bd.pbditemid
	and cdCostingID = @intcostingid group by cd.cdcostingid, pbhexchangerates, pbhinvaccexrate
	set @numshipmentoc  = 0.0
	-- TO Take only the custom duty paid which will be saved in the first record
	-- of loacostingdetail table with caddetailid = 1	
	select @numshipmentoc = isnull(sum(isnull(cadamount,0)),0) from
	LOaCostingAccountDetails cad, aPackageSettings s where
	cad.cadcostingid = @intcostingid and cad.cadaccountid = customsaccid
	and cad.cadCOmpanyid = s.companyid and cad.cadDetailID = 1
	and cad.cadCompanyid = @intCompanyID
	--To take the shipment other charges other than custom duty
	select @numshipmentoc = @numshipmentoc + isnull(sum(isnull(cadamount,0)),0) from
	LOaCostingAccountDetails cad, aPackageSettings s  where
	cad.cadcostingid = @intcostingid and cad.cadaccountid <> customsaccid
	and cad.cadCOmpanyid = s.companyid and cad.cadCompanyid = @intCompanyID
	set @numdiffingain = isnull(@numcostingamt,0) - isnull(@numfobvalue,0) - isnull(@numshipmentoc,0)
	INSERT into MOaJournalHeader (JournalID, CompanyID, JournalDate, ReferenceNo, Remarks,
	FinancialID, Type, CurrencyID, chequedate,updatetime) VALUES (@intJournalID,
	@intCompanyID, @dtCostingDate, @strcostingno, @strCostingRemarks, @intFinancialID,
	''COST'', @intcurrencyid, @dtcostingdate, @dtutime)
	set @intJournalDetailId = 1
	declare @numconsamount as numeric(18,2),
		@numdepamount as numeric(18,2),
		@numresamount as numeric(18,2),
		@intconscurid as int,
		@intdepcurid as int,
		@numtemp as numeric(18,4)
	select @intconscurid = currencyid from acompanymaster where companyid = @intcompanyid
	select @intdepcurid = depcurrencyid from adepartmentmaster where departmentid =
	@intdepartmentid
	set @numtemp = isnull(@numCostingAmt,0) - isnull(@numlcmarginamtinvequi,0)
			- isnull(@numdiffingain,0)
	exec spConvertequiamount @intinvaccountid, ''a'', @intgitaccountid, ''a'', @strbillexrates,
	@numtemp, @numresamount output,''''
	exec spConvertequiamount @intinvaccountid, ''a'', @intconscurid, ''m'', @strbillexrates,
	@numtemp, @numconsamount output,''''
	exec spConvertequiamount @intinvaccountid, ''a'', @intdepcurid, ''m'', @strbillexrates,
	@numtemp, @numdepamount output,''''
	/* inserting the account with the cost price */
	INSERT into MOaJournalDetails (JournalID, JournalDetailID, CompanyID, JournalCredit,
	AccountID, Amount, ActualAmount, departmentid, depamount) VALUES (@intJournalID,
	@intJournalDetailID, @intCompanyID, 1, @intgitaccountid, @numconsamount, @numresamount,
	@intDepartmentID, @numdepamount)
	if @numlcmarginamt > 0.0
	begin
		exec spConvertequiamount @intlcmarginaccid, ''a'', @intconscurid, ''m'',
		@strpymtexrates, @numlcmarginamt, @numconsamount output,''''
		exec spConvertequiamount @intlcmarginaccid, ''a'', @intdepcurid, ''m'',
		@strpymtexrates, @numlcmarginamt, @numdepamount output,''''		
		set @intJournalDetailId = @intJournalDetailId+ 1	
		/* inserting the account with the cost price */
		INSERT into MOaJournalDetails (JournalID, JournalDetailID, CompanyID,
		JournalCredit, AccountID, Amount, ActualAmount,departmentid, depamount)
		VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1, @intlcmarginaccid ,
		@numconsamount, @numlcmarginamt, @intDepartmentID, @numdepamount)
	end
	if @numdiffingain <> 0.0
	begin
		set @numtemp = abs(isnull(@numdiffingain,0))
		exec spConvertequiamount @intinvaccountid, ''a'', @intdiffaccid, ''a'',
		@strbillexrates, @numtemp , @numresamount output,''''
		exec spConvertequiamount @intinvaccountid, ''a'', @intconscurid, ''m'',
		@strbillexrates, @numtemp , @numconsamount output,''''
		exec spConvertequiamount @intinvaccountid, ''a'', @intdepcurid, ''m'',
		@strbillexrates, @numtemp , @numdepamount output,''''
		set @intJournalDetailId = @intJournalDetailId+ 1	
		if @numdiffingain > 0.0
			/* inserting the account with the cost price */
			INSERT into MOaJournalDetails (JournalID, JournalDetailID, CompanyID,
			JournalCredit, AccountID, Amount, ActualAmount,departmentid, depamount)
			VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,
			@intdiffaccid, @numconsamount, @numresamount, @intDepartmentID,
			@numdepamount)
		else
			INSERT into MOaJournalDetails (JournalID, JournalDetailID, CompanyID,
			JournalCredit, AccountID, Amount, ActualAmount,departmentid, depamount)
			VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,
			@intdiffaccid, @numconsamount, @numresamount, @intDepartmentID,
			@numdepamount)
	end
	set @intJournalDetailId = @intJournalDetailId+ 1	
	exec spConvertequiamount @intinvaccountid, ''a'', @intconscurid, ''m'',
	@strbillexrates, @numCostingAmt, @numconsamount output,''''
	exec spConvertequiamount @intinvaccountid, ''a'', @intdepcurid, ''m'',
	@strbillexrates, @numCostingAmt, @numdepamount output,''''
	INSERT into MOaJournalDetails (JournalID, JournalDetailID, CompanyID, JournalCredit,
	AccountID, Amount, ActualAmount,departmentid, depamount) VALUES (@intJournalID,
	@intJournalDetailID, @intCompanyID, 0, @intinvaccountid, @numconsamount, @numCostingAmt,
	@intDepartmentID, @numdepamount)
	update LOaCostingHeader set chPosted =1 WHERE chCompanyID = @intCompanyID
	and chcostingid = @intcostingid
	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[dataExist]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dataExist]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 14/09/2002 12:48:16 AM ******/
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 31/07/2002 2:00:36 PM ******/
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 20/11/2001 9:59:14 AM ******/
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 17/11/2001 9:22:25 PM ******/
/****** Object:  Stored Procedure dbo.dataExist    Script Date: 16/06/2001 15:36:36 ******/
CREATE procedure [dbo].[dataExist] @cid int,@dt smalldatetime
as
declare @retval int
	
	if (select count(invoiceid) from accountsinvoiceheader where companyid = @cid and invoicedate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
	if (select count(receiptid) from receiptvoucherheader where companyid = @cid and receiptdate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
/*
	if (select count(journalid) from journalheader where companyid = @cid and journaldate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
*/
	if (select count(journaltransid) from journaltransheader where companyid = @cid and journaltransdate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
	if (select count(contraid) from contra where companyid = @cid and contradate = @dt)  > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
	if (select count(pbhBillID) from losppurchasebillheader where pbhCompanyID = @cid and pbhBillDate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
	
	if (select count(invoiceid) from accountsinvoiceheader where companyid = @cid and invoicedate = @dt) > 0
	begin
		select @retval = 1
		select @retval
		return 1
	end
select @retval = 0
select @retval
return 0' 
END
GO
/****** Object:  View [dbo].[vwVendorSettlementHeader]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSettlementHeader]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 06/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For Vendor Settlement in Header Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on     : 31-12-2008
-- Modified by     : Regin
-- Comments        : Cancelled field is added as it is needed to add Cancelled watermark.
-------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwVendorSettlementHeader] AS
-- Hq Payments
SELECT  VSH.VSID SettlementID,VSH.Companyid CompanyId,VSH.VSNO SettlementNo,VSH.VSDate SetttlementDate,VSH.DepartmentID
DepartmentID,AD.DepartmentName DepartmentName,VSH.VendorID VendorID,AV.VendorName VendorName,
phPaymentNo ReferenceNo,''HQ Payments'' Type, VSH.Cancelled
FROM    VendorSettlementHeader VSH
INNER JOIN  aHQPaymentVoucherHeader HQP ON VSH.PaymentID = HQP.phPaymentID
INNER JOIN  aDepartmentMaster AD ON VSH.DepartmentID= AD.DepartmentID
INNER JOIN  aVendorMaster AV ON VSH.VendorID= AV.VendorID
UNION ALL
-- Hq DCN
SELECT  VSH.VSID ,VSH.Companyid ,VSH.VSNO ,VSH.VSDate ,VSH.DepartmentID,AD.DepartmentName,VSH.VendorID,AV.VendorName,
DCN.DCNNo,''HQ DCN'', VSH.Cancelled
FROM    VendorSettlementHeader VSH
INNER JOIN  DebitCreditNote DCN ON VSH.dcnid = DCN.DCNId
INNER JOIN  aDepartmentMaster AD ON VSH.DepartmentID= AD.DepartmentID
INNER JOIN  aVendorMaster AV ON VSH.VendorID= AV.VendorID
UNION ALL
-- SHOP DCN
SELECT  VSH.VSID ,VSH.Companyid ,VSH.VSNO ,VSH.VSDate ,VSH.DepartmentID,AD.DepartmentName,VSH.VendorID,AV.VendorName,
LDCN.losDCNNo,''Shop DCN'', VSH.Cancelled
FROM   VendorSettlementHeader VSH
INNER JOIN  losDebitCreditNote LDCN ON VSH.shopid = LDCN.losDCNShopid AND VSH.losdcnid = LDCN.losDCNId
INNER JOIN  aDepartmentMaster AD ON VSH.DepartmentID= AD.DepartmentID
INNER JOIN  aVendorMaster AV ON VSH.VendorID= AV.VendorID
UNION ALL
--Shop Exports
SELECT  VSH.VSID ,VSH.Companyid ,VSH.VSNO ,VSH.VSDate ,VSH.DepartmentID,AD.DepartmentName,VSH.VendorID,AV.VendorName,
LEH.rehExportNo,''Shop Export'', VSH.Cancelled
FROM   VendorSettlementHeader VSH
INNER JOIN   losExportHeader LEH ON VSH.shopid = LEH.rehShopID AND VSH.losexportid = LEH.rehExportID
INNER JOIN  aDepartmentMaster AD ON VSH.DepartmentID= AD.DepartmentID
INNER JOIN  aVendorMaster AV ON VSH.VendorID= AV.VendorID'
GO
/****** Object:  View [dbo].[vwTransferOUT]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTransferOUT]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwTransferOUT    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwTransferOUT] as
select gtdItemID,gtdGodownId,sum(gtdItemGoodQty) as transferin,gthDespatchDate from meiGodownTransferDetail,
meiGodownTransferheader where gtdgodownid=gthFromgodownid and gtddespatchid=gthdespatchid and gthcancelled=0
group by gtdGodownID,gthDespatchdate,gtdItemID'
GO
/****** Object:  View [dbo].[vwSpecialInvoicePopulate]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoicePopulate]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- This view is created to populate the details of given special invoice
-- in lvwAll of frmINV while editing a select special invoice.
--------------------------------------------------------------------------------
-- Created By: Regin T.
-- Created On: 31-08-2009
-- Need of this view:
-- In the Sub PopulateItemDetails of frmMaster of Special Invoice,
-- frmINV.lvwAll is populated using the sub objDb.PopulateListview.
-- To consider Kit Item, the query should have Union All portion.
-- But Union All is difficult to handle following the syntax of objDb.PopulateListview
-- So this view was created to make the population of special invoice details possible.
--------------------------------------------------------------------------------
-- Modified By: Regin T.
-- Modified On: 17-09-2009
-- Modification:
-- Since this view is going to be reused in Return Before Despatch
-- the condition idratetype=0 is removed from the view.
-- This condition will be added in the code in the case of Special Invoice.
-- idratetype is added in the select list.
--------------------------------------------------------------------------------
-- Modified By: Nidheesh P V
-- Modified On: 31-12-2009
-- Modification:  Added Tax details
--------------------------------------------------------------------------------
create  view [dbo].[vwSpecialInvoicePopulate] as
select
idInvoiceID, idShopID, idGodownID idGodownID, Godownname idGodownName,
iditemid idItemID, idratetype idRateType,
locationid idLocationID, lLocationname idLocationName,
shipmentid idShipmentID, sShipmentno idShipmentNo,
cast(cast(reqQty as decimal(18,3)) as varchar(20)) idReqQuantity,
idPackingTypeid idPackingTypeID, idPunitID idUnitID,
cast(cast(IDPQuantity as decimal(18,3)) as varchar(20)) idPQuantity,
cast(cast(IDQuantity as decimal(18,3)) as varchar(20)) idQuantity,
cast(IDUnitPrice as varchar(24)) idUnitPrice, cast(IDactualUnitPrice as varchar(24)) idActualUnitPrice,
ABS(idFreeQuantity) idFreeQuantity, idItemType idItemType,idItemTaxPercentage,idItemTaxAmount,idItemTaxCategory
from
losSpecialInvoiceDetail,
(select min(sshipmentid) sshipmentid, min(sshipmentno) sshipmentno from ashipment) ashipment,
agodown,loiLocation
where
locationid=llocationid and shipmentid=sShipmentid
and idgodownid=godownid  and loilocation.lgodownid=idgodownid --and idratetype=0
and idItemType=''I''
-- Kit Item
union all
select distinct
idInvoiceID, idShopID, idGodownID, Godownname, KitID, idratetype,
locationid, lLocationname, shipmentid, sShipmentno,
cast(cast(min(idKitQuantity)*min(pc.Quantity) as decimal(18,3)) as varchar(20)) ReqQty,
min(km.PackingTypeID), min(km.UnitID),
cast(cast(min(idKitQuantity) as decimal(18,3)) as varchar(20)) PQty,
cast(cast(min(idKitQuantity)*min(pc.Quantity) as decimal(18,3)) as varchar(20)) Qty,
cast(min(idKitActualPrice)*min(idKitQuantity) as varchar(24)) Amount,
cast(min(idKitActualPrice) as varchar(24)) ActualUP, ABS(min(idFreeQuantity)) FreeQty, idItemType,idItemTaxPercentage,idItemTaxAmount,idItemTaxCategory
from
losSpecialInvoiceDetail, aKitItemMaster km, aPackingTypeCapacityDetail pc,
(select min(sshipmentid) sshipmentid, min(sshipmentno) sshipmentno from ashipment) ashipment,
agodown,loiLocation
where
locationid=llocationid and shipmentid=sShipmentid
and idgodownid=godownid  and loilocation.lgodownid=idgodownid  --and idratetype=0
and idKitID=km.KitID and pc.PackingTypeID=km.PackingTypeID and pc.UnitsID=km.UnitID
and idItemType=''K''
group by idInvoiceID, idShopID, idGodownID, Godownname, idItemType, KitID, idratetype,
locationid, lLocationname, shipmentid, sShipmentno,idItemTaxPercentage,idItemTaxAmount,idItemTaxCategory
--------------------------------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceItemStatus]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceItemStatus]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------
/*
CREATED BY  : PRASANTH JOSEPH
CREATED ON  : 14-04-2009
CRATED FOR  : To get Confirmed and Non Confirmed Qty from Special invoice.
MODIFY ON   :
MODIFY BY   : Yogesh Joe 27-06-2009
PUPOSE      : Here all the invoices ie,Cash Invoice,Credit Invoice,Return Before Despatch Invoice and Return after despatch
invoice are getting stored in the same tables(losspecialinvoiceheader and losspecialinvoicedetail).Here we need
to take only Cash and credit invoices.The reason is given below
a)We are avoiding the RAD invoices(which has idraetype=1),whether it is confirmed or non confirmed because
it has no effect on the godown quantity.Because the returned quantity will go only to the respective shop.
b)secondly we are avoiding the confirmed RBD invoice  and the corresponding invoices(Remember when doing RBD invoice
we can''t do a partial return)
c)finally we are avoiding the non-confirmed RBD.Otherwise it''s quantity will be added to the non-confirmed quantities.
It must be prevented
*/
---------------------------------------------
CREATE  view [dbo].[vwSpecialInvoiceItemStatus] as
SELECT godownid,itemid,locationid,shipmentid,sum(confqty) confqty,sum(nonconfqty) nonconfqty from (
SELECT ihinvoiceno, ihinvoicedate,
idgodownid godownid, iditemid itemid, locationid,
shipmentid,
sum(reqqty) confqty,0 as nonconfqty
from
losspecialinvoicedetail d, losspecialinvoiceheader h where despatch=0 and
h.ihinvoiceid=d.idinvoiceid and h.ihshopid=d.idshopid and h.ihcancelled=0
and ihtransfinished=1 and d.idratetype=0
and h.ihnoofocdetails=0  --To avoid confirmed ''Return Berore Despatch'' invoices  (Yogesh Joe 27-06-2009)
and h.IhInvoiceID not in(  --To avoid  those invoices which are returned before despatch (Yogesh Joe 27-06-2009)
select ihnoofocdetails
from
losSpecialInvoiceHeader
where
ihcancelled=0 and ihTransFinished=1 and
ihShopID=h.IhShopID and  ihnoofocdetails<>0
)
group by ihinvoiceno, ihinvoicedate,
idgodownid, iditemid,locationid,
shipmentid
union all
SELECT ihinvoiceno, ihinvoicedate,
idgodownid godownid, iditemid itemid, locationid,
shipmentid,0 as confqty ,sum(reqqty) nonconfqty
from
losspecialinvoicedetail d, losspecialinvoiceheader h where despatch=0 and
h.ihinvoiceid=d.idinvoiceid and h.ihshopid=d.idshopid and h.ihcancelled=0
and d.idratetype=0 and  ihtransfinished=0
and h.ihnoofocdetails=0  --To avoid non-confirmed ''Return Berore Despatch'' invoices  (Yogesh Joe 27-06-2009)
group by ihinvoiceno, ihinvoicedate,
idgodownid, iditemid,locationid,shipmentid
)Invoice group by godownid,itemid,locationid,shipmentid'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceDiffGodown]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceDiffGodown]'))
EXEC dbo.sp_executesql @statement = N'
--Created By  : Sebin T.S
--Created On  : 17/06/09
--Created for solving the issue when same item taken from different godowns at a time in special invoice
CREATE view [dbo].[vwSpecialInvoiceDiffGodown]
as
select idshopid,idInvoiceId, idItemid,  sum(reqqty) idquantity,
--case when ihNoofOCDetails > 0  then -sum(reqqty) else sum(reqqty) end idquantity,
case when ihNoofOCDetails > 0  then -sum(idUnitPrice) else sum(idUnitPrice) end idunitprice,
case when ihNoofOCDetails > 0 then -idcostprice else idcostprice end costprice from losspecialinvoiceHeader
inner join losspecialinvoicedetail on ihInvoiceId=idInvoiceId and ihShopId=idShopId where idRateType=0
--and ihshopid=6 and ihInvoiceId=438
group by idShopid,idinvoiceid, iditemid,idcostprice,ihNoofOCDetails
union all
select idshopid,idInvoiceId, idItemid, sum(reqqty) idquantity,
-sum(idUnitPrice) idunitprice,
-idcostprice costprice from losspecialinvoiceHeader
inner join losspecialinvoicedetail on ihInvoiceId=idInvoiceId and ihShopId=idShopId
where idRateType=1 and ihTransFinished=1 --and ihshopid=6 and ihInvoiceId=438
group by idShopid,idinvoiceid, iditemid,idcostprice,idratetype'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceDetails]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------
/*
CREATED BY  : Yogesh JOe
CREATED ON  : 23-04-2009
CRATED FOR  : To get GodownName,ShopName,Customername,InvoiceNo,InvoiceDate,InvoiceQty,Confirmed of SpecialInvoice
MODIFY ON   :
MODIFY BY   :
*/
---------------------------------------------
CREATE view [dbo].[vwSpecialInvoiceDetails] as
SELECT  ShopName,CustomerName,invType,invNo,invDate,invQty,confirmed,BarCode,godownid from (
SELECT ShopName,PackingBarCode BarCode,idgodownid godownid,
ihinvoiceno invNo, ihinvoicedate invDate,
reqqty invQty,CustomerName,case ihtransfinished when 0 then ''No'' when 1 then ''Yes'' end as confirmed,
case IhCashInvoice when 0 then ''Credit'' when 1 then ''Cash'' end as invType
from
losspecialinvoicedetail d
left outer join losspecialinvoiceheader h on h.ihinvoiceid=d.idinvoiceid and h.ihshopid=d.idshopid
left outer join agodown g on d.idgodownid=g.GodownID
left outer join ashops  s on d.idshopid=s.shopid
left outer join acustomermaster c on h.IhCustomerID=c.CustomerID
left outer join aitempackingdetail pd on d.iditemid=pd.ItemID
where
d.despatch = 0
and h.ihcancelled = 0
and d.idratetype = 0
and  ihnoofocdetails=0--For avoiding RBD invoices
and h.IhInvoiceID not in(--For avoiding those invoices against that RBD invoice taken place
select ihnoofocdetails
from
losSpecialInvoiceHeader
where
ihcancelled=0 and ihTransFinished=1 and
ihShopID=h.IhShopID and  ihnoofocdetails<>0
)
)Invoice'
GO
/****** Object:  View [dbo].[vwspecialinvoiceamount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvoiceamount]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Modified on   : 22/02/03
--Modified by  : leo
--Comments  : v3
-----------------------------------------------------------------
--Modified on   : 04/08/2003, 09/02/2004
--Modified by  : R Harikrishnan, Hariharan
--Comments  : Added the exchangerates sting field
--   : ihTransfinished = 1 added
--modified on :14-08-09
--modified by :Nidheesh
--comments :includede ihNoofOCDetails=0 condition to avoid RBD transactions.
--
-----------------------------------------------------------------
CREATE view [dbo].[vwspecialinvoiceamount] as
select
h.ihcompanyid companyid, h.ihdepartmentid, h.ihshopid shopid, h.ihinvoiceid invoiceid,
h.ihinvoiceno invoiceno, h.ihinvoicedate invoicedate, h.ihduedate,
h.ihcustomerid customerid,sum(d.idunitprice) Amount,0 as settled, ''PDI'' as type,
isnull(ihreferenceno,'''') referenceno, isnull(ihremarks,'''') remarks, h.updatetime,
h.ihexchangerate, h.ihfinancialid, h.ihdepexrate, h.ihexchangerates
from
losSpecialinvoiceheader h , losSpecialinvoicedetail d
where
h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and h.ihcancelled=0 and
h.ihcashinvoice=0 and h.ihproforma=0 and idratetype =0  and ihNoofOCDetails=0
and h.ihTransfinished = 1
group by
h.ihcompanyid, h.ihdepartmentid, h.ihshopid , h.ihinvoiceid, h.ihinvoiceno,
h.ihinvoicedate,h.ihcustomerid, h.ihduedate, h.ihreferenceno, h.ihremarks,
h.updatetime, h.ihexchangerate, h.ihfinancialid, h.ihdepexrate, h.ihexchangerates'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReturnReport]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReturnReport]'))
EXEC dbo.sp_executesql @statement = N'
--Created by : MANUNADH.U
--Created on : 03/11/2011
--Purpose  : To solve the issue in the special  invoice report while select same items from more than
--    one godowns
---jyothish
--modified :20/12/2011
--sum(idItemTaxAmount) added
-----------------------------------------------------------------------------
CREATE view [dbo].[vwSpecialInvoiceReturnReport] AS
select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,sum(idQuantity)idQuantity,
sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice)idUnitPrice,AVG(idActualUnitPrice)idActualUnitPrice,
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,--idGodownID,
ihexchangerates,ac.currencyid,
--dbo.fnIssueSerialNosForSpINV(5023,idGodownID,ihInvoiceId,idItemId) idSerialNo,
''''idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,sum(idItemTaxAmount)idItemTaxAmount ,idItemTaxPercentage
from losspecialinvoiceheader
left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid
left outer join aitem a on iditemid = a.itemid
left outer join apackingtype p on idpackingtypeid = p.packingtypeid
left outer join vwitemdescription vw on a.itemid = vw.itemid
left outer join aunit u on u.unitid = a.unitsid
left outer join acustomermaster ac on ac.customerid = ihcustomerid
left outer join acurrencymaster c on ac.currencyid = c.currencyid
left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid
left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID
where IhCashInvoice=1
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice,
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,--idGodownID,
ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,idItemTaxPercentage
UNION ALL
----Special Invoice - Credit
select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,sum(idQuantity)idQuantity,
sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice) idUnitPrice,AVG(idActualUnitPrice)idActualUnitPrice,
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,--idGodownID,
ihexchangerates,ac.currencyid,  --RefNo-1
--dbo.fnIssueSerialNosForSpINV(5008,idGodownID,ihInvoiceId,idItemId) idSerialNo,
''''idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto ,sum(idItemTaxAmount)idItemTaxAmount ,idItemTaxPercentage
from losspecialinvoiceheader
left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid
left outer join aitem a on iditemid = a.itemid
left outer join apackingtype p on idpackingtypeid = p.packingtypeid
left outer join vwitemdescription vw on a.itemid = vw.itemid
left outer join aunit u on u.unitid = a.unitsid
left outer join acustomermaster ac on ac.customerid = ihcustomerid
left outer join acurrencymaster c on ac.currencyid = c.currencyid
left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid
left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID
where IhCashInvoice=0
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice,
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,--idGodownID,
ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,idItemTaxPercentage'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReturn]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReturn]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on : 29/07/2003
-- Modified by : Kishore
-- Comments    : Replace with script from v2
-----------------------------------------------------------
-- Modified on : 14/10/2003
-- Modified by : Kishore
-- Comments    : Added idFreeQuantity column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--modified by 181203 venki specialinvoice filteration
--Verified by      : Hariharan
--Verified Date     : 04/05/2004 (verified From Dev Server(Fies))
--Modified by :Benzigar S D
--Action :  sum(idUnitPrice)
--Purpose :  To show the total price in case of multiple godown
--Modified by :Abhishek CS
--Action :  Add sales person and change view by using joins in case sales person name is null
--Modified By : Yogesh Joe 14-07-2010
--Action : Added the column idGodownID. It was missing.
--     ''rptSpecialInvReturn_Multi.rpt'' and ''rptSpecialInvReturnwoutdisc_Multi.rpt'' need it.
--Modified by :Abhishek CS on 12-10-10
--Action :  Add cancelled remarks for modified addree showing in SInvoice report
-----------------------------------------------------------------------------
--Modified by :Nidheesh P V
--Modified on :20/07/2011
--Action :  Included Exchange Rates & currency id in select statement.
--Modified Area: In Spl Invoice Reports.
--Reference No :RefNo-1
-----------------------------------------------------------------------------
--Modified by :SHINE
--Modified on :16/09/2011
--Action :  ADDE NEW FIELDS FOR WARRANTY FEATURE
--Modified Area: In Spl Invoice Reports.
--Reference No :RefNo-2
-----------------------------------------------------------------------------
--Modified by :MANUNADH.U
--Modified on :21/09/2011
--Action :  ADD NEW CONDITION TO FILTER SPL INVOICE CASH AND CREDIT TRANSACTIONS TO AVOID DUPLICATE
--			DATA
--Modified Area: In Spl Invoice Reports.
--Reference No :RefNo-3
-----------------------------------------------------------------------------
--Modified by  :AADYAKUMAR.D.V
--Modified on  :01/06/2012
--Action       : For distributing Discount,to show discount in special invoice godown wise report
--Modified Area: In Spl Invoice Reports.
--Ticket id    :VXM-317988
--Reference No :RefNo-4
-----------------------------------------------------------------------------
CREATE view [dbo].[vwSpecialInvoiceReturn] AS
----Special Invoice - Cash
select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,
	sum(idQuantity)idQuantity,sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice)idUnitPrice,
	idActualUnitPrice,idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,
	customerid,Symbol,ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,
	IhCancelledRemarks,IhCancelled,Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,
	ihsalespersonid,Spername,idGodownID,ihexchangerates,ac.currencyid,  --RefNo-1
	dbo.fnIssueSerialNosForSpINV(5023,idGodownID,ihInvoiceId,idItemId) idSerialNo,idServWarrantyUpto,
	idPartsWarrantyUpto,---RefNo-2
idItemTaxAmount ,IhInvoiceAmount,idItemTaxPercentage,
(idActualUnitPrice*idpQuantity)*(ihdiscount/100) dis --RefNo-4
from losspecialinvoiceheader
	left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid
	left outer join aitem a on iditemid = a.itemid
	left outer join apackingtype p on idpackingtypeid = p.packingtypeid
	left outer join vwitemdescription vw on a.itemid = vw.itemid
	left outer join aunit u on u.unitid = a.unitsid
	left outer join acustomermaster ac on ac.customerid = ihcustomerid
	left outer join acurrencymaster c on ac.currencyid = c.currencyid
	left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid
	left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID
where IhCashInvoice=1			--<<RefNo-3>>
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice,
	idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
	ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
	Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,
	ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,
	idItemTaxAmount ,IhInvoiceAmount,idItemTaxPercentage ,idUnitPrice,idpQuantity --RefNo-4
UNION ALL
----Special Invoice - Credit
select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,sum(idQuantity)idQuantity,
	sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice) idUnitPrice,idActualUnitPrice,
	idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
	ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
	Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,
	ihexchangerates,ac.currencyid,  --RefNo-1
	dbo.fnIssueSerialNosForSpINV(5008,idGodownID,ihInvoiceId,idItemId) idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,---RefNo-2
	idItemTaxAmount,IhInvoiceAmount,idItemTaxPercentage,
(idActualUnitPrice*idpQuantity)*(ihdiscount/100) dis --RefNo-4
from losspecialinvoiceheader
	left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid
	left outer join aitem a on iditemid = a.itemid
	left outer join apackingtype p on idpackingtypeid = p.packingtypeid
	left outer join vwitemdescription vw on a.itemid = vw.itemid
	left outer join aunit u on u.unitid = a.unitsid
	left outer join acustomermaster ac on ac.customerid = ihcustomerid
	left outer join acurrencymaster c on ac.currencyid = c.currencyid
	left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid
	left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID
where IhCashInvoice=0			--<<RefNo-3>>
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice,
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,
ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto ,
idItemTaxAmount,IhInvoiceAmount,idItemTaxPercentage,idUnitPrice,idpQuantity --RefNo-4'
GO
/****** Object:  View [dbo].[vwSpecialInvoiceReserveItem]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReserveItem]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 09/12/02
--Modified by  : leo
--Comments  : v3
--modified by 181203 venki specialinvoice filteration
--Modified by : Yogesh Joe 25-05-2009
CREATE view [dbo].[vwSpecialInvoiceReserveItem] as
SELECT ihinvoiceno, ihinvoicedate, idgodownid godownid, iditemid itemid, locationid,
shipmentid, sum(reqqty) qty from
losspecialinvoicedetail d, losspecialinvoiceheader h where despatch=0 and
h.ihinvoiceid=d.idinvoiceid and h.ihshopid=d.idshopid and h.ihcancelled=0
and ihtransfinished=1 and d.idratetype=0
and h.ihnoofocdetails=0--To avoid Return Before Despatch invoices
and h.IhInvoiceID not in(--To avoid invoices corresponding to returned before despatch
select ihnoofocdetails
from
losSpecialInvoiceHeader
where
ihcancelled=0 and ihTransFinished=1 and
ihShopID=h.IhShopID and  ihnoofocdetails<>0
)
group by ihinvoiceno, ihinvoicedate, idgodownid, iditemid,locationid,
shipmentid'
GO
/****** Object:  View [dbo].[vwAccountsInvolved]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccountsInvolved]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on	: 28/09/2003
--Modified by	 	: R Harikrishnan
--Comments		: added Manaam transactions header
--------------------------------------------------------------------------------
-- modified on		: 10/09/2003
-- Modified by		: Kishore
-- Comments 		: Added type condition in losExportHeader
-- modified on		: 18/12/2003
-- Modified by		: venki
-- Comments 		: added spcialinvoiceheader ihtransfinished=1
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--------------------------------------------------------------------------------
CREATE view [dbo].[vwAccountsInvolved]
as
select distinct accountid, companyid from
(select distinct AccountID, companyid from moajournaldetails where AccountID is not null
union all
select distinct TradeDebtorAcID, companyid from asettings
union all
select distinct TradeCreditorAcID, companyid from asettings
union all
select distinct ExchangeDiffAcID, companyid from asettings
union all
select distinct BankCashID, companyid  from accountsinvoiceheader where bankcashid is not null
union all
select distinct DiscountAccountID, companyid from accountsinvoiceheader where discountaccountid is not null
union all
select distinct GrnReturnAccID, grncompanyid from losgoodsreturnnoteheader where GrnReturnAccID is not null
union all
select distinct ihBankcashAccID, ihcompanyid from losinvoiceheader where ihBankcashAccID is not null
union all
select distinct ihDiscountAccID, ihcompanyid from losinvoiceheader where ihDiscountAccID is not null
union all
select distinct ihSalesAccID, ihcompanyid from losinvoiceheader where ihSalesAccID is not null
union all
select distinct ioAccID, iocompanyid from losinvoiceoc where ioAccID is not null
union all
select distinct lphDiscountAccID,lphcompanyid from loslocalpurchaseheader where lphDiscountAccID is not null
union all
select distinct lphBankcashAccID, lphcompanyid  from loslocalpurchaseheader where lphBankcashAccID is not null
union all
select distinct lphPurchaseAccID,lphcompanyid from loslocalpurchaseheader where lphPurchaseAccID is not null
union all
select distinct lpoAccID,lpocompanyid from loslocalpurchaseoc where lpoAccID is not null
union all
select distinct phBankCashID, phcompanyid from lospaymentvoucherheader where phBankCashID is not null
union all
select distinct phdebitaccountid, phcompanyid from lospaymentvoucherheader where phdebitaccountid is not null
union all
select distinct pddAccountID,pddcompanyid  from ahqpaymentvoucherdebitdetails where pddAccountID is not null
union all
select distinct phBankCashID, phcompanyid from ahqpaymentvoucherheader where phBankCashID is not null
union all
select distinct phdebitaccountid,phcompanyid from ahqpaymentvoucherheader where phdebitaccountid is not null
union all
select distinct phGoodsinTransitaccid, phcompanyid from ahqpaymentvoucherheader where phGoodsinTransitaccid is not null
union all
select distinct DiscountAccountID, companyid from bills where DiscountAccountID is not null
union all
select distinct BankCashAccID , companyid from bills where BankCashAccID  is not null
union all
select distinct sehCashAccID, sehcompanyid from losposexchangeheader where sehCashAccID is not null
union all
select distinct sehSalesAccID, sehcompanyid from losposexchangeheader where sehSalesAccID is not null
union all
select distinct seoAccID, seocompanyid from losposexchangeothercharges where seoAccID is not null
union all
select distinct poshCashAccID, poshCompanyID from losposheader where poshCashAccID is not null and poshcancelled=0
union all
select distinct poshSalesAccID, poshCompanyID from losposheader where poshSalesAccID is not null
union all
select distinct posoAccID, posocompanyid from losposothercharges where posoAccID is not null
union all
select distinct pbhDiscountAccID, pbhcompanyid from losppurchasebillheader where pbhDiscountAccID is not null
union all
select distinct pbhBankCashAccID, pbhcompanyid from losppurchasebillheader where pbhBankCashAccID is not null
union all
select distinct pbhPurchaseAccID, pbhcompanyid from losppurchasebillheader where pbhPurchaseAccID is not null
union all
select distinct pboAccID, pbocompanyid from losppurchasebilloc where pboAccID is not null
union all
select distinct rhBankCashAccountID, rhCompanyID from losreceiptvoucherheader where rhBankCashAccountID is not null
union all
select distinct rhdebitaccountid ,rhCompanyID from losreceiptvoucherheader where rhdebitaccountid  is not null
union all
select distinct siAccountid, sicompanyid from losserviceinvoicedetails where siAccountid is not null
union all
select distinct IhBankcashAccID, IhCompanyId from losspecialinvoiceheader where
IhBankcashAccID is not null and ihtransfinished=1
union all
select distinct IhDiscountAccID, IhCompanyId from losspecialinvoiceheader
where IhDiscountAccID is not null and ihtransfinished=1
union all
select distinct IhSalesAccID, IhCompanyId from losspecialinvoiceheader where
IhSalesAccID is not null and  ihtransfinished=1
union all
select distinct ioAccid, iocompanyid from losspecialoc where ioAccid is not null
union all
select distinct AccountID, companyid from billsdebitdetails where AccountID is not null
union all
select distinct FromAccountID, companyid from contra where FromAccountID is not null
union all
select distinct ToAccountID, companyid from contra where ToAccountID is not null
union all
select distinct ChargeAccountID, companyid from contra where ChargeAccountID is not null
union all
select distinct DCNOtherAccId, DCNCompanyid from debitcreditnote where DCNOtherAccId is not null
union all
select distinct DeprAccountID, companyid from depreciationheader where DeprAccountID is not null
union all
select distinct FixedAssetAccID, companyid from fixedasset where FixedAssetAccID is not null
union all
select distinct DepreciationAccId, companyid from fixedasset where DepreciationAccId is not null
union all
select distinct AccountID, companyid from journaltransdetails where AccountID is not null
union all
select distinct cadBankCashAccID, cadcompanyid from loacostingaccountdetails where cadBankCashAccID is not null
union all
select distinct chInventoryaccid, chcompanyid from loacostingheader where chInventoryaccid is not null
union all
select distinct chGoodsinTransitaccid , chcompanyid from loacostingheader where chGoodsinTransitaccid is not null
union all
select distinct pohLCAccountid , pohcompanyid from lopurchaseorderheader where pohLCAccountid  is not null
union all
select distinct pohPurchaseAccountid , pohcompanyid from lopurchaseorderheader where pohPurchaseAccountid  is not null
union all
select distinct aiBankCashID, aicompanyid from losaccountsinvoiceheader where aiBankCashID is not null
union all
select distinct aiDiscountAccountId, aicompanyid from losaccountsinvoiceheader where aiDiscountAccountId is not null
union all
select distinct aiSalesAccID, aicompanyid from losaccountsinvoiceheader where aiSalesAccId is not null
union all
select distinct losDCNOtherAccId, losdcncompanyid from losdebitcreditnote where losdcnotheraccid is not null
union all
select distinct AccountID, companyid from Receiptvouchercreditdetails where accountid is not null
union all
select distinct BankCashAccountID, companyid from Receiptvoucherheader where BankCashAccountID is not null
union all
select distinct debitaccountid, companyid from Receiptvoucherheader where debitaccountid is not null
union all
select distinct Accountid, companyid from serviceinvoicedetails where accountid is not null
union all
select distinct rehBankcashAccID, rehcompanyid from losexportheader where rehBankcashAccID is not null
union all
select distinct abhCashAccId, abhCompanyid from losApartmentBillHeader where abhCashAccId is not null
union all
select distinct abhSalesAccID, abhCompanyid from losApartmentBillHeader where abhSalesAccID is not null
union all
select distinct abhOCAccID, abhCompanyid from losApartmentBillHeader where abhOCAccID is not null
union all
select distinct tbhServiceAccid, tbhCompanyId from losTenantServiceBillHeader where tbhServiceAccid is not null
union all
select distinct tbhBankCashID, tbhCompanyId from losTenantServiceBillHeader where tbhBankCashID is not null
union all
select distinct mghAdavanceAccID, mghCompanyId from losApartmentagreementHeader where mghAdavanceAccID is not null
union all
select distinct mghAccountId, mghCompanyId from losApartmentagreementHeader where mghAccountId is not null
union all
select distinct chCashAccId, chCompanyId from losApartmentCheckOut where chCashAccId is not null
Union all
select distinct chWriteOffAccID, chCompanyId from losApartmentCheckOut where chWriteOffAccID is not null
) s'
GO
/****** Object:  View [dbo].[vwShopInvoices]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvoices]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on 		: 07/08/2003
--Modified by		: R Harikrishnan
--Comments		: Credit Invoice other charges changes
--Modified on 		: 18/12/2003 venki
-----------------------------------------------------------------------------
CREATE view [dbo].[vwShopInvoices] as
--serviceinvoice
select
	h.aicompanyid companyid, h.aishopid shopid, h.aiinvoiceid invoiceid,
	h.aiinvoiceno invoiceno, h.aiinvoicedate invoicedate,
	dateadd(day,h.aidueperiod,h.aiinvoicedate) duedate, h.aicustomerid customerid,
	sum(siServiceQty*siAmount)-h.aidiscount Amount,"PSI" as Type,
	sum(siServiceQty*siAmount)-h.aidiscount * aiexchangerate cAmount,
	sum(siServiceQty*siAmount)-h.aidiscount * aidepexrate dAmount
from
	losaccountsinvoiceheader h , losserviceinvoicedetails d
where
	h.aiinvoiceid=d.siinvoiceid and h.aicompanyid=d.sicompanyid and
	h.aishopid=d.sishopid and h.aicancelled=0 and h.aiposted=0 and
	h.aiproduct=0 and h.aisettled=0
group by
	h.aicompanyid,h.aishopid,h.aiinvoiceid,h.aiinvoiceno,h.aiinvoicedate,
	h.aicustomerid,h.aidueperiod,h.aidiscount, aiexchangerate, aidepexrate
union all
--SPECIALINVOICE
select
	h.ihcompanyid companyid, h.ihshopid shopid, h.ihinvoiceid invoiceid,
	h.ihinvoiceno invoiceno, h.ihinvoicedate invoicedate, h.ihduedate,
	h.ihcustomerid customerid,sum(d.idquantity*d.idunitprice)- h.ihdiscount Amount,
	"PDI" as type, sum(d.idquantity*d.idunitprice)- h.ihdiscount * ihexchangerate cAmount,
	sum(d.idquantity*d.idunitprice)- h.ihdiscount * ihdepexrate dAmount
from
	losSpecialinvoiceheader h , losSpecialinvoicedetail d
where
	h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and
	h.ihcancelled=0 and h.ihposted=0 and h.ihsettled=0 --and d.despatch=1
	and ihtransfinished=1
group by
	h.ihcompanyid, h.ihshopid , h.ihinvoiceid, h.ihinvoiceno, h.ihinvoicedate,
	h.ihcustomerid, h.ihduedate, h.ihdiscount, ihexchangerate, ihdepexrate
union all
--creditinvoice
select
	h.ihcompanyid companyid, h.ihshopid shopid, h.ihinvoiceid invoiceid,
	h.ihinvoiceno invoiceno, h.ihinvoicedate invoicedate, h.ihduedate,
	h.ihcustomerid customerid,sum(d.idquantity*d.idunitprice)- h.ihdiscount Amount ,
	"PCI" as type, sum(d.idquantity*d.idunitprice)- h.ihdiscount * ihexchangerate cAmount ,
	sum(d.idquantity*d.idunitprice)- h.ihdiscount * ihexchangerate dAmount
from
	losinvoiceheader h , losinvoicedetail d
where
	h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and
	h.ihcancelled=0 and h.ihposted=0 and h.ihsettled=0 and h.ihtype =''i''
group by
	h.ihcompanyid, h.ihshopid , h.ihinvoiceid, h.ihinvoiceno, h.ihinvoicedate,
	h.ihcustomerid, h.ihduedate, h.ihdiscount, ihexchangerate, ihdepexrate
union all
--ReExporting Transaction Details
select
	h.rehcompanyid companyid, h.rehshopid shopid, h.rehExportID invoiceid,
	h.rehExportno invoiceno, h.rehExportdate invoicedate, h.rehduedate,
	h.rehcustomerid customerid,sum(d.redquantity*d.redunitprice)- h.rehdiscount Amount ,
	"PCI" as type, sum(d.redquantity*d.redunitprice)- h.rehdiscount * rehexchangerate cAmount ,
	sum(d.redquantity*d.redunitprice)- h.rehdiscount * rehexchangerate dAmount
from
	losExportHeader h , losExportDetail d
where
	h.rehExportID = d.redExportID and h.rehshopid = d.redshopid and
	h.rehcancelled=0 and h.rehposted=0  and h.rehtype =''i'' and
	rehcustomerid is not null
group by
	h.rehcompanyid, h.rehshopid , h.rehExportID, h.rehExportNo, h.rehExportDate,
	h.rehcustomerid, h.rehduedate, h.rehdiscount, rehexchangerate, rehdepexrate'
GO
/****** Object:  View [dbo].[vwitemsplitDetail]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwitemsplitDetail]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwitemsplitDetail    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwitemsplitDetail    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwitemsplitDetail    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwitemsplitDetail    Script Date: 20/11/2001 9:59:06 AM ******/
/****** Object:  View dbo.vwitemsplitDetail    Script Date: 17/11/2001 9:21:54 PM ******/
CREATE view [dbo].[vwitemsplitDetail] as
select loih.ishgodownid,loih.ishid,loih.ishno,loih.ishdate,vwith.itemdescription,loih.ishactualqty,
vwitd.itemdescription itemdescriptiondetail,loid.isdqty,gd.godownname,loac.cdcostingprice from
loiitemsplitheader loih left outer join loiitemsplitdetail loid on
loih.ishid=loid.isdid left outer join vwitemdescription vwith on
loih.ishsplititemid=vwith.itemid left outer join  vwitemdescription vwitd on
loid.isditemid=vwitd.itemid  left outer join agodown gd on
loih.ishgodownid=gd.godownid left outer join loiarrivalheader loia on
loih.ishgodownid=loia.ahlocalgodownid and loih.isharrivalid = loia.aharrivalid
and loih.ishcancelled=0 and loia.ahcancelled=0
left outer join aHQDespatchnoteHeader ahdh on
loia.ahdespatchnoteid=ahdh.dhdespatchnoteid and ahdh.dhcancelled=0
left outer join ahqdespatchnotemain ahdm on
ahdh.dhdespatchnotemainid=ahdm.dnmdespatchnoteid and ahdm.dnmcancelled=0
left outer join loacostingheader loah on ahdm.dnmbillid=loah.chbillid and loah.chcancelled=0
left outer join loacostingdetail loac on loah.chcostingid=loac.cdcostingid
and loac.cditemid=loih.ishsplititemid'
GO
/****** Object:  View [dbo].[vwpaymentswithcontrolaccs]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentswithcontrolaccs]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--modified By	:venki , Hariharan , Hariharan R
--MOdified Date	:03/11/2003 , 07/12/2003
--comments : added payment should displayed on multiple depts
--	   : refjournalid conditions removed
--	   : refPaymentId given for ahqPaymentvoucherheader
CREATE view [dbo].[vwpaymentswithcontrolaccs] as
select h.phpaymentno, h.phpaymentid, h.phpaymentDate, h.phRemarks, dep.departmentname,
maindepid, h.phcompanyid, pddaccountid, pddamount, 0 credit, a.accountdesc, h.phbankcashid, h.phchequedetails,
h.phexchangerates  from
ahqpaymentvoucherdebitdetails d, ahqpaymentvoucherheader h ,
adepcontrolaccounts ca, adepartmentmaster dep, aaccountmaster a where
h.phcompanyid = d.pddCompanyID and h.phpaymentid = d.pddpaymentid and
ca.companyid = d.pddcompanyid and ca.controlaccid = d.pddaccountid and h.phcancelled =0 and
pddaccountid = a.accountid
and refreceiptid is null
--and refjournalid is null and refreceiptid is null and refdcnid is null
and h.phdepartmentid = dep.departmentid
and maindepid <> h.phdepartmentid and ca.maindepid  not in
(select departmentid from
Journaltransheader where paymentid = h.phpaymentid and cancelled = 0
union all
select departmentid from
Receiptvoucherheader where paymentid = h.phpaymentid and cancelled = 0
union all
select dcndepartmentid from debitcreditnote where
parentpaymentid = h.phpaymentid and dcncancelled = 0
union all
select ahqPaymentVoucherheader.phDepartmentid  from ahqPaymentVoucherheader where
ahqPaymentVoucherheader.refPaymentid = h.phpaymentid and ahqPaymentVoucherheader.phcancelled = 0
union all
select 0)'
GO
/****** Object:  View [dbo].[vwguraranteesales]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwguraranteesales]'))
EXEC dbo.sp_executesql @statement = N'
--created date : - 17/08/2002
--created by   : - Hariharan
--modified by venki on 181203 for special invoice trans finished chking
CREATE view [dbo].[vwguraranteesales]
as
select posditemid, posdbillid, poshbillno, poshbilldate, posdguarantee from losposheader,
losposdetail where poshbillid=posdbillid and poshshopid = posdshopid and poshcancelled =0 and
isnull(posdguarantee,'''')<>''''
union all
select iditemid, idinvoiceid, ihinvoiceno, ihinvoicedate, idguarantee from losinvoiceheader,
losinvoicedetail where ihinvoiceid = idinvoiceid and ihshopid = idshopid and ihcancelled =0 and
isnull(idguarantee,'''') <>''''
union all
select iditemid, idinvoiceid, ihinvoiceno, ihinvoicedate, idguarantee from
losspecialinvoiceheader, losspecialinvoicedetail where ihinvoiceid = idinvoiceid and
ihshopid = idshopid and ihcancelled =0 and isnull(idguarantee,'''') <>'''' and ihtransfinished=1
union all
select seditemid, sedexchangeid, sehexchangeno, sehexchangedate, sedguarantee from
losposexchangeheader, losposexchangedetail where sehexchangeid = sedexchangeid and
sehshopid = sedshopid and sehcancelled =0 and isnull(sedguarantee,'''') <>''''
and sedbillorexchange=''E'''
GO
/****** Object:  View [dbo].[vwPurchaseBillPackQty]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillPackQty]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------
--Created By  :Aadyakumar.D.V
--Created Date:05/10/2011
--Purpose     :To list Pack Quantity in Purchase Bill Interface.
------------------------------------------------------------------
--Altered By  :Aadyakumar.D.V
--Altered Date:25/10/2011 ,15/11/2011
--Purpose     :Add new join condition u.UnitID =ap.UnitsID to avoid duplication .
--chnage inner joins to left outer join
------------------------------------------------------------------
CREATE view [dbo].[vwPurchaseBillPackQty] as
select distinct (case when lo.lpdItemQuantity is null then 1 else lo.lpdItemQuantity end)
/(case when ap.Quantity is null then 1 else ap.Quantity end)  PackQty,lo.*
from losLocalPurchaseDetail lo
inner join aItem i on lo.lpdItemID=i.itemid
inner join aUnit u on i.UnitsID=u.UnitID
left outer join aitempackingdetail ai on lo.lpdItemID=ai.itemid and lo.lpdpackid=ai.PackingTypeID
left outer join aPackingTypeCapacityDetail ap on  lo.lpdpackid=ap.PackingTypeID and u.UnitID =ap.UnitsID'
GO
/****** Object:  View [dbo].[vwRefundedSalesTax]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRefundedSalesTax]'))
EXEC dbo.sp_executesql @statement = N'
-- View
------------------------------------------------------------------------------------------
-- Modified by  : Nidheesh P V
-- Date         : 19/10/2011
-- Comments  : To get total sales taxes which are refunded.Created as the format of VwCashSales.
-- This include sales Returns such as goods return,exchnage,Spl inv return.
------------------------------------------------------------------------------------------
-- Modified by  : Jyothish S R
-- Date         : 03/11/2011
--- Comments  : To  Bill No  is added
------------------------------------------------------------------------------------------
-- Modified by  : Rajesh Kamalakshan
-- Date         : 24/11/2011
-- Comments  :Increased precision to 9 digits ,so as to get accuracy in GST report
-- Modified by  : Jyothish
-- Date         : 29/11/2011
-- Comments  : Ref-1
------------------------------------------------------------------------------------------
-- Modified by : Jyothish
-- RefNo       : RefNo-2
-- Date        : 01/12/2011
-- Desc        : Commented filteration tax percentage
-- Modified by : Jyothish
-- RefNo       : RefNo-3
-- Date        : 23/12/2011
-- Desc        : correted goods exchange comapny and deparment tax amount
---== Modified by : Jyothish
-- RefNo       : RefNo-4
-- Date        : 28/03/2012
-- Desc        : correted goods speceil invoice retun
------------------------------------------------------------------------------------------
CREATE  View [dbo].[vwRefundedSalesTax]
As
-- special invoice (cash) - return before despatch
select
ihcompanyid As companyid, ihshopid As shopid, ihinvoicedate As billdate, ihbankcAshaccid As accountid,
convert(numeric(18, 9),-sum(idUnitPrice)) amount,
convert(numeric(18, 9),-sum(idUnitPrice * ihDepExRate)) damount,
convert(numeric(18, 9),-sum(idUnitPrice * ihExchangeRate)) camount,
1 As cAsh, ''d'' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled
,ISNULL(ihUserId,0) as UserID
,isnull(idItemTaxPercentage,0)TaxPercentage
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0)))As TaxAmount
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihDepExRate)As DTaxAmount
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihExchangeRate)As CTaxAmount,IhInvoiceNo,ISNULL(idItemTaxCategory,0) idItemTaxCategory
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
--and isnull(idItemTaxPercentage,0)<>0   --RefNo-2
Group By
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,
ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0),idItemTaxPercentage,IhInvoiceNo , idItemTaxCategory
union all
-- Special invoice return (cash)  - after desp   RefNo-4
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))
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihDepExRate)As DTaxAmount
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihExchangeRate)As CTaxAmount,IhInvoiceNo,ISNULL( idItemTaxCategory,0)
from
losspecialinvoicedetail,losspecialinvoiceheader
where
ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1
--and isnull(idItemTaxPercentage,0)<>0    --RefNo-2
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, 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))
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihDepExRate)As DTaxAmount
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihExchangeRate)As CTaxAmount,IhInvoiceNo,isnull(idItemTaxCategory,0) idItemTaxCategory
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
--and isnull(idItemTaxPercentage,0)<>0   --RefNo-2
Group By
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,
ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0) ,idItemTaxPercentage,IhInvoiceNo,idItemTaxCategory
union all
-- Special invoice return(credit)  - after desp
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))
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihDepExRate)As DTaxAmount
,-COnvert(numeric(18,9), Sum(isnull(idItemTaxAmount,0))* ihExchangeRate)As CTaxAmount ,IhInvoiceNo ,isnull(idItemTaxCategory,0)
from
losspecialinvoicedetail,losspecialinvoiceheader
where
ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice<>1
--and isnull(idItemTaxPercentage,0)<>0  Ref-1
Group By
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,
ihdepexrate, ihexchangerate,ISNULL(ihUserId,0),idItemTaxPercentage ,IhInvoiceNo,idItemTaxCategory
--  RefNo-4
UniOn All
---Exchange (returned items)
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) TaxPercentage
,-COnvert(numeric(18,9),CONVERT(numeric(18,9),Sum(isnull(sedItemTaxAmount,0)))) TaxAmount
,-COnvert(numeric(18,9),CONVERT(numeric(18,9),Sum(isnull(sedItemTaxAmount,0)*sehdepexrate ))) DTaxAmount
,-COnvert(numeric(18,9),CONVERT(numeric(18,9),Sum(isnull(sedItemTaxAmount,0)*sehexchangerate ))) CTaxAmount,sehExchangeNo,ISNULL(sedItemTaxCategory,0)
--RefNo-3
From   losposexchangeheader ph, losposexchangedetail pd
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid
And sehcancelled=0 And sedbillorexchange =''B'' And sedexchangeqty > 0
--and isnull(sedItemTaxPercentage,0)<>0  --RefNo-2
Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,
sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0),sedItemTaxPercentage,sehExchangeNo,sedItemTaxCategory
UniOn All
---goods Return
Select GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate, grnhCustomerId,
-COnvert(numeric(18,9),Sum(grndunitprice))  amount,
-COnvert(numeric(18,9),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,9),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid  ,0 as PdChqCancelled
,ISNULL(grnUserID,0) as UserID
,isnull(idItemTaxPercentage,0) TaxPercentage
,-COnvert(numeric(18,9),Sum(isnull(idItemTaxAmount,0))) TaxAmount
,-COnvert(numeric(18,9),Sum(isnull(idItemTaxAmount,0))*grnhdepExRate) DTaxAmount
,-COnvert(numeric(18,9),Sum(isnull(idItemTaxAmount,0))*grnhExchangeRate) CTaxAmount ,GrnhGoodsreturnnoteNO ,ISNULL( idItemTaxCategory,0)
From losGoodsReturnNoteHeader ih, losGoodsReturnNoteDetail invd
Where ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID
And grnhCancel = 0-- and isnull(idItemTaxPercentage,0)<>0   Ref-1
Group By grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,
GrnhGoodsreturnnoteID, grnhCustomerID, grnhdepartmentid, grnhdepExRate, grnhExchangeRate
,ISNULL(grnUserID,0),idItemTaxPercentage ,GrnhGoodsreturnnoteNO ,  idItemTaxCategory'
GO
/****** Object:  View [dbo].[vwReceiptVoucherHeader]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptVoucherHeader]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 10/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For  Settlement in ReceiptVoucherHeader Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on      :
-- Modified by      :
-- Comments         :
-------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwReceiptVoucherHeader] AS
Select RVH.CompanyID,RVH.ReceiptId,RVH.ReceiptNo,RVH.ReceiptDate,RVH.CustomerID,CustomerName,
0 as VendorID,'''' VendorName,RVH.DepartmentID,RVH.Remarks,RVH.ChequeDetails, RVH.Cancelled
From ReceiptVoucherHeader RVH
INNER JOIN aCustomerMaster AC ON AC.CustomerID =RVH.CustomerID
Union ALL
Select RVH.CompanyID,RVH.ReceiptId,RVH.ReceiptNo,RVH.ReceiptDate,0,'''',
RVH.VendorID,VendorName,RVH.DepartmentID,RVH.Remarks,RVH.ChequeDetails, RVH.Cancelled
From ReceiptVoucherHeader RVH
INNER JOIN aVendorMaster AV ON AV.VendorID =RVH.VendorID'
GO
/****** Object:  View [dbo].[vwPurchaseBillDetailGSTSeparately]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetailGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
/****** 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
/****** Object:  View [dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]'))
EXEC dbo.sp_executesql @statement = N'
--select * from vwPurchaseBillDetail where  pbdbillid=219
/****** 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]
CREATE  view  [dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]
as
--hari altered to handle the costing with out custom duty - 020805
select ph.pbhbilldate, pb.*,uom.unitcode,pt.packingtypecode,uom.unitid,ptc.quantity,
convert(varchar(250),vw.itemdescription) itemdescription, cstm.customcategorypercent,
icp.cdcostingprice,icp.symbol, isnull(custom.cadamount,0) cadamount,oc.cadDescription,
isnull( oc.otherc,0) otherc, icp.cdnewitemcostprice,
icp.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,cadDescription, 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,cadDescription ) 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
--and ph.pbhbillid=219'
GO
/****** Object:  View [dbo].[vwPurchaseBillDetail]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetail]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** 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
CREATE   view  [dbo].[vwPurchaseBillDetail]
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
/****** Object:  View [dbo].[vwPrePurchaseOrderTracking3]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPrePurchaseOrderTracking3]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created By   : Benzigar S D
--Created Date : 09082008
------------------------------------------------------------------------
create view [dbo].[vwPrePurchaseOrderTracking3] as
select vw.pohpoid,vw.pohshopid, case when vw.ShopRequetNO is not null then vw.ShopRequetNO
else mos.Grhrequestno end as ShopRequetNO,
vw.HQRequestNo,vw.QuotationNO
from vwprePurchaseOrderTracking2 vw left outer join mosgoodsrequestheader mos
on vw.pohrequestid=mos.grhrequestid and vw.pohshopid =mos.grhshopid'
GO
/****** Object:  View [dbo].[vwPosServiceInvoiceDetails]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPosServiceInvoiceDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By   : Rajesh , Hariharan R
-- Last Modified on  : 02/06/2003, 09/10/2003, 20/04/2004
-- Comments      : added depexrate
----------------------------------------------------------
--Ref No:1
--Mofified By MANUNADH.U on 07.10.2011
--Purpose: To include GST details to show in the Shop-ServiceInvoice Report
CREATE VIEW [dbo].[vwPosServiceInvoiceDetails] AS
select aih.aiCompanyID, aih.aiInvoiceID, aih.aiInvoiceNo,aih.aiinvoicedate, aih.aiReferenceno,
aih.aiRemarks,aih.aiPosted,aih.aiProforma,aiShopID,case when aih.aiproforma =0 then
''Service Invoice'' when aih.aiproforma =1 then ''Proforma Service Invoice'' end as Header,
case when aih.aiCashInvoice = 0 then ''Credit'' when aih.aiCashInvoice =1 then ''Cash'' end as
Cashorcredit,case when aih.aiCashInvoice = 0 then c.currencyid when aih.aiCashInvoice =1 then
acc.currencyid end as Transcurrencyid,isnull(acc.accountdesc,''N/A'') as bankcashname,c.customername,
isnull(aih.aiChequeNo,''-'') as chequeno,siServiceName,siServiceTerm,siServiceQty,(sd.siAmount)
serviceamt,dacc.accountdesc as discountacc,aih.aiexchangerate,(aidiscount ) as discount,aicancelled,
dateadd(dd,aih.aiDuePeriod,aiinvoicedate) as duedate,c.address1,c.address2,c.address3,
dm.departmentname,aih.aiDepartmentID deptid,aidepExRate,isnull(c2.symbol, c1.symbol)symbol,aiAddress,
c.CUSTOMERTIN,aih.aiTaxAmount,aih.aiTaxPercentage --<<Ref No:1>>
from LOsAccountsInvoiceHeader aih
left outer join aaccountmaster acc on aih.aiCompanyID=acc.companyid and aih.aiBankCashID=acc.accountid
left outer join aaccountmaster dacc on aih.aiCompanyID = dacc.companyid and aih.aiBankCashID = dacc.accountid
left outer join aCurrencymaster c2 on dacc.currencyid = c2.currencyid and dacc.companyid = c2.companyid ,
acustomermaster c, LOsServiceInvoiceDetails sd, adepartmentmaster dm,aCurrencymaster c1
where aih.aiCompanyID = dm.companyid and aih.aiDepartmentID = dm.departmentid and aih.aiProduct = 0
and aih.aiCompanyID = c.companyid and aih.aicustomerid = c.customerid
and aih.aiInvoiceID = sd.siinvoiceid and aih.aicompanyid = sd.sicompanyid
and aih.aishopid = sd.sishopid and c.Currencyid = c1.Currencyid'
GO
/****** Object:  View [dbo].[vwShopgrn]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopgrn]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopgrn    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwShopgrn] as
SELECT grh.GrnCompanyID, GRNhShopid, GrnhInvoiceID as InvoiceID,
sum(isnull(grd.GRNDunitprice,0)) as Amtsettled,
sum(isnull(grd.GRNDunitprice,0)) * grnhexchangerate  cAmtsettled,
sum(isnull(grd.GRNDunitprice,0)) * grnhdepexrate  dAmtsettled
FROM LosGoodsReturnNoteDetail grd
left outer join LosGoodsReturnNoteHeader grh
on GrnhGoodsreturnnoteID = GRNDReturnNoteID and GRNDShopid = grnhShopid
WHERE GrnhCancel = 0
GROUP BY GrnCompanyID, GRNhShopid, GrnhInvoiceID, grnhexchangerate, grnhdepexrate'
GO
/****** Object:  StoredProcedure [dbo].[spDayWiseAvgQtySalesRpt]    Script Date: 10/06/2012 14:17: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].[spDayWiseAvgQtySalesRpt]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- ==============================================================================================
-- Author: LAWRENCE M.
-- Create Date: 24 March 2011
-- Description: To show the F&B Bill details in the Day Wise Avarege Quantity Sales Report -
--     : as per the client requested format.
--	   : If the added item is exist inside the selected sales bill need to show seperatly.
--     : This stored procedure is used to show the Day Wise Avarege Quantity Sales Report.
-- Client     : Wings Service
-- ==============================================================================================
-- Modified by Bijesh.B as on 16-01-2011, change date data type to varchar(10)
-- spDayWiseAvgQtySalesRpt ''20111001'', ''20111030''
CREATE PROCEDURE [dbo].[spDayWiseAvgQtySalesRpt] @Fromdate AS varchar(10),@Todate AS varchar(10)
AS
BEGIN
declare @From as datetime
declare @To as datetime
set @From=convert(datetime,@FromDate)
set @To=convert(datetime,@ToDate)
	CREATE TABLE #TempDayWiseAvgQtySales
		(
			intBillID INT,
			strDishcode VARCHAR(50),
			strDishName VARCHAR(250),
			strUnit VARCHAR(50),
			strweekday VARCHAR(11),
			strSegment VARCHAR(50),
			decRate DECIMAL(18,2)
		)
	IF ISNULL(@From,0)=0
	BEGIN
		SET @From=0
	END
	IF ISNULL(@To,0)=0
	BEGIN
		SET @To=0
	END
	IF @From<>0 AND @To<>0
	BEGIN
		INSERT INTO #TempDayWiseAvgQtySales(intBillID,strDishcode,strDishName,strUnit,strweekday,strSegment,decRate)
		SELECT fb_pd_processid,fb_dd_dishcode,fb_dd_dishname,''Dish'',DATENAME(WEEKDAY, poshbilldate) weekday,seg_header_name,fb_pd_Rate
		FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
			fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID INNER JOIN fb_dishdetails ON
			fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid AND fb_pd_AddedItemtype=0
			INNER JOIN dishsegmentdetail ON seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
			INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
		WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
		GROUP BY fb_pd_processid,fb_dd_dishcode,fb_dd_dishname,seg_header_name,DATENAME(WEEKDAY, poshbilldate),fb_pd_Rate
		INSERT INTO #TempDayWiseAvgQtySales(intBillID,strDishcode,strDishName,strUnit,strweekday,strSegment,decRate)
		SELECT fb_pd_processid,ItemCode,ItemDescription+''[Extras]'',PackingTypeName,DATENAME(WEEKDAY, poshbilldate) weekday,seg_header_name,fb_pd_Rate
		FROM Losposfandbheader INNER JOIN fb_processdetail ON fb_pd_processid=poshBillID AND
			fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID INNER JOIN aitem ON
			itemid=fb_pd_dishid AND fb_pd_AddedItemtype=2
			INNER JOIN dishsegmentdetail ON seg_detail_header_id=poshSegID AND poshCompanyID=seg_detail_companyid
			INNER JOIN dishsegmentheader ON seg_header_id=seg_detail_header_id AND seg_header_companyID=seg_detail_companyid
			INNER JOIN fb_DishAdds ON Fb_da_itemid=ItemID INNER JOIN
			apackingtype ON PackingTypeID=fb_da_packingtypeid
		WHERE CAST(LEFT(poshbilldate,11) AS DATETIME)>=@From AND CAST(LEFT(poshbilldate,11) AS DATETIME)<=@To
		GROUP BY fb_pd_processid,seg_header_name,DATENAME(WEEKDAY, poshbilldate),ItemID,ItemCode,ItemDescription,PackingTypeName,fb_pd_Rate
	END
	SELECT ''Sales Quantity Based on Day'' Heading,strDishcode,strDishName,strUnit,strweekday,strSegment,decRate
	FROM #TempDayWiseAvgQtySales ORDER BY intBillID
	DROP TABLE #TempDayWiseAvgQtySales
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDaySalesAndBankPosition]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDaySalesAndBankPosition]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--exec spDaySalesAndBankPosition  1,''R'',''20030101'',''20030105'',0,0,0
-------------------------------------------------------------------------
--Created on	: 16/05/2003
--Created by	: R Harikrishnan
--Comments	: For Bank POsition Report
-------------------------------------------------------------------------
CREATE procedure [dbo].[spDaySalesAndBankPosition]
	@intCompanyID		as int,
	@strDateRangeType 	as char(1),
	@strFromDate 		as varchar(8),
	@strToDate 		as varchar(8),
	@intShopID 		as int,
	@intDeptID		as int,
	@intChkDeptID		as int
--set @intCompanyID = 1
--set @strDateRangeType =''R''
--set @strFromDate =''20030301''
--set @strToDate =''20030312''
--set @intShopID =0
--set @intDeptID =0
--set @intChkDeptID=0
as
begin
	set nocount on	
	create table #tempSales
		(
			companyid 	int,
			departmentid 	int,
			shopid 		int,
			billdate 	datetime,
			cashsales 	numeric(18,2),
			dcashsales 	numeric(18,2),
			ccashsales 	numeric(18,2),
			creditcard 	numeric(18,2),
			dcreditcard 	numeric(18,2),
			ccreditcard 	numeric(18,2),
			debitcard 	numeric(18,2),
			ddebitcard 	numeric(18,2),
			cdebitcard 	numeric(18,2),
			receipts 	numeric(18,2),
			dreceipts 	numeric(18,2),
			creceipts 	numeric(18,2),
			payments 	numeric(18,2),
			dpayments 	numeric(18,2),
			cpayments 	numeric(18,2),
			creditsales 	numeric(18,2),
			dcreditsales 	numeric(18,2),
			ccreditsales 	numeric(18,2),
			localpurchase 	numeric(18,2),
			dlocalpurchase 	numeric(18,2),
			clocalpurchase 	numeric(18,2),
			RowOrder 	tinyint,
			Type		varchar(100),
			ShopName	Varchar(250),
			colOrder	tinyint
		)
	declare @strSQL as nvarchar(2000),@intDateDiff as smallint
	if @strDateRangeType=''R''
		set @intDateDiff=datediff(dd,convert(datetime,@strFromDate),convert(datetime,@strtoDate))+1
	-- cashsales
	set @strSQl = N''insert into #tempSales
		select cs.companyid ,cs.departmentid, cs.shopid, billdate, sum(actamount) cashsales,
		sum(damount) dcashsales, sum(camount) 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, 0.0 as localpurchase,
		0.0 as dlocalpurchase, 0.0 as clocalpurchase,1 RowOrder, "Cash Sales" Type,s.ShopName, 1 ColOrder
		from vwcashsalestruncated cs left outer join aShops s on cs.companyID=s.companyID and cs.shopid=s.shopID , aaccountmaster am where
		am.misc="CA" and cs.accountid = am.accountid and cs.companyid = am.companyid
		and cash = 1''
	set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
	if @intdeptid>0
		set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and billdate between "'' + @strFromDate + ''" and "'' + @strTodate + ''"''
	set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
	exec sp_Executesql @strSQl
	--Credit Card
	set @strSQl = N''insert into #tempSales
		select cs.companyid ,cs.departmentid, cs.shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
		convert(numeric(18,2),sum(actamount)) as creditcard, convert(numeric(18,2),sum(damount)) as dcreditcard,
		convert(numeric(18,2),sum(camount)) 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, 0.0 as localpurchase, 0.0 as dlocalpurchase,
		0.0 as clocalpurchase,1 RowOrder, "Cash Sales" Type ,s.ShopName, 1 ColOrder
		from vwcashsalestruncated cs left outer join aShops s on cs.companyID=s.companyID and cs.shopid=s.shopID , aaccountmaster am
		where am.misc = "CC" and cs.accountid = am.accountid and cs.companyid = am.companyid
		and cash=1''
	set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
	if @intDeptID>0
		set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and billdate between "'' + @strFromDate + ''" and "'' + @strTodate + ''"''
	set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
	exec sp_Executesql @strSQl
	--debit card sales
	set @strSQl = N''insert into #tempSales
		select cs.companyid,cs.departmentid, cs.shopid, billdate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
		0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, convert(numeric(18,2),sum(actamount))
		as debitcard, convert(numeric(18,2),sum(damount)) as ddebitcard, convert(numeric(18,2),sum(camount))
		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, 1 RowOrder, "Cash Sales" Type ,s.ShopName, 1 ColOrder
		from vwcashsalestruncated cs left outer join aShops s on cs.companyID=s.companyID and cs.shopid=s.shopID , aaccountmaster am where
		am.misc ="DC" and cs.accountid = am.accountid and cs.companyid = am.companyid
		and cash=1 ''
	set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
	if @intDeptID>0
		set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and billdate between "'' + @strFromDate + ''" and "'' + @strTodate + ''"''
	set @strSQl=@strSQl + '' group by cs.companyid ,cs.departmentid, cs.shopid, billdate, s.ShopName''
	exec sp_Executesql @strSQl
	--credit sales
	Set @strSQl = N''insert into #tempSales
		select cs.companyid ,cs.departmentid, cs.shopid, billdate, 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, convert(numeric(18,2),sum(actamount)) as creditsales,
		convert(numeric(18,2),sum(damount)) as dcreditsales, convert(numeric(18,2),sum(camount))
		as ccreditsales, 0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase
		,2 RowOrder, "Credit Sales",s.ShopName, 1 ColOrder from vwcashsalestruncated cs left outer join aShops s on cs.companyID=s.companyID and cs.shopid=s.shopID
		where cs.cash=0 ''
	set @strSQL=@strSQL + N'' and cs.companyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and cs.shopID='' + convert(varchar(10),@intShopID)
	if @intDeptID>0
		set @strSQL=@strSQL + N'' and cs.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and cs.billdate between "'' + @strFromDate + N''" and "'' + @strTodate + ''"''
	set @strSQL=@strSQL + N'' group by cs.companyid ,cs.departmentid, cs.shopid, cs.billdate, s.ShopName''
	exec sp_Executesql @strSQl
	--Receipts
	set @strSQl = N''insert into #tempSales
		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,2),sum(drAmount)) receipts,
		convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
		convert(numeric(18,2),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,5 RowOrder, "Reciepts" Type,s.ShopName, 1 ColOrder
		from losDummyReceiptHeader rh, acustomermaster cm,aShops s
		where rh.drcustomerid=cm.customerid and rh.drcompanyid=cm.companyid
		and rh.drCompanyid*=s.CompanyID and rh.drShopID*=s.ShopID and drcancelled=0''
	set @strSQL=@strSQL + N'' and drcompanyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and drshopID='' + convert(varchar(10),@intShopID)
	if @intDeptID>0
		set @strSQL=@strSQL + N'' and drdepartmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and drdate between "'' + @strFromDate + ''" and "'' + @strTodate + ''"''
	set @strSQl=@strSQl + '' group by drcompanyid, drdepartmentid, drshopid, drdate, s.ShopName''
	exec sp_Executesql @strSQl
	--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
	set @strSQl = N''insert into #tempSales
		select rh.companyid,rh.departmentid, s.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,2),sum(customeramount)) receipts,
		convert(numeric(18,2),sum(amount * depexrate)) dreceipts,
		convert(numeric(18,2),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,5 RowOrder, "Reciepts",s.ShopName, 1 ColOrder
		from receiptvoucherheader rh,receiptvoucherdetails rd, ashops s
		where rh.receiptid=rd.receiptid and rh.companyid = rd.companyid
		and rh.departmentid=s.departmentid and rh.cancelled=0 and s.companyid=rh.companyid and
		((rh.dummyreceiptid is null and rh.recshopid is null) or
		(rh.dummyreceiptid=0 and rh.recshopid=0)) ''
	set @strSQL=@strSQL + N'' and rh.companyid='' + convert(varchar(10),@intCompanyID)
	if @intShopID>0
		set @strSQL=@strSQL + N'' and s.shopid='' + convert(varchar(10),@intShopID)
	if @intDeptID>0
		set @strSQL=@strSQL + N'' and rh.departmentid='' + convert(varchar(10),@intdeptid)
	if @strDateRangeType=''R''
		set @strSQL=@strSQL + N'' and rh.receiptdate between "'' + @strFromDate + N''" and "'' + @strTodate + ''"''
	set @strSQL=@strSQL + N'' group by rh.companyid,rh.departmentid, s.shopid, rh.receiptdate, s.ShopName''
	exec sp_Executesql @strSQl
	if @intDateDiff<=0
		set @intDateDiff=1
	insert into #tempSales
	select
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,sum(ts.cashsales) ,sum(ts.dcashsales) ,
		sum(ts.ccashsales) ,sum(ts.creditcard) ,sum(ts.dcreditcard) ,sum(ts.ccreditcard) ,sum(ts.debitcard) ,
		sum(ts.ddebitcard) ,sum(ts.cdebitcard) ,sum(ts.receipts) ,sum(ts.dreceipts) ,sum(ts.creceipts) ,
		sum(ts.payments) ,sum(ts.dpayments) ,sum(ts.cpayments) ,sum(ts.creditsales) ,sum(ts.dcreditsales) ,
		sum(ts.ccreditsales) ,sum(ts.localpurchase) ,sum(ts.dlocalpurchase) ,sum(ts.clocalpurchase) ,
		3 RowOrder ,''Revenue'' Type ,dm.DepartmentName , 1 ColOrder
	from 	
		#tempSales ts,aDepartmentMaster dm
	where
		ts.companyID=dm.CompanyID and ts.DepartmentID=dm.DepartmentID and
		roworder<3 and ts.DepartmentID is not null
	group by
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,dm.DepartmentName
	
	insert into #tempSales
	select
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,sum(ts.cashsales)/@intDateDiff ,
		sum(ts.dcashsales)/@intDateDiff ,sum(ts.ccashsales)/@intDateDiff ,
		sum(ts.creditcard)/@intDateDiff ,sum(ts.dcreditcard)/@intDateDiff ,
		sum(ts.ccreditcard)/@intDateDiff ,sum(ts.debitcard)/@intDateDiff ,
		sum(ts.ddebitcard)/@intDateDiff ,sum(ts.cdebitcard)/@intDateDiff ,
		sum(ts.receipts)/@intDateDiff ,sum(ts.dreceipts)/@intDateDiff ,
		sum(ts.creceipts)/@intDateDiff ,sum(ts.payments)/@intDateDiff ,
		sum(ts.dpayments)/@intDateDiff ,sum(ts.cpayments)/@intDateDiff ,
		sum(ts.creditsales)/@intDateDiff ,sum(ts.dcreditsales)/@intDateDiff ,
		sum(ts.ccreditsales)/@intDateDiff ,sum(ts.localpurchase)/@intDateDiff ,
		sum(ts.dlocalpurchase)/@intDateDiff ,sum(ts.clocalpurchase)/@intDateDiff ,
		4 RowOrder ,''Daily Average'' Type ,dm.DepartmentName , 1 ColOrder
	from 	
		#tempSales ts,aDepartmentMaster dm
	where
		ts.companyID=dm.CompanyID and ts.DepartmentID=dm.DepartmentID and
		ts.roworder<3 and ts.departmentID is not null
	group by
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,dm.DepartmentName
	insert into #tempSales
	select
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,sum(cashsales)/@intDateDiff ,
		sum(dcashsales)/@intDateDiff ,sum(ccashsales)/@intDateDiff ,
		sum(creditcard)/@intDateDiff ,sum(dcreditcard)/@intDateDiff ,
		sum(ccreditcard)/@intDateDiff ,sum(debitcard)/@intDateDiff ,
		sum(ddebitcard)/@intDateDiff ,sum(cdebitcard)/@intDateDiff ,
		sum(receipts)/@intDateDiff ,sum(dreceipts)/@intDateDiff ,
		sum(creceipts)/@intDateDiff ,sum(payments)/@intDateDiff ,
		sum(dpayments)/@intDateDiff ,sum(cpayments)/@intDateDiff ,
		sum(creditsales)/@intDateDiff ,sum(dcreditsales)/@intDateDiff ,
		sum(ccreditsales)/@intDateDiff ,sum(localpurchase)/@intDateDiff ,
		sum(dlocalpurchase)/@intDateDiff ,sum(clocalpurchase)/@intDateDiff ,
		6 RowOrder ,''Daily Average'' Type ,dm.DepartmentName ShopName, 1 ColOrder
	from 	
		#tempSales ts,aDepartmentMaster dm
	where
		ts.companyID=dm.CompanyID and ts.DepartmentID=dm.DepartmentID and
		ts.roworder=5 and ts.departmentID is not null
	group by
		ts.companyid ,ts.departmentid ,ts.shopid , ts.billdate ,dm.DepartmentName
	
	Insert into #tempSales
		(companyid,departmentid,billdate,cashsales,dcashsales,ccashsales,
		RowOrder,Type,ShopName,colOrder)
		exec spBankPosition @intCompanyID,@strToDate,@intDeptID
	
	select
		ts.companyid, ts.departmentid, shopid, billdate,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
			else convert(numeric(18,2),sum(dcashsales)) end cashsales,
		convert(numeric(18,2),sum(dcashsales)) dcashsales,
		convert(numeric(18,2),sum(ccashsales)) ccashsales,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
			else convert(numeric(18,2),sum(dreceipts)) end receipts,
		convert(numeric(18,2),sum(dreceipts)) dreceipts,
		convert(numeric(18,2),sum(creceipts)) creceipts,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
			else convert(numeric(18,2),sum(dpayments)) end payments,
		convert(numeric(18,2),sum(dpayments)) dpayments ,
		convert(numeric(18,2),sum(cpayments)) cpayments ,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
			else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
		convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
		convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
			else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
		convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
		convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
			else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
		convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
		convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
			else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
		convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
		convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
		RowOrder, Type,dm.DepartmentName ShopName,@intDateDiff TotalDays, 1 ColOrder
	from
		#tempsales ts,aDepartmentMaster dm
	where
		ts.CompanyID=dm.CompanyID and ts.DepartmentID = dm.DepartmentID and
		ts.departmentID is not null
	group by
		ts.companyID,ts.departmentID,shopID,Billdate,RowOrder, Type,  colOrder,dm.DepartmentName
	union all
	select
		a.companyid,0, 0, '''',
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccashsales))
			else convert(numeric(18,2),sum(dcashsales)) end cashsales,
		convert(numeric(18,2),sum(dcashsales)) dcashsales,
		convert(numeric(18,2),sum(ccashsales)) ccashsales,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(creceipts))
			else convert(numeric(18,2),sum(dreceipts)) end receipts,
		convert(numeric(18,2),sum(dreceipts)) dreceipts,
		convert(numeric(18,2),sum(creceipts)) creceipts,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(cpayments))
			else convert(numeric(18,2),sum(dpayments)) end payments,
		convert(numeric(18,2),sum(dpayments)) dpayments ,
		convert(numeric(18,2),sum(cpayments)) cpayments ,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditsales))
			else convert(numeric(18,2),sum(dcreditsales)) end creditsales,
		convert(numeric(18,2),sum(dcreditsales)) dcreditsales,
		convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(ccreditcard))
			else convert(numeric(18,2),sum(dcreditcard)) end creditcard,
		convert(numeric(18,2),sum(dcreditcard)) as dcreditcard,
		convert(numeric(18,2),sum(ccreditcard)) as ccreditcard,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(cdebitcard))
			else convert(numeric(18,2),sum(ddebitcard)) end debitcard,
		convert(numeric(18,2),sum(ddebitcard)) as ddebitcard,
		convert(numeric(18,2),sum(cdebitcard)) as cdebitcard,
		case when @intChkDeptID =0 then convert(numeric(18,2),sum(clocalpurchase))
			else convert(numeric(18,2),sum(dlocalpurchase)) end localpurchase,
		convert(numeric(18,2),sum(dlocalpurchase)) as dlocalpurchase,
		convert(numeric(18,2),sum(clocalpurchase)) as clocalpurchase,
		RowOrder, Type,b.Name shopname,@intDateDiff TotalDays, 2 ColOrder
	from
		#tempsales a, aCompanyMaster b
	where
		a.companyID=b.CompanyID and a.departmentID is not null
	group by
		a.companyID,RowOrder, Type,b.Name
	order by RowOrder,Type
	drop table #tempsales
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCommissiONInvoiceItemDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCommissiONInvoiceItemDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By 	: dheena
--Created ON	: 07/12/2003
--Comments	: For commissiON Invoice Report(Male Ofice operatiONs)
--		: Item Details
CREATE PROC [dbo].[spCommissiONInvoiceItemDetails]
	@intShopID 	AS int,
	@intInvoiceID 	AS int
as
BEGIN
	-- For Testing Purpose R Harikrishnan
	 --set @intShopID=16
	 --set @intInvoiceID=67
	SELECT
		sih.aiShopID,sih.aiInvoiceID,sih.aiInvoiceNo,sih.aiInvoiceDate,sih.aiReferenceno,sih.aiRemarks,
		sih.aiClearingComPerc,cust.CustomerName,cust.Symbol,sid.siServiceName,
		sid.siAmount invoicedetailamount ,sid.siClearingCommAmt,''''  ClrReqPONo,lh.LPClrReqPONo,
		sih.aiPOCommPer,bnhboateNoteNo,dateadd(d,isnull(sih.aiDuePeriod,0),sih.aiInvoiceDate) duedate
		,sih.aiDuePeriod,lh.detailamount lpAmount, sid.siClearingOCAmt,
		isnull(sid.siClearingCommAmt, 0) + isnull(sid.siClearingOCAmt, 0) PoAmount,
		lh.PONo,lh.ItemDescription,lh.unit,lh.qty,lh.detailamount, ''Local PO'' Type,aiCashPaidByshop
	FROM
		losAccountsInvoiceHeader sih
		left outer join losShipmentBNheader on sih.aiBoatnoteid=bnhboatnoteId and
		sih.aiShopID=bnhshopid inner join losShipmentBNdetail on
		bnhboatnoteId=bndboatnoteId and bnhShopId=bndShopId
		LEFT OUTER JOIN (SELECT
			lph.shopID,lph.POID,lph.PONo LPClrReqPONo,a.PONo,lpd.ItemDescription,
			lpd.Unit,lpd.Qty,lpd.Amount detailamount,DetailID
		FROM
			LosLPHeader lph left outer join losLocalClearenceRequestHeader a
			on lph.ClearenceReqID=a.ClearenceReqID and lph.ShopID=a.ShopID,
			LosLPdetail lpd
		WHERE
			lpd.POID=lph.poid and lph.ShopID=lpd.ShopID
			)lh ON bndShopId=lh.ShopID and bndlppoid=lh.poid
		LEFT OUTER JOIN (SELECT
			cm.CustomerID,cm.CustomerName,cm.companyID,curr.Symbol
		FROM
			aCustomerMASter cm,aCurrencyMASter curr
		WHERE
			cm.CompanyID = curr.CompanyID and cm.CurrencyID =curr.currencyID) cust
		ON sih.aiCustomerID= cust.CustomerID ,
		losServiceInvoiceDetails sid 		
	WHERE
		sih.aiShopID=sid.siShopID and sih.aiInvoiceID=sid.siInvoiceID
		and sih.aiShopID= @intShopID and sih.aiInvoiceID=@intInvoiceID
		and lh.DetailID=bndlpdetailid
		and lh.poid=bndlppoid and sid.siLocalPOId=lh.poid
union all
	SELECT
		sih.aiShopID,sih.aiInvoiceID,sih.aiInvoiceNo,sih.aiInvoiceDate,sih.aiReferenceno,sih.aiRemarks,
		sih.aiClearingComPerc,cust.CustomerName,cust.Symbol,sid.siServiceName,
		sid.siAmount,sid.siClearingCommAmt,rh.PONo ,'''' ,
		sih.aiPOCommPer,bnhboateNoteNo,dateadd(d,isnull(sih.aiDuePeriod,0),sih.aiInvoiceDate) duedate
		,sih.aiDuePeriod, sid.siAmount, sid.siClearingOCAmt,
		isnull(sid.siClearingCommAmt, 0) + isnull(sid.siClearingOCAmt, 0) PoAmount,
		'''' pono,'''' ItemDescription,'''' unit,''0.000'' qty,''0.00'' detamt,''Clearence'',aiCashPaidByshop
	FROM
		losAccountsInvoiceHeader sih
		left outer join losShipmentBNheader on sih.aiBoatnoteid=bnhboatnoteId and
		sih.aiShopID=bnhshopid
		LEFT OUTER JOIN (SELECT
			cm.CustomerID,cm.CustomerName,cm.companyID,curr.Symbol
		FROM
			aCustomerMASter cm,aCurrencyMASter curr
		WHERE
			cm.CompanyID = curr.CompanyID and cm.CurrencyID =curr.currencyID) cust
		ON sih.aiCustomerID= cust.CustomerID  ,
		losServiceInvoiceDetails sid,ClearenceRequestHeader rh		
	WHERE
		sih.aiShopID=sid.siShopID and sih.aiInvoiceID=sid.siInvoiceID and
		 sid.siShopID=rh.ShopID and sid.siclearingReqId=rh.ClearenceReqID and	
		 sih.aiShopID= @intShopID and sih.aiInvoiceID=@intInvoiceID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCommissiONInvoice]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCommissiONInvoice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created By 	: R Harikrishnan, Hariharan R, Thomas Dheena, Hariharan R
--Created ON	: 29/07/2003, 26/11/2003, 08/12/2003
--Comments	: For commissiON Invoice Report(Male Ofice operatiONs)
--		: Modified to get the PO amount
-- Modifed By dheena 12/11/2003
--		: Modified to add request no from Customer
--		: aVendorMaster is removed
-----------------------------------------------------------------------
CREATE PROC [dbo].[spCommissiONInvoice]
	@intShopID 	AS int,
	@intInvoiceID 	AS int
AS
BEGIN
	-- For Testing Purpose R Harikrishnan
	-- set @intShopID=17
	-- set @intInvoiceID=13
	SELECT
		sih.aiShopID,sih.aiInvoiceID,sih.aiInvoiceNo,sih.aiInvoiceDate,sih.aiReferenceno,sih.aiRemarks,
		sih.aiClearingComPerc,cust.CustomerName,cust.Symbol,sid.siServiceName,
		sid.siAmount,sid.siClearingCommAmt,rh.PONo ClrReqPONo,lh.LPClrReqPONo,
		sih.aiPOCommPer,bnhboateNoteNo,dateadd(d,isnull(sih.aiDuePeriod,0),sih.aiInvoiceDate) duedate
		,sih.aiDuePeriod, sid.siAmount, sid.siClearingOCAmt,
		isnull(sid.siClearingCommAmt, 0) + isnull(sid.siClearingOCAmt, 0) PoAmount,
		lh.PONo
	FROM
		losAccountsInvoiceHeader sih
		left outer join losShipmentBNheader on sih.aiBoatnoteid=bnhboatnoteId and
		sih.aiShopID=bnhshopid
		LEFT OUTER JOIN (SELECT
			cm.CustomerID,cm.CustomerName,cm.companyID,curr.Symbol
		FROM
			aCustomerMASter cm,aCurrencyMASter curr
		WHERE
			cm.CompanyID = curr.CompanyID and cm.CurrencyID =curr.currencyID) cust
		ON sih.aiCustomerID= cust.CustomerID  ,
		losServiceInvoiceDetails sid
		LEFT OUTER JOIN ClearenceRequestHeader rh
		ON sid.siShopID=rh.ShopID and sid.siclearingReqId=rh.ClearenceReqID
		LEFT OUTER JOIN (SELECT
			lph.shopID,lph.POID,lph.PONo LPClrReqPONo,a.PONo
		FROM
			LosLPHeader lph left outer join losLocalClearenceRequestHeader a
			on lph.ClearenceReqID=a.ClearenceReqID and lph.ShopID=a.ShopID)lh
		ON sid.siShopID=lh.ShopID and sid.siLocalPOId=lh.POID
	WHERE
		sih.aiShopID=sid.siShopID and sih.aiInvoiceID=sid.siInvoiceID and
		sih.aiShopID=@intShopID and sih.aiInvoiceID=@intInvoiceID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDepNew]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBalanceSheetDepNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spBalanceSheetDepNew  ''20040323'', 1, 1, 0, 3, 0
-- Last Modified : 24/01/2004, 20/03/2004, 15/04/2004, 27/04/2004
-- Modified by   : Kishore, Hariharan
--          	 : included level (30/05/03)
--               : removed account head filteration deptwise (25/08/2003)
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : included consolidation venki 261203
--		 : Removed cursor and given temporary table names
--		 : carry forwarding of unclosed financial year done
--		 : Financialid considerations corrected
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spBalanceSheetDepNew] (@strToDate as varchar(10),
@intCompanyID as int,
@intDepartmentId as int,
@bitcons as bit,
@intlevel as int = 0,
@intconsolidation as int =0 ) AS
Begin
set nocount on
Declare @AcCode as varchar(100),
	@AcID as int,
	@dblDebit as numeric(18,2),
	@dblCredit as numeric(18,2),
	@intParentGroupID as int,
	@strGroupName varchar(50),
	@GroupID as int,
	@dtToDate as datetime,
	@dtFromDate as datetime,
	@strFromdate as varchar(10),
	@intCount as integer,
	@intFinId as int,
	@dtPrevFinUnclosedSDate as datetime,
	@dtLastFinUnclosedEDate as datetime,
	@intLastFinId as int
Create table #vwJournalDetails(companyid int,
journalid	int,
journaldetailid	int,
journalcredit	bit,
accountid	int,
Amount	numeric(18,2),
ActualAmount	numeric(18,2),
departmentid	int,
depamount	numeric(18,2),
PostGroup int)
Create table #Tempjournalheader
(JournalID	int,
CompanyID	int,
JournalDate	smalldatetime,
ReferenceNo	varchar(100),
Remarks	varchar(250),
Type	char(10),
Cancel	bit,
Realised	bit,
CurrencyId	int,
FinancialID	int,
chequedate	datetime,
updatetime	datetime,
bankdate	datetime)
Create table #BalSheet(
	CompanyID int,
	AccCode varchar(100),
	AcDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	ParentGroupID int,
	ParentGroupName1 varchar(100),
	ParentGroupName2 varchar(100),
	ParentGroupName3 varchar(100),
	ParentGroupName4 varchar(100),
	ParentGroupName5 varchar(100),
	ParentGroupName6 varchar(100),
	ParentGroupName7 varchar(100), AccId int, DepartmentId int)
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),
			AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,
			orderno int, levelcode int, departmentid int,
			DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))
Create table #BalSheetFinal(
	CompanyID int,
	AccCode varchar(100),
	AcDesc varchar(100),
	AcType varchar(1),
	GroupID int,
	GroupName varchar(100),
	OBDr numeric(18,2),
	OBCr numeric(18,2),
	DebitAmt numeric(18,2),
	CreditAmt numeric(18,2),
	AccId int, DepartmentId int, orderno int,
	levelcode int,
	Checked int,
	ProfitLoss Numeric(18,2),
	ParentGroupId int)
-- create the temporary table to insert sub departments
-- table name is given as #SubDepts1 to avoid conflicts
-- with #SubDepts inside the sp
create table #SubDepts1(DeptId int)
if @intconsolidation=0
insert into #SubDepts1 values(@intDepartmentId)
else
-- get the sub depts into the temporary table
insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId
set @dtToDate = CONVERT(DATETIME,@strToDate)
	select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),
@intFinId = financialid from vwfinyearperiod
where convert(datetime,@strToDate,101) between sdate and edate
	 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )
	Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening
	where CompanyId = @intCompanyId and FinancialId <= @intFinId
	if @intLastFinId = 0
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = (Select min(financialid) from afinancialyear where
		companyid = @intCompanyId ) and CompanyId= @intCompanyId
	ELSE
		Select 	@dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod
		where financialid = @intLastFinId and CompanyId= @intCompanyId
	insert #Tempjournalheader
	Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate
	and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId
	insert #vwJournalDetails
	Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where
	Journaldate>=@dtPrevFinUnclosedSDate and
	JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId
	and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in
	(Select Deptid from #SubDepts1)
--to change the parent group if level id > 0	
if @intlevel > 0
begin
	    create table #temp (
			levelgroupid 	int 	null,
			parentid	int 	null
					)
	 create table #lowergroup (lowergroupid int null)
	    create table #levelgroup(
			levelgroupid 		int 	null,
			levelgroupparentid	int 	null,
			groupid 		int 	null,
			parentgroupid		int 	null
				)
			
			Declare @intlgid as int
			Declare @intlgpid as int
	    insert into #temp
			select l.groupid, l.parentgroupid from vwgroupmasterwithlevel l
			where levelgm =  @intlevel
	    select @intcount = count(*) from #temp
	    while @intcount <> 0
		begin
		    select @intlgid = max(levelgroupid) from #temp
		    select @intlgpid = parentid from #temp where levelgroupid = @intlgid
		    delete from #lowergroup
		
		    insert into #lowergroup
				exec spLeafNodeValues @intcompanyid, @intlgid
	    insert into #levelgroup
			select @intlgid, @intlgpid, lowergroupid, @intlgpid from #lowergroup
		    delete from #temp where levelgroupid = @intlgid
		    select @intcount = count(*) from #temp
		end
	    drop table #temp
	    drop table #lowergroup			
	end
	Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,
	OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, ParentGroupName1, ParentGroupName2,
	ParentGroupName3, ParentGroupName4, ParentGroupName5, ParentGroupName6,
	ParentGroupName7, AccId, DepartmentID)	
	Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
	GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, pg1, pg2, pg3,
	pg4, pg5, pg6, pg7, AccountID, @IntDepartmentId DepartmentId from
	(SELECT am.CompanyId, AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID, GM.GroupDesc,
	0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, '''' pg1, '''' pg2, '''' pg3,
	'''' pg4, '''' pg5, '''' pg6, '''' pg7 FROM aAccountMaster AM,aGroupMaster GM, adeptAccounts d,
	#SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
	GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
	and am.Accountid = d.daAccountId and am.CompanyId = d.daCompanyId
	AND d.dadepartmentid = dep.deptid
	Union
	SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,
	GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, '''' pg1, '''' pg2, '''' pg3,
	'''' pg4, '''' pg5, '''' pg6, '''' pg7 FROM aAccountMaster AM,aGroupMaster GM,
	vwGlobalAccounts d WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = ''A'' OR
	GM.AccountType = ''L'') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID
	and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId	
	group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,
	GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, pg1, pg2, pg3,
	pg4, pg5, pg6, pg7, AccountID ORDER BY GrpAcId.AccountID
	Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,
	DepartmentId, CompanyId,
	case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from
	aaccountfinyearopening where
	Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where
	opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId
	and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId
	Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''A''
	Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,
	#TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and
	h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and
	h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,
	v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId and
	trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	and #BalSheet.AcType =''L''
	Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h
	where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId
	and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,
	v.DepartmentId, v.CompanyId,
	case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else
	Sum(isnull(v.DepAmount,0)) End Amount From
	#vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and
	h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and
	h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate
	group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where
	trialDeb.Accountid = #BalSheet.AccId and
	trialDeb.DepartmentId = #BalSheet.DepartmentId
	and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId
	set  @intCount = 0
SET @dblDebit = 0.0
SET @dblCredit = 0.0
		
if @intFinId > (Select max(financialid) from aAccountfinyearopening where
	   CompanyId = @intCOmpanyId )
Begin
	    select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId
	    and FinancialId = (Select max(financialid) from aAccountfinyearopening where
	    CompanyId = @intCOmpanyId )
	    select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 0 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	     and (accounttype =''e'' or accounttype =''i'') and h.financialid > 0
	    and d.departmentid IN (Select DeptId from #SubDepts1)
	    select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
	    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
	    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
	    and h.cancel =0 and journalcredit = 1 and
	    (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )
	    and (accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
	    and d.departmentid IN (Select DeptId from #SubDepts1)
	    if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0
		Begin
			Update #BalSheet set OBDr = isnull(OBDr,0) +
			(isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0
			where AccId = (Select RetainedEarningsAcc from aSettings where
			CompanyId = @intCompanyId)
		End		
		
End	
set @dblDebit = 0.0
set @dblCredit = 0.0
/*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId
and FinancialId = (Select max(financialid) from aAccountfinyearopening where
CompanyId = @intCompanyId ) */
select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'') and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end
from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g
where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid
and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and
(accounttype =''e'' or accounttype =''i'' )	and h.financialid > 0
and d.departmentid IN (Select DeptId from #SubDepts1)
--SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b
--where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0
--order by b.parentgroupid
Insert #FilteredResult(groupid , AccountCode ,
		AccountDesc , groupdesc , parentGroupid ,
			orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)
exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,
	OBCr, DebitAmt, CreditAmt, AccId, DepartmentId, orderno, levelcode, Checked,
	ProfitLoss, ParentGroupId)
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,
	b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.DepartmentId, r.OrderNo, r.LevelCode,
	0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r
left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null)
or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))
where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0)) <> 0 and
isnull(AcType,'''') =''A'') or ((isnull(obdr,0) + isnull(obcr,0) + isnull(creditamt,0)) -  isnull(debitamt,0)
<> 0 and isnull(AcType,'''') =''L'') and b.accCode is not null) or b.accCode is null)
and (r.AccType =''A'' or r.AccType =''L'' )
order by r.orderno
	set @GroupId = 0
-- TO avoid the groups which does not have any accounts information
	Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
	Order by OrderNo Desc
	While @GroupID <>0
	Begin
		set @intCount = 0
		Select @intCount = count(*) from #BalSheetFinal where
		((AcDesc is not Null and Groupid= @GroupID)
		 or ParentGroupid = @GroupID)
		if @intCount = 0
			Delete from #BalSheetFinal where GroupId = @GroupID
		else
			Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID
		Set @GroupID  = 0
		Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0
		Order by OrderNo Desc
	End
	Set @GroupID  = 0
	/*Select top 1 @GroupID = GroupId, @AcID = AccId, @intParentGroupID = ParentGroupId From
	#BalSheetFinal where levelCode > @intLevel and AccId is not null
	Order by OrderNo Desc
	While @GroupID <>0 and @intlevel <>0
	Begin
		set @intCount = 0
		set @intlgid = 0
		set @intlgpid = 0
		Select @intlgid = ParentGroupId,
		@intlgpid = levelCode, @strGroupName = GroupName from #BalSheetFinal where
		GroupId = @intParentGroupID
		While @intlgpid > @intLevel and @intlgid >0
		Begin
			Delete from #BalSheetFinal where GroupId = @intlgid
			set @intlgpid = 0
			Select @intlgid = isnull(ParentGroupId,0),
			@intlgpid = isnull(levelCode,0), @strGroupName = isnull(GroupName ,'''')
			from #BalSheetFinal where GroupId = @intlgid
		End
		if @intlgpid = @intLevel
		Begin
			Update #BalSheetFinal set GroupId =  @intlgid, GroupName = @strGroupName, 			
			LevelCode = @intLevel where
			GroupId = @GroupId and AccId = @AcID
			
			Delete from #BalSheetFinal where LevelCode = @intLevel
			and GroupId = @intlgid and AccId is null			
		End
		Set @GroupID  = 0
		Select top 1 @GroupID = GroupId, @AcID = AccId,  @intParentGroupID = ParentGroupId From
		#BalSheetFinal where levelCode > @intLevel and AccId is not null
		Order by OrderNo Desc
	End */
	Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null
Select * from #BalSheetFinal order by OrderNo
drop table #Tempjournalheader
drop table #vwJournalDetails
drop table #BalSheet
Drop table #BalSheetFinal
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spComplimentaryItemValue]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spComplimentaryItemValue]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author     :  <AADYAKUMAR.D.V>
-- Create date: <27/01/2012>
-- Comment    : This sp is used only for showing complementory items value in F&B(poshbilltype=''NP'')
-- =============================================
--spComplimentaryItemValue ''20120101'',''20120130'',1
CREATE PROCEDURE [dbo].[spComplimentaryItemValue]
@FromDate AS varchar(10),
@ToDate AS varchar(10),
@intShopid AS INT
AS
BEGIN
select fb_dd_dishcode ItemCode,fb_dd_dishname ItemDescription,sum(fb_pd_reusedqty) Quantity,avg(fb_pd_Actualrate) SellingPrice,
avg(fb_pd_Rate) SoldPrice,sum(fb_pd_reusedqty)*avg(fb_pd_Actualrate) Value
FROM Losposfandbheader H
INNER JOIN fb_processdetail D ON H.poshbillid=D.fb_pd_processid
AND H.poshShopID =D.fb_pd_outletid
AND H.poshCompanyID = D.fb_pd_companyid
AND poshbilltype=''NP''
INNER JOIN fb_dishdetails dishdetails ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid
WHERE CAST(LEFT(poshBillDate,11) AS DATETIME)>=@FromDate AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=@ToDate and H.poshShopID=@intShopid
GROUP BY fb_dd_dishcode,fb_dd_dishname
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAssetDetailsuptoDate]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssetDetailsuptoDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--spAssetDetailsuptoDate ''20040423'',0
-- created by    : 20/02/2004
-- Modified by   : Hariharan
-- comments	 : For gettng asset details
-- modified by Venkitesh on 130403 For accc id correction and company curr
CREATE Proc [dbo].[spAssetDetailsuptoDate] (
			    @dtdate as varchar(10),
			    @intdepartmentid as int = 0)			
as
set nocount on
SET ANSI_WARNINGS OFF
begin
Declare
	@intdepid as int,
	@DispDate as Datetime,
	@Assetid as int,
	@Deprecitamt as numeric(18,2),
	@costprice as numeric(18,2),
	@ctrtodept as int,
	@ctrtoacc as int,
	@accid as int,
	@numInitialDepvalue as numeric(18,2),
	@CompExrate as numeric(18,2)
	--@dtdate as datetime
	--set @dtdate= convert(datetime,@dtdate,103)
	
	set @intdepid=@intdepartmentid
	--print @dtdate
set ansi_warnings off
set nocount off
Create table #tempAssetDetails(
	CompanyID int,
	AssetId	 int,
	AssetCode  varchar(50),
	AssetDesc  varchar(100),
	AssetDate  Datetime,
	AssetPurDt Datetime,
	AssetValue numeric(18,2),
	CurrDepid int,
	depreciationamt numeric(18,2)DEFAULT Null, -- Null as default because if costvalue <=deprreciationvalue should be as null
	disposalDate datetime Default null, -- Null as default we r storing the disposed date
	TotalNoofDeptTrans int default Null,
	TotalNoofAccTrans int Default Null,
	Lastaccid int Default Null,
	LastAccountDesc Varchar(100) Default Null,
	CompExRate numeric(18,2))
	
	
		/*if   @intdepid>0  	
			Insert into #tempAssetDetails
			 select CompanyID,FixedAssetID,assetcode,
			 assetname,FixedAssetDate,PurchaseDate,CostPrice,CurrentDepartmentId,
			 initialDepreciatedValue,null,null,null,null,null  from
			 fixedasset where cancelled=0  and CurrentDepartmentId=@intdepid
			and FixedAssetDate <= @dtdate --and  CurrentDepartmentId=@intdepid
		else
			Insert into #tempAssetDetails
			select CompanyID,FixedAssetID,assetcode,
			assetname,FixedAssetDate,PurchaseDate,CostPrice,CurrentDepartmentId,
			initialDepreciatedValue,null,null,null,null,null  from
			fixedasset where cancelled=0
			and FixedAssetDate <= @dtdate */
		Insert into #tempAssetDetails
		select CompanyID,FixedAssetID,assetcode,
		assetname,FixedAssetDate,PurchaseDate,CostPrice,CurrentDepartmentId,
		Null,null,null,null,null,null,exrate  from
		fixedasset where cancelled=0
		and FixedAssetDate <= @dtdate
-- Deprecication
	
	declare DepriCurr cursor for
	select dd.fixedassetid,sum(depreciationamount)depreciamount,sum(costprice),
	sum(initialDepreciatedValue),max(consexrate) from
	depreciationheader dh,depreciationdetail dd,
	Fixedasset Fa where dh.companyid=dd.companyid and dd.depreciationid=dh.depreciationid
	and dd.fixedassetid=fa.fixedassetid  and dd.companyid=fa.companyid
	and dh.cancelled=0 and fa.cancelled=0 and DepreciationDate<=@dtdate
	group by dd.fixedassetid having
	sum(fa.costprice) >= sum(depreciationamount)
OPEN DepriCurr
	FETCH NEXT FROM DepriCurr INTO @Assetid, @Deprecitamt, @costprice, @numInitialDepvalue,@CompExrate
		update #tempAssetDetails  set depreciationamt = @Deprecitamt,CompExRate=@CompExrate
		where AssetId=@Assetid
	WHILE @@FETCH_STATUS = 0
		begin
			update #tempAssetDetails  set
			depreciationamt =  isnull(depreciationamt,0) + @Deprecitamt +
			@numInitialDepvalue,CompExRate=@CompExrate
			where AssetId=@Assetid
			FETCH NEXT FROM DepriCurr INTO @Assetid, @Deprecitamt,@costprice,
			@numInitialDepvalue,@CompExrate
		end
	
CLOSE DepriCurr
DEALLOCATE DepriCurr
-- Disposal date
		update #tempAssetDetails  set disposalDate=disphdate
		from assetdisposalheader adh,assetdisposaldetail adde
		inner join #TempAssetDetails Fa on
		adde.dispdasstid=fa.assetid and adde.dispdcompanyid= fa.companyid
		where adh.disphcompanyid=adde.dispdcompanyid and
		adh.disphid=adde.dispID and disphdate<=@dtdate
		and adh.disphcancelled=0
-- Asset Transfer
declare AssetTranCur cursor for
	select asttransassetid,count(asttranstodepid)ctrTodept,
	count(ToAssetAccID)CtrToaccid,max(consexrate) from
	assettransfer atr,Fixedasset fa
	where fa.companyid=atr.asttranscompanyid
	and fa.fixedassetid=atr.asttransassetid and atr.asttranscompanyid=fa.companyid
	and fa.cancelled=0 and atr.asttranscancelled=0 and asttransdate<= @dtdate
	group by asttransassetid,asttranscompanyid
	-- having clause  given opposite of actual condition for avoiding less count records
	-- if dept value > then cost price it will update else default value null will be stored
	-- on last fetching time we will take only the null value
OPEN AssetTranCur
	FETCH NEXT FROM AssetTrancur INTO @Assetid, @ctrtodept,@ctrtoacc, @CompExrate
		update #tempAssetDetails  set TotalNoofDeptTrans = @ctrtodept,
		TotalNoofAccTrans = @ctrtoacc,CompExRate=@CompExrate
		where AssetId=@Assetid
	WHILE @@FETCH_STATUS = 0
		begin			
			update #tempAssetDetails  set TotalNoofDeptTrans = @ctrtodept,
			TotalNoofAccTrans = @ctrtoacc,CompExRate=@CompExrate
			where AssetId=@Assetid
			FETCH NEXT FROM AssetTrancur INTO @Assetid, @ctrtodept,@ctrtoacc ,@CompExrate
		end
	
CLOSE AssetTranCur
DEALLOCATE AssetTranCur
--------- For getting latest
/*eclare AssetTranCur cursor for
	select asttransassetid, MAX(ToAssetAccID) accid from
	assettransfer atr, Fixedasset fa
	where fa.companyid=atr.asttranscompanyid
	and fa.fixedassetid=atr.asttransassetid and atr.asttranscompanyid=fa.companyid
	and fa.cancelled=0 and atr.asttranscancelled=0 and
	asttransid in (select max(asttransid)from  assettransfer where asttranscancelled=0
	and ToAssetAccID is not null and assettransfer.asttransassetid = fa.FixedAssetID and
	assettransfer.asttranscompanyid = fa.CompanyID and asttransdate<= @dtdate
	group by asttransassetid ) group by asttransassetid*/
	--FixedAssetId, isnull(MAX(ToAssetAccID), FixedAssetAccId) accid
	Update #tempAssetDetails set Lastaccid = astr.accid
	from (Select isnull(MAX(ToAssetAccID), min(FixedAssetAccId)) accid,
	min(Companyid) CompanyId, FixedAssetID  from
	Fixedasset fa , assettransfer atr where
	 fa.companyid=atr.asttranscompanyid
	and fa.fixedassetid=atr.asttransassetid and atr.asttranscompanyid=fa.companyid
	and fa.cancelled=0 and 0 = atr.asttranscancelled  and
	asttransid in (select max(asttransid)from  assettransfer where asttranscancelled=0
	and ToAssetAccID is not null and assettransfer.asttransassetid = fa.FixedAssetID and
	assettransfer.asttranscompanyid = fa.CompanyID and asttransdate<= @dtdate
	group by FixedAssetID ) group by FixedAssetID) astr where
	astr.FixedAssetId = #tempAssetDetails.AssetId and astr.CompanyId  =
	#tempAssetDetails.CompanyID
	Update #tempAssetDetails set CurrDepid = astr.CurrDepId
	from (Select isnull(MAX(asttranstodepid), min(DepartmentID)) CurrDepId,
	min(Companyid) CompanyId, FixedAssetID  from
	Fixedasset fa , assettransfer atr where fa.companyid=atr.asttranscompanyid and
	fa.fixedassetid=atr.asttransassetid and atr.asttranscompanyid=fa.companyid and
	fa.cancelled=0 and 0 = atr.asttranscancelled
	and asttransid in (select max(asttransid)from assettransfer where asttranscancelled=0
	and ToAssetAccID is null and FromAssetAccID is null and assettransfer.asttransassetid
	= fa.FixedAssetID and assettransfer.asttranscompanyid = fa.CompanyID and
	asttransdate<= @dtdate group by FixedAssetID ) group by FixedAssetID) astr where
	astr.FixedAssetId = #tempAssetDetails.AssetId and astr.CompanyId  =
	#tempAssetDetails.CompanyID
/*OPEN AssetTranCur
	FETCH NEXT FROM AssetTrancur INTO @Assetid, @accid
		update #tempAssetDetails  set Lastaccid = @accid
		where AssetId=@Assetid
	WHILE @@FETCH_STATUS = 0
		begin
			update #tempAssetDetails  set Lastaccid =@accid
			where AssetId=@Assetid
			FETCH NEXT FROM AssetTrancur INTO @Assetid, @accid
		end
	
	CLOSE AssetTranCur
	DEALLOCATE AssetTranCur */
	update #tempAssetDetails set Lastaccid=FixedAssetAccID
	from fixedasset inner join #tempAssetDetails on
	FixedAssetID=assetid and  Lastaccid is  null
	update #tempAssetDetails  set LastAccountDesc= AccountDesc
	from aaccountmaster inner join #tempAssetDetails on
	Lastaccid=AccountID  and  Lastaccid is not null
set nocount on
set ansi_warnings on
IF @intdepartmentid = 0
select * from  #tempAssetDetails  where disposalDate is null
else
select * from  #tempAssetDetails  where disposalDate is null and CurrDepid = @intdepartmentid
drop table  #TempassetDetails
end
SET ANSI_WARNINGS on
set nocount off' 
END
GO
/****** Object:  View [dbo].[vwchartofaccounts]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwchartofaccounts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwchartofaccounts    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwchartofaccounts] as
select am.companyid, accountid, accountcode, accountdesc,case when gm.accounttype =''A'' then
''Asset'' when gm.accounttype=''L'' then ''Liability'' when gm.accounttype=''I'' then ''Income''
when.gm.accounttype=''E'' then ''Expense'' end Type, levelgm, 0.0 as opening, da.dadepartmentid
from agroupmaster gm, vwgroupmasterwithlevel gml, aaccountmaster am left outer
join  aDeptAccounts da on am.companyid = da.dacompanyid and am.accountid = da.daaccountid
where am.groupid = gm.groupid and gm.groupid = gml.groupid'
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsInvoiceFullyDelivered]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_IsInvoiceFullyDelivered]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:		Regin T.
-- Create date: 10-08-2010
-- Description:	
--   Input:
--     1. Company Id (Not in use now, but to support multiple companies enhancement)
--     2. Shop Id
--     3. Invoice Id
--   Output:
--     Returns TRUE if items are already fully delivered,
--	   FALSE otherwise.
-- =============================================================================
-- Code to execute this procedure:
/*
DECLARE @FullyDelivered BIT
EXEC spMag_IsInvoiceFullyDelivered 1, 1, 17, @FullyDelivered output
PRINT @FullyDelivered
*/
-- =============================================================================
CREATE PROC [dbo].[spMag_IsInvoiceFullyDelivered]
@CompanyId AS INT
, @ShopId AS INT
, @InvoiceId AS INT
	, @FullyDelivered AS BIT = NULL OUTPUT
AS
BEGIN
	DECLARE @PendingQty	NUMERIC(18,3)
	SET NOCOUNT ON;
	-- Create a temporary table to store the output
	-- of spMag_FetchCreditSaleDeliveryDetails
	CREATE TABLE #tblCreditSaleDeliveryDetails
	(
		ShopId INT
		, InvoiceId INT
			, InvoiceNo VARCHAR(50)
			, InvoiceDate DATETIME
		, CustomerId INT
		, CustomerName VARCHAR(100)
			, ItemId INT
			, ItemCode VARCHAR(50)
		, ItemDescription VARCHAR(200)
		, PackId INT
			, PackingTypeName VARCHAR(100)
			, PackingBarCode VARCHAR(50)
		, InvoicedPackQty NUMERIC(18,3)
		, InvoicedQty NUMERIC(18,3)
			, DeliveredPackQty NUMERIC(18,3)
			, DeliveredQty NUMERIC(18,3)
	)
	-- Execute spMag_FetchCreditSaleDeliveryDetails and
	-- save the output into the temporary table.
	INSERT INTO #tblCreditSaleDeliveryDetails
	EXEC spMag_FetchCreditSaleDeliveryDetails
		@CompanyId, @ShopId, @InvoiceId
	-- Check if all items fully delivered already.
	SELECT @PendingQty=ISNULL(SUM(InvoicedPackQty-DeliveredPackQty),0)
	FROM #tblCreditSaleDeliveryDetails
	IF @PendingQty <= 0
		SET @FullyDelivered = 1
	ELSE
		SET @FullyDelivered = 0
	-- Give output
	SELECT @FullyDelivered FullyDelivered
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsBillFullyDelivered]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_IsBillFullyDelivered]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================================================
-- Author:		Regin T.
-- Create date: 10-08-2010
-- Description:	
--   Input:
--     1. Company Id (Not in use now, but to support multiple companies enhancement)
--     2. Shop Id
--     3. Invoice Id
--   Output:
--     Returns TRUE if items are already fully delivered,
--	   FALSE otherwise.
-- =============================================================================
-- Code to execute this procedure:
/*
DECLARE @FullyDelivered BIT
EXEC spMag_IsBillFullyDelivered 1, 1, 17, @FullyDelivered output
PRINT @FullyDelivered
*/
-- =============================================================================
CREATE PROC [dbo].[spMag_IsBillFullyDelivered]
@CompanyId AS INT
, @ShopId AS INT
, @BillId AS INT
	, @FullyDelivered AS BIT = NULL OUTPUT
AS
BEGIN
	DECLARE @PendingQty	NUMERIC(18,3)
	SET NOCOUNT ON;
	-- Create a temporary table to store the output
	-- of spMag_FetchCashSaleDeliveryDetails
	CREATE TABLE #tblCashSaleDeliveryDetails
	(
		ShopId INT
		, BillId INT
			, BillNo VARCHAR(50)
			, BillDate DATETIME
		, CustomerId INT
		, CustomerName VARCHAR(100)
			, ItemId INT
			, ItemCode VARCHAR(50)
		, ItemDescription VARCHAR(200)
		, PackId INT
			, PackingTypeName VARCHAR(100)
			, PackingBarCode VARCHAR(50)
		, BilledPackQty NUMERIC(18,3)
		, BilledQty NUMERIC(18,3)
			, DeliveredPackQty NUMERIC(18,3)
			, DeliveredQty NUMERIC(18,3)
	)
	-- Execute spMag_FetchCashSaleDeliveryDetails and
	-- save the output into the temporary table.
	INSERT INTO #tblCashSaleDeliveryDetails
	EXEC spMag_FetchCashSaleDeliveryDetails
		@CompanyId, @ShopId, @BillId
	-- Check if all items fully delivered already.
	SELECT @PendingQty=ISNULL(SUM(BilledPackQty-DeliveredPackQty),0)
	FROM #tblCashSaleDeliveryDetails
	IF @PendingQty <= 0
		SET @FullyDelivered = 1
	ELSE
		SET @FullyDelivered = 0
	-- Give output
	SELECT @FullyDelivered FullyDelivered
END' 
END
GO
/****** Object:  View [dbo].[vwGodownLocationWiseStock]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownLocationWiseStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By       : Hariharan
-- Created Date     : 24/12/2002
------------------------------------------------
-- last modifed by  : Kishore
-- Last modified on : 24/04/2003
-- description      : add location id ,godownid (by dheena)
--                    Added ''Cancel = 0'' condition (24/04/2003)
---------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwGodownLocationWiseStock] AS
select godownname,ladgodownid, laditemid, ItemDescription, Code, lLocationName, LgGroupName,
sum(Stock ) Stock,llocationid from
(select godownname, ladgodownid, laditemid, ItemDescription, Code, lLocationName, LgGroupName,
laditemqty Stock,li.llocationid from loilocationarrivaldetails ad,
vwitemdescription vw, loilocation li, loilocationgroup lg, agodown
where ad.laditemid = vw.itemid and ladlocationid = li.llocationid
and ladgodownid = li.lgodownid and lgroupid = Lggroupid and lcompanyid = Lgcompanyid
and lGodownid = lggodownid  and lgodownid = godownid and lcompanyid = companyid
and ad.ladCancel = 0
union all
select  godownname, lidgodownid,liditemid, ItemDescription, Code, lLocationName, LgGroupName,
-liditemqty Stock,llocationid from loilocationIssuedetails ad,
vwitemdescription vw, loilocation li, loilocationgroup lg, agodown
where ad.liditemid = vw.itemid and lidlocationid = li.llocationid
and lidgodownid = li.lgodownid and lgroupid = Lggroupid and lcompanyid = Lgcompanyid
and lGodownid = lggodownid and lgodownid = godownid and lcompanyid = companyid
and ad.lidCancel = 0) locstock
group by godownname, ladgodownid, LgGroupName, itemDescription, laditemid, Code, llocationname,llocationid'
GO
/****** Object:  View [dbo].[vwgodownlocationstock]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownlocationstock]'))
EXEC dbo.sp_executesql @statement = N'
--Created on 	: 22/02/03
--Created by 	: leo
CREATE view [dbo].[vwgodownlocationstock] as
select ladgodownid, ladlocationid, laditemid, sum(quantity) stock from
(select ladgodownid, ladlocationid, laditemid, sum(laditemqty) quantity from loilocationarrivaldetails where
ladcancel = 0 group by ladgodownid, ladlocationid, laditemid
union all
select lidgodownid, lidlocationid, liditemid, - sum(liditemqty) quantity  from loilocationissuedetails where
lidcancel = 0 group by lidgodownid, lidlocationid, liditemid) s group by ladgodownid, ladlocationid, laditemid'
GO
/****** Object:  View [dbo].[vwExchangeSales]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwExchangeSales]'))
EXEC dbo.sp_executesql @statement = N'
/*
--Last Modified on  : 18/05/2004
--Modified by  : Hariharan
-- Comments  : Added sedFreeQty, sedExcFreeQty columns on 14/10/2003
--   : itemcode and packingtype code added
-- Modified By : Shine Das
-- On : 29-08-2011
-- Purpose: To bring warranty dates in this view.
----------------------------------------------------------------------------------
-- RefNo :01
--Modified by : Aadyakumar.D.V
--Modified on : 01-10-2011
--Comments    : Added CUSTOMERTIN  column
-----------------------------------------------------------
-- RefNo : 02
-- Modified By : Shine Das
-- On : 03-01-2012
-- Unwanted comment avoided
----------------------------------------------------------------------------------
*/
CREATE VIEW [dbo].[vwExchangeSales] AS
select vw.itemdescription, h.sehexchangeid, h.sehexchangeNo,
h.sehShopid, h.sehexchangedate,
seditemid, sedquantity, sedpquantity, sedunitprice, sedactualunitprice, sedcostprice,
UnitName, packingtypename, accountdesc,Symbol, h.sehremarks,
sedexchangeqty, sedexchangepqty,  sedbillorexchange,
case poshbillno when null then dh.sehexchangeno else poshbillno end exchangebillno ,
case poshbillno when null then dh.sehexchangedate else poshBillDate end exchangebilldate,
h.sehdepexrate, h.sehexchangerate,h.sehcancelled, sedFreeQty, sedExcFreeQty, UnitCode, ItemCode,
PackingTypeCode,SedServWarrantyUpto,SedPartsWarrantyUpto ,sedItemTaxPercentage,sedItemTaxAmount ,CUSTOMERTIN  -- RefNo :01
from losposexchangeheader h left outer join losposheader ph
on h.sehbillid =ph.poshbillid and h.sehshopid= ph. poshshopid
left outer join acustomermaster acu on acu.CustomerID=ph.poshcustomerid
left outer join losposexchangeheader dh on h.sehexchangeid  = dh.sehExchangedBillID and
h.sehshopid = dh.sehshopid,
losposexchangedetail, aitem a, apackingtype p, vwitemdescription vw, aunit u, aaccountmaster ac,
acurrencymaster c
where h.sehShopid= sedShopid and h.sehexchangeid = sedexchangeid and
sedpackingtypeid=p.packingtypeid and seditemid=a.itemid and a.itemid=vw.itemid and
u.unitid=a.unitsid  and ac.accountid =h. sehCashAccID and ac.currencyid=c.currencyid
and (sedbillorexchange = ''E'' or sedexchangeqty<>0)      -- RefNo : 02
--and  h.sehexchangeid=14 and h.sehshopid=1'
GO
/****** Object:  View [dbo].[vwediPO]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwediPO]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwediPO    Script Date: 18/01/2003 9:45:36 PM ******/
/* created  by  : dheena
created date : 021127
description  : collect edi approved po only */
CREATE view [dbo].[vwediPO] as
select ecshopid,ecconfirmid,ecconfirmno,erpoid
from losEDIRequest,losEDIConfirmation
where ershopid=ershopid and ecediid=erediid and ecstatus=''s''
and eccancelled=0 and ercancelled =0'
GO
/****** Object:  View [dbo].[vwGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownTotalStockVerification]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by : Kishore
-- Created in : 27/09/2003
-- Comments   : View for printing report vwGodownTotalStockVerification
--              Created to use in report - rptGodownTotalStockVerification
--              Taken from v2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwGodownTotalStockVerification] AS
--
SELECT h.svhId, h.svhGodownid, svhNo, svhDate, svhVerificationBy,
svhCancelled, svhRemarks, svdItemId, svdAvailStock AvailableStock,
svdVerifiedBadStock VerifiedStock, svdVerifiedStock ActualVerifiedStock,
svdAvailBadStock AddedByUser, i.ItemCode, vw.ItemDescription, u.UnitCode,
svdCostPrice * svdVerifiedStock StockValue,
CASE SUBSTRING(svhFutureVc, 2, 1)
	WHEN ''n'' THEN ''No''
	WHEN ''c'' THEN ''Yes''
END Confirmed
FROM loiStockVerificationHeader h, loiStockVerificationDetail d,
aItem i, aUnit u, vwItemDescription vw
WHERE h.svhId = d.svdId
AND h.svhGodownId = d.svdGodownId
AND d.svdItemId = i.ItemId
AND i.ItemId = vw.ItemId
AND i.UnitsId = u.UnitId
AND LEFT(svhFutureVc, 1) = ''T''
AND svhCancelled = 0'
GO
/****** Object:  View [dbo].[vwGodownToGodownTransfer]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownToGodownTransfer]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on 	: 12/12/02
-- Modified by		: leo
-- Comments		: v3
--------------------------------------------------------------------------------------------
-- Modified by		: Kishore
-- Modified on		: 13/06/2003
-- Comments		: view corrected for the problem of wrong items in the preview
--			  (On comparison with v2)
--------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwGodownToGodownTransfer] AS
select gth.gthremarks,agfrom.godownname fromgodown,
agto.godownname togodown,gth.gthdespatchno,
gth.gthdespatchdate, gth.gthcarrier,gth.gthvehicleno,
vwit.itemdescription,aitp.packingbarcode barcode,
sum(gtd.gtditemgoodqty) gtditemgoodqty, au.unitname,gtd.gtditemid, gthfromgodownid,
gthtogodownid, gthdespatchid, unitcode
from meigodowntransferheader gth
left outer join meigodowntransferdetail gtd on gth.gthdespatchid=gtd.gtddespatchid
and gth.GthFromgodownid = gtd.gtdGodownid
left outer join agodown agfrom on agfrom.godownid = gth.gthfromgodownid
left outer join aitem  ait on ait.itemid = gtd.gtditemid
left outer join aitempackingdetail  aitp on ait.itemid = aitp.itemid
left outer join aunit au on ait.unitsid = au.unitid
left outer join agodown agto on agto.godownid = gth.gthtogodownid
left outer join vwitemdescription vwit on vwit.itemid = gtd.gtditemid, vwitemRetailPacking  vwitp
where ait.itemid = vwit.itemid
and aitp.itemid =vwitp.itemid
and aitp.packingtypeid = vwitp.packingtypeid
group by gthdespatchid, gthfromgodownid, gthtogodownid, vwit.itemdescription,
gtd.gtditemid, gth.gthremarks, agfrom.godownname,
agto.godownname,au.unitname, unitcode ,
gth.gthdespatchno, gth.gthdespatchdate, gth.gthcarrier,
gth.gthvehicleno, aitp.packingbarcode'
GO
/****** Object:  View [dbo].[vwGodownStockVerification]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownStockVerification]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGodownStockVerification    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--modified by: Benzigar S D
--Modified n : 18/08/2009
--Comment    : Added svdcostprice
CREATE view [dbo].[vwGodownStockVerification] as
select svhGodownid, svhid, svhNo, svhDate, svhVerificationby, svhRemarks, svditemid,
ItemDescription, sum(svdAvailStock) as BeforeVerify, sum(svdVerifiedStock) as AfterVerify,
sum(svdavailbadstock) svdavailbadstock, sum(svdVerifiedBadStock) svdVerifiedBadStock,svdcostprice
from loistockverificationheader, loistockverificationdetail, vwitemdescription
where svhGodownid = svdGodownID and svhid = svdid and svdItemID = ItemID
group by svhGodownid, svhid, svhNo, svhDate, svhVerificationby, svhRemarks, svditemid,
ItemDescription,svdcostprice'
GO
/****** Object:  View [dbo].[vwDespatchArrivalDiff]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchArrivalDiff]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwDespatchArrivalDiff    Script Date: 18/01/2003 9:45:36 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--------------------------------------------------------------------------------------
--Ref.No:1
--Modified By:AADYA KUMAR.D.V
--Modification:Added ahremarks,dh.updatetime despatchdate in this view
--Reason:As per Ticket:ASV-882601
--------------------------------------------------------------------------------------
CREATE view [dbo].[vwDespatchArrivalDiff] as
select
dhdespatchnoteno,ah.aharrivalno,ah.aharrivaldate,ah.ahlocalgodownid,
s.sshipmentno, ad.aditemid,vi.itemdescription,ad.addespatchedqty,ad.adreceivedqty,vi.code,
ahremarks,dh.updatetime despatchdate  --Ref.No:1
from loiarrivalheader ah,loiarrivaldetail ad
,ahqdespatchnoteheader dh, ashipment s,vwitemdescription vi
where ah.AHARRIVALID=AD.ADARRIVALID AND ah.ahlocalgodownid=ad.adgodownid
and ah.ahDespatchNoteID=dh.dhdespatchnoteid and ah.ahlocalgodownid=dh.dhGodownid and
ad.adDespatchedQty <> ad.adReceivedQty and ah.ahshipmentid=s.sshipmentid and
ad.aditemid=vi.itemid and ah.ahcancelled=0 and ah.ahtransfinished=1'
GO
/****** Object:  View [dbo].[vwDiscountGiven]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDiscountGiven]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------------
--Created by : Shinu
--Created on : 07/03/2008
------------------------------------------------------------------------------------------------------------------------
--Modified by :
--Modified on :
------------------------------------------------------------------------------------------------------------------------
--Purpose   : To Get The Total Discount Given From POS and Invoices
------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwDiscountGiven] AS
SELECT poshShopID,poshBillID,poshBillno,poshBillDate,poshCustomerID,''POS'' as Type ,poshBillAmount,poshDiscount,
Sum(posdUnitPrice)Rate,sum(posdPQuantity*posdActualUnitPrice)ActualRate,poshCustomerName
FROM losposheader,losposdetail WHERE  poshShopID=posdShopID AND poshBillID=posdBillID and
poshCancelled=0
GROUP BY poshShopID,poshBillID,poshBillDate,poshBillNo,poshBillAmount,
poshDiscount,poshCustomerID,poshCustomerName
Union All
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Invoice'',ihInvoiceAmount,ihDiscount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice ,''''
FROM losinvoiceheader,losinvoicedetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 And ihType=''I''
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihDiscount,ihCustomerID
/*
UNION ALL
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Purchase Order'',ihInvoiceAmount,ihDiscount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice,''''
FROM losinvoiceheader,losinvoicedetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 And ihType=''P''
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihDiscount,ihCustomerID
*/
UNION ALL
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Quotation'',ihInvoiceAmount,ihDiscount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice ,''''
FROM losinvoiceheader,losinvoicedetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 And ihType=''Q''
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihDiscount,ihCustomerID
UNION ALL
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Direct Invocie -Cash'',ihInvoiceAmount,
case sum(idPQuantity*idActualUnitPrice) when 0 then 0 else
((sum(idPQuantity*idActualUnitPrice)-sum(idUnitPrice))/sum(idPQuantity*idActualUnitPrice)) *100 end Discount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice ,''''
FROM losSpecialInvoiceHeader,losSpecialInvoicedetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 And ihCashInvoice=1 and (select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId and idratetype = 1) = 0 and IhTransFinished=1
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihCustomerID
UNION ALL
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Direct Invocie -Credit'',ihInvoiceAmount,
case sum(idPQuantity*idActualUnitPrice) when 0 then 0 else
((sum(idPQuantity*idActualUnitPrice)-sum(idUnitPrice))/sum(idPQuantity*idActualUnitPrice)) *100 end Discount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice ,''''
FROM losSpecialInvoiceHeader,losSpecialInvoicedetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 And ihCashInvoice=0 and (select count(*) from losspecialinvoicedetail d
where ihinvoiceid = d.idinvoiceid and ihShopId = d.idShopId and idratetype = 1) = 0 and IhTransFinished=1
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihCustomerID
UNION ALL
select ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihCustomerID,''Direct Invocie -Quotation'',ihInvoiceAmount,
case sum(idPQuantity*idActualUnitPrice) when 0 then 0 else
((sum(idPQuantity*idActualUnitPrice)-sum(idUnitPrice))/sum(idPQuantity*idActualUnitPrice)) *100 end Discount,
sum(idUnitPrice)Rate,sum(idPQuantity*idActualUnitPrice)ActualPrice ,''''
FROM losSIQuotationHeader,losSIQuotationDetail WHERE  ihShopID=idShopID AND ihInvoiceID=idInvoiceID
and ihCancelled=0 --and IhTransFinished=1
Group By ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ihInvoiceAmount,ihCustomerID'
GO
/****** Object:  View [dbo].[vwDailyCounterSales]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailyCounterSales]'))
EXEC dbo.sp_executesql @statement = N'
--Created By Aneesh
--Purpose - For populating Counterwise Reports
--modified by Shinu 25/04/07
--purpose - added goods exchange
--modified by Shinu 25/04/07
--purpose - added goods exchange
CREATE  View [dbo].[vwDailyCounterSales] as
Select poshbillid as Billid,poshbillno as BillNo,poshshopid As shopid, poshbilldate As billdate,
updatetime as BillingTime,poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid,poshcounterid counterid,ph.poshuserid
From  losposheader ph,losposdetail pd   Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
Group By poshbillno , poshshopid , poshbilldate ,updatetime,poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,ph.poshcounterid,ph.poshuserid
union all
select sehexchangeid as Billid ,sehExchangeNo as BillNo,sehShopID,sehExchangeDate As billdate,seh.updatetime as BillingTime, sehCashaccid As accountid
,vw.NewExAmount  As amount ,  COnvert(numeric(18,2),(vw.NewExAmount*sehdepexrate))  As damount, COnvert(numeric(18,2),(vw.NewExAmount*sehexchangerate),2) As camount,1 As cAsh, ''E'' As transtype,
sehdepartmentid  as departmentid,poshcounterid counterid,lo.userid
from losposExchangeheader seh , losposheader ph ,lousers lo,
(select sedShopID,sedExchangeID ,sum(ExAmount)-sum(BillAmount) As NewExAmount from
(select sedShopID ,sedExchangeID,case when sedBillorExchange=''B'' then Sum( sedunitprice) else 0  end  BillAmount ,
case when sedBillorExchange=''E'' then Sum( sedunitprice) else 0  end  ExAmount   from losposexchangedetail group by sedShopID ,sedExchangeID,sedBillorExchange)v1
group by sedShopID,sedExchangeID )vw
where seh.sehcancelled=0  and seh.sehexchangeid =vw.sedExchangeID  and seh.sehshopid=vw.sedShopID  and  seh.sehshopid = ph.poshshopid  and
seh.sehbillid= ph.poshbillid and seh.sehrecadduser=lo.username and  lo.shopid=seh.sehshopid'
GO
/****** Object:  View [dbo].[vwCashInvoices]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCashInvoices]'))
EXEC dbo.sp_executesql @statement = N'
--Created by  : Hariharan R
--Created Date  : 03/05/2004
--Comments  : Created to incorporate cash invoices in Sales Commission related Objects
----------------------------------------------------------------------------------------
--Ref.No.1
--Modified on :29-02-2012
--Modified by :AADYA KUMAR.D.V
--Ticket id   :FGY-413407
--Comment     :Added new column TaxAmount
----------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCashInvoices] as
--1. Accounts Invoice
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 ,
''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,
isnull(TaxAmount,0) TaxAmount --Ref.No.1
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 = 1 and AIH.Proforma = 0 and
AIH.Cancelled = 0
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,
TaxAmount  --Ref.No.1
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, ''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,
isnull(aiTaxAmount,0) TaxAmount --Ref.No.1
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 = 1 and
AIH.aiProforma = 0 and AIH.aiCancelled = 0
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,
convert(int, isnull(aiCashPaidByShop,0)),
aiTaxAmount  --Ref.No.1
having
sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0
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, ''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,
sum(isnull(idItemTaxAmount,0)) TaxAmount --Ref.No.1
FROM
ashops s, acustomermaster c, losSpecialInvoiceHeader IH
Left outer join losSpecialInvoiceDetail SID
on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid
WHERE
s.shopid = ih.ihshopid and s.accountable is not null and
ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 1 and IH.ihProforma = 0 and
IH.ihCancelled = 0 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
union all
--5. Shop Booking Invoice
SELECT
IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,
IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''''), ih.remarks, serinvhamount,
''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,
isnull(serinvhTaxamount,0) TaxAmount  --Ref.No.1
FROM
ashops s, acustomermaster c,  vwbookingservinvoices IH
where
s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid
UNION ALL
--6.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, ''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,
0.0 TaxAmount --Ref.No.1
FROM
losApartmentBillHeader abh, acustomermaster c
WHERE
abh.abhCustomerID=c.customerID and abh.abhCashAccId is NOT null and
abh.abhCancelled=0 and
isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0
UNION ALL
--7.Room Billing 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, ''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,
0.0 TaxAmount  --Ref.No.1
FROM
losTenantServiceBillHeader tbh, acustomermaster c
WHERE
tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is NOT null and
tbh.tbhCancelled=0 and isnull(tbh.tbhAmount,0) >0.0
union all
--8.Tenant Billing
SELECT
IH.poshCompanyID, ih.poshshopid, IH.poshDepartmentID, IH.poshBillid, IH.poshcustomerid,
IH.poshBilldate,  iH.poshBillNo, '''' referenceno,
ih.poshCancelledremarks, sum(posdUnitPrice) as InvAmt, ''PDI'' as type,
''Trade Debtors'' Debtortype, ih.updatetime,
customercategory, NULL duedate,avg(ih.poshdepexrate) as depExRate,
5008 interfaceID,ih.poshsalespersonid SalesPersonID,c.CustomerType,0.0 DutyAmt,
sum(isnull(posdQuantity*posdcostprice,0)) CostPrice,
sum(isnull(posdItemTaxAmount,0)) TaxAmount  --Ref.No.1
FROM
ashops s, acustomermaster c, losPosHeader IH
Left outer join losPosDetail SID
on IH.poshBillID = SID.posdBillID and ih.poshshopid=sid.posdshopid
WHERE
s.shopid = ih.poshshopid and s.accountable is not null and
ih.poshcustomerid = c.customerid and IH.poshCancelled = 0
GROUP BY
IH.poshCompanyID, IH.poshSHOPID, IH.poshBillid, IH.poshcustomerid, IH.poshBilldate,
ih.updatetime, iH.poshBillNo, ih.poshCancelledRemarks,
IH.poshDepartmentID, IH.poshDiscount, customercategory, ih.poshsalespersonid,
c.CustomerType'
GO
/****** Object:  View [dbo].[vwCustomerSalesQtyWise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesQtyWise]'))
EXEC dbo.sp_executesql @statement = N'
/*
--Created By : Hariharan
--Created Date : 14/11/2003
--For customer qty wise sales in bonded
--modified Date : 18/12/2003
--modified date 25/02/04 by renjith added company value and departmentsalesvalue
--for specialinvoice ihtransfinished chking
---- added goods return also on venkitesh 150404
--------------------------------------------------------------------------------
-- Modified By: Regin
-- Modified On: 22-09-2009
-- Modification:
-- Added Type field
-- Added - sign for Exchanged In type since items are returned by the customer.
-- Cash Sales, Exchanged Out, Exchanged In parts got modified to include all trans
--    even though no respective customer found.
--    (left outer join used with aCustomerMaster).
-- Purpose:
-- To show Cash Sale Value separately in Customer Sales Itemwise report.
--------------------------------------------------------------------------------
-- Modified By: jyothish
-- Modified On: 23-09-2009
-- Modification:
-- Added Type field
-- Added - add  new filed salespersonid
select * from vwCustomerSalesQtyWise where ihinvoicedate= ''20100419'' and ihCustomerId=316
------------------------------------------------------------------------------------------
Modified By : Shine Das
On : 08-07-2010
Purpose: In the case of Special Invoice it was taking quantity from field "idquantity". It was wrong,
So changed it as "idpquantity"
*/
CREATE   VIEW [dbo].[vwCustomerSalesQtyWise]
as
-- Credit Sales
select  ihcompanyid, ihshopid, ihinvoicedate,
ihCustomerId, ihdepartmentid,
convert(numeric(18, 2), sum(isnull(idquantity,0))) Quantity,
countryname, ihinvoiceno, Customername, ihReferenceNo, IdItemId,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName,  vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(isnull(idUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(isnull(idUnitPrice*ihexchangerate,0)))csalesvalue,
convert(numeric(18, 2),sum(isnull(idUnitPrice*ihdepexrate,0)))dsalesvalue,
''Credit Sales'' as Type ,isnull(ih.ihsalespersonid,0)salespersonid
from
losinvoiceheader ih
left outer join losinvoicedetail invd
on ih.ihshopid = invd.idshopid and ih.ihinvoiceid = invd.idinvoiceid,
acustomermaster c, acountrymaster cm , vwItemDescription v
where
ihcancelled=0 and ihproforma = 0 and
ihcustomerid=c.customerid and c.countryid = cm.countryid and ihtype =''i''
and iditemid = v.itemid
-- and year(ihInvoiceDate) = @intYear and ihShopId = @intShopId
group by
ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid,
ihCustomerId ,ihdepartmentid, countryname,
CustomerCardNo, Customername, ihReferenceNo, idItemId, v.ItemDescription, v.code,
v.vunitcode, v.vUnitName, vBrand, vitemCategoryid ,ih.ihsalespersonid
union all
-- Special Invoice
select
ihcompanyid, ihshopid, ihinvoicedate,
ihCustomerId, ihdepartmentid,
convert(numeric(18, 2), sum(isnull(idpquantity,0))) Quantity,
countryname, ihinvoiceno, Customername, ihReferenceNo, idItemid,
v.itemDescription, v.code,v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(isnull(idUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(isnull(idUnitPrice*ihexchangerate,0)))csalesvalue,
convert(numeric(18, 2),sum(isnull(idUnitPrice*ihdepexrate,0)))dsalesvalue,
''Special Invoice'' as Type ,isnull(ih.ihsalespersonid,0) as salespersonid
from
losSpecialinvoiceheader ih
left outer join losSpecialinvoicedetail invd
on ih.ihshopid = invd.idshopid and ih.ihinvoiceid = invd.idinvoiceid,
acustomermaster c, acountrymaster cm , vwItemDescription v
where
ihcancelled=0 and ihproforma = 0  and
ihcustomerid=c.customerid and c.countryid = cm.countryid
and idItemid = v.ItemId and ih.ihtransfinished=1
-- and year(ihInvoiceDate) = @intYear and ihShopId = @intShopId
group by
ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid,
ihCustomerId ,ihdepartmentid, countryname,
CustomerCardNo, Customername, ihReferenceNo, idItemId, v.ItemDescription, v.code,
v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,ih.ihsalespersonid
union all
-- Cash Sales
select  poshcompanyid, poshshopid, poshBilldate,
poshCustomerId, poshdepartmentid,
convert(numeric(18, 2), sum(isnull(posdquantity,0))) Quantity,
countryname, poshBillNo, isnull(poshCustomername,''CASH''), '''' blank, posdItemId,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(isnull(posdUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(isnull(posdUnitPrice*poshExchangeRate,0)))csalesvalue,
convert(numeric(18, 2),sum(isnull(posdUnitPrice*poshdepexrate,0)))dsalesvalue,
''Cash Sales'' as type1,isnull(ih.poshsalespersonid,0) as salespersonid
from
losPosHeader ih
left outer join losPosDetail invd
on ih.poshshopid = invd.posdshopid and ih.poshBillid = invd.posdBillid
left outer join acustomermaster c on poshcustomerid=c.customerid
left outer join acountrymaster cm on c.countryid = cm.countryid, vwItemDescription v
where
poshcancelled=0 and posditemid = v.itemid
group by
poshcompanyid, poshshopid, poshbillno, poshbilldate, poshBillid,
poshCustomerId ,poshdepartmentid, countryname,
CustomerCardNo, Customername, poshCustomername, posdItemId, v.ItemDescription, v.code,
v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,ih.poshsalespersonid
union all
-- Goods Exchanged Out
select  sehcompanyid, sehshopid, sehExchangedate,
poshCustomerId, sehdepartmentid,
convert(numeric(18, 2), sum(isnull(sedquantity,0))) Quantity,
countryname, sehExchangeNo, isnull(sehExchangerName,''CASH''), '''', sedItemId,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(isnull(sedUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(isnull(sedUnitPrice*sehExchangeRate,0)))csalesvalue,
convert(numeric(18, 2),sum(isnull(sedUnitPrice*sehdepexrate,0)))dsalesvalue,
''Exchanged Out'' as Type ,isnull(ih.sehsalespersonid,0) as salespersonid
from
losPosExchangeHeader ih
left outer join losPosExchangeDetail invd
on ih.sehshopid = invd.sedshopid and ih.sehexchangeid = invd.sedExchangeid
left outer join losPosHeader on sehBillId = poshBillid and sehShopId = poshShopID
left outer join acustomermaster c on poshcustomerid=c.customerid
left outer join acountrymaster cm on c.countryid = cm.countryid, vwItemDescription v
where
sehcancelled=0 and seditemid = v.itemid and sedbillorexchange = ''E''
-- and year(ihInvoiceDate) = @intYear and ihShopId = @intShopId
group by
sehcompanyid, sehshopid, sehExchangeNo, sehExchangeDate, sehExchangeid,
poshCustomerid, sehdepartmentid, countryname,
CustomerCardNo, Customername, sehExchangerName, sedItemId, v.ItemDescription, v.code,
v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,ih.sehsalespersonid
Union All
-- Goods Exchanged In
select  sehcompanyid, sehshopid, sehExchangedate,
poshCustomerId, sehdepartmentid,
convert(numeric(18, 2), sum(-isnull(sedExchangeqty,0))) Quantity,
countryname, sehExchangeNo, isnull(sehExchangerName,''CASH''), '''', sedItemId,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(-isnull(sedUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(-isnull(sedUnitPrice*sehExchangeRate,0)))csalesvalue,
convert(numeric(18, 2),sum(-isnull(sedUnitPrice*sehdepexrate,0)))dsalesvalue,
''Exchanged In'' as Type ,isnull(ih.sehsalespersonid,0) as salespersonid
from
losPosExchangeHeader ih
left outer join losPosExchangeDetail invd
on ih.sehshopid = invd.sedshopid and ih.sehexchangeid = invd.sedExchangeid
left outer join losPosHeader on sehBillId = poshBillid and sehShopId = poshShopID
left outer join acustomermaster c on poshcustomerid=c.customerid
left outer join acountrymaster cm on c.countryid = cm.countryid, vwItemDescription v
where
sehcancelled=0 and seditemid = v.itemid and sedbillorexchange = ''B'' and sedExchangeQty >0
group by
sehcompanyid, sehshopid, sehExchangeNo, sehExchangeDate, sehExchangeid,
poshCustomerid, sehdepartmentid, countryname,
CustomerCardNo, Customername, sehExchangerName, sedItemId, v.ItemDescription, v.code,
v.vunitcode, v.vUnitName, vBrand, vitemCategoryid ,ih.sehsalespersonid
union all
-- Re-Exporting
select  rehcompanyid, rehshopid, rehExPortdate,
rehCustomerId, rehdepartmentid,
convert(numeric(18, 2), sum(isnull(redQuantity,0))) Quantity,
countryname, rehExportNo, CustomerName, '''', redItemId,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(isnull(redUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(isnull(redUnitPrice*rehExchangeRate,0)))csalesvalue,
convert(numeric(18, 2),sum(isnull(redUnitPrice*rehDepExRate,0)))dsalesvalue,
''Re-Export'' as Type  ,isnull(ih.rehSalesPersonID,0)salespersonid
from
losExportHeader ih left outer join losExportDetail invd
on ih.rehshopid = invd.redshopid and ih.rehExportId = invd.redExportid,
acustomermaster c, acountrymaster cm , vwItemDescription v
where
rehcancelled=0 and rehcustomerid=c.customerid and c.countryid = cm.countryid
and reditemid = v.itemid and rehType =''i''
group by
rehcompanyid, rehshopid, rehExportNo, rehExportDate, rehExportID,
rehCustomerid, rehdepartmentid, countryname,
CustomerCardNo, Customername,  redItemId, v.ItemDescription,
v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid ,ih.rehSalesPersonID
union all
-- Goods return note  - Kishore 23/06/2003
select
grnCompanyId, grnhShopId, grnhGoodsReturnNoteDate, grnhcustomerid, grnhdepartmentid,
convert(numeric(18, 2), sum(-isnull(invd.grndQuantity,0))) Quantity,
isnull(countryname, '''') countryname , GrnhGoodsreturnnoteNO,c.customername,'''',invd.grndItemId ,
v.ItemDescription, v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid,
convert(numeric(18, 2),sum(-isnull(grndUnitPrice,0)))salesvalue,
convert(numeric(18, 2),sum(-isnull(grndUnitPrice*grnhExchangeRate,0)))csalesvalue,
convert(numeric(18, 2),sum(-isnull(grndUnitPrice*grnhdepExRate,0)))dsalesvalue,
''Goods Return'' as Type ,0 as salesperson
from losGoodsReturnNoteHeader ih left outer join acustomermaster c
on GrnhCustomerID = c.customerid left outer join acountrymaster cm
on c.CountryId = cm.CountryId,
losGoodsReturnNoteDetail invd, vwItemDescription v, aItemCategory ic
where ih.grnhshopid = invd.grndshopid
and ih.grnhGoodsReturnNoteId  = invd.GRNDReturnNoteID
and GrnhCancel = 0
and invd.grndQuantity > 0
and invd.grndItemId = v.ItemId
and v.vItemCategoryId = ic.ItemCategoryId
group by grncompanyid, grnhshopid, v.vBrand, ic.CategoryNameDescription,
GrnhGoodsreturnnoteDate, c.customername ,
grnhGoodsReturnNoteId, ih.GrnhGoodsreturnnoteNO, grnReturnAccId, grnhExchangeRate,
GrnhCustomerID, grnhdepartmentid, countryname, customercardno, grnhexchangerate ,
grndItemId, v.ItemDescription,
v.code, v.vunitcode, v.vUnitName, vBrand, vitemCategoryid'
GO
/****** Object:  StoredProcedure [dbo].[spFixedAssetopeningBalance]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedAssetopeningBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified on	: 26/03/04, 16/04/2004
--Modified By	: Hariharan R
CREATE  proc [dbo].[spFixedAssetopeningBalance] (@intcompanyid as int,
	 				 @lastfinyear as int ,
					 @intCmpCur as int )
as
begin
	set nocount on
	declare
		@intfinancialid as int,		
		@strCondition as varchar(50),
		@todate as datetime
		
	Create table #Temp(
			CompanyID int,
			TransDeptid int,
			FixedAssetid int,
			AssetAccid int,
			TransAmt numeric(18,2),
			Type varchar(3),
			TransType  varchar(3))
			-- from dep id and reducing cost value
			--asset  value For open asset
			set @intfinancialid= @lastfinyear
			--select @intfinancialid=financialid from vwfinyearperiod where
--			year(sdate)=left(@todate,4)
			
			select  @Todate =sdate  from vwfinyearperiod
			where financialid=@intfinancialid
			print @todate	
-- Fixed Asset Details Inserting
			insert into #Temp --Inertng asset and depreciation opending  details
			
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then costprice* exrate
			else  costprice end Costprice,''O'',''C'' from fixedasset
			where billsrefid is null and godownrefid is null and Cancelled=0
			insert into #Temp --dep open   value For open asset	
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then initialDepreciatedValue* exrate
			else  initialDepreciatedValue end initialDepreciatedValue,''O'',''D'' from fixedasset
			where billsrefid is null and godownrefid is null and Cancelled=0
			
			insert into #Temp --Inertng asset and depreciation opending  details
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then costprice* exrate
			else  costprice end Costprice,''A'',''C'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			insert into #temp  --Depreciation value For purchased or gdn transfer asset	
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then initialDepreciatedValue* exrate
			else  initialDepreciatedValue end initialDepreciatedValue,''A'',''D'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			
			
--depreciation 	
			insert into #temp
			select a.companyid,DepartmentID,FixedAssetID,assetAccountID,
			case when @intCmpCur=1 then consexrate* DepreciationAmount
			else  DepreciationAmount end DepreciationAmount ,''A'',''D''
			from depreciationheader a,depreciationdetail b
			where  	a.DepreciationID=b.DepreciationID and a.CompanyID=b.companyid
			and Cancelled=0  and DepreciationDate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and DepreciationDate <=@Todate
--Asset Transfer
			-- Department transfer
			insert into #Temp --Inertng asset transfer details
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then consexrate*-asttransvalue else  -asttransvalue*fromdepexrate end  assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* asttransvalue else asttransvalue*todepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* -astDeprValue else  -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate<=@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*todepexrate end  assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
				insert into #temp
			-- from acc dep id and redcuing cost value(accounts)
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate * -asttransvalue else -asttransvalue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- To acc dep id and depreciation reducing cost value
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccID,case when @intCmpCur=1 then  consexrate* asttransValue else  asttransValue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			
		
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate*-astDeprValue else -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is  null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate	
--disposal
			
			insert into #temp ---disposal case cost
			
			select disphcompanyid,disphdepartmentid,dispdasstid,
			case when c.lasttoaccid is null then c.FixedAssetAccID
			else c.lasttoaccid end
			dispdaccid, case when @intCmpCur=1 then  -disphexrate * dispdamount else  -dispdamount end dispdamount ,''D'',''C'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate
			
			insert into #temp --disposal case depreciation			
			
			select disphcompanyid,disphdepartmentid, dispdasstid,
		case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end dispdaccid,case when @intCmpCur=1 then disphexrate * disdepeBalamt else disdepeBalamt end disdepeBalamt,''D'',''D'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate	
			
			
			
			
--Final data
select CompanyID,TransDeptid,max(FixedAssetid)FixedAssetid,max(AssetAccid)AssetAccid,sum(TranAmt)transam,''O'' Type,''c'' TransType from
	(
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt from #temp
		where type =''O'' and transtype =''C''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
			
	union all	
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''A'' and transtype =''C''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	union all
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''T'' and transtype =''C''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	union all
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''D'' and transtype =''C''
		group by AssetAccid,TransDeptid,companyid
	) data1
	group by AssetAccid,TransDeptid,companyid,FixedAssetid
union all
		select CompanyID,TransDeptid,max(FixedAssetid)Fixedassetid,max(AssetAccid)AssetAccid,sum(TranAmt)transam,''O''Type,''D''TransTYpe from
		(
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''O'' and transtype =''D''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	union all
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''A'' and transtype =''D''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	union all
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''T'' and transtype =''D''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	union all
		select CompanyID,TransDeptid,max(FixedAssetid)fixedassetid,max(AssetAccid)AssetAccid,sum(TransAmt)tranamt  from #temp
		where type =''D'' and transtype =''D''
		group by AssetAccid,TransDeptid,companyid,FixedAssetid
	)Data2
	group by AssetAccid,TransDeptid,companyid,FixedAssetid
-- Dept filteration not given taking group by deptid also
end' 
END
GO
/****** Object:  View [dbo].[vwGetSlNoWarrantyDetails]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGetSlNoWarrantyDetails]'))
EXEC dbo.sp_executesql @statement = N'
/*
CREATED BY : SHINE DAS
ON			: 11.08.2011
Puporse	: To Bring Warranty Feature in Magnolia. This view is used to populate related information
			  in Service Modules.
*/
CREATE VIEW [dbo].[vwGetSlNoWarrantyDetails]
AS
--(FOR POS. InterfaceID:1502)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,posh.poshShopID Shopid,posh.poshBillID BillID,posh.poshBillNo BillNo,
posh.poshBillDate BillDate,posh.poshcustomerid customerid,posh.poshCustomerName CustomerName,
posd.posdServWarrantyUpto ServWarrantyUpto,posd.posdPartsWarrantyUpto PartsWarrantyUpto,
slid.sidSerialNo,posd.posdItemID ItemID
FROM
losposheader posh
INNER JOIN LOsPosDetail posd ON posh.poshShopID =posd.posdShopID and posh.poshBillID =posd.posdBillID
INNER JOIN losSerialIssueDetails slid ON posd.posdItemID =slid.sidItemID and posdBillID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
WHERE
poshCancelled =0 and slid.sidInterfaceID =1502
UNION ALL
--(FOR CREDIT INVOICE. InterfaceID:1504)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,invh.ihShopID ShopID,invh.ihInvoiceID BillID,invh.ihInvoiceNo BillNo,
invh.ihInvoiceDate BillDate,Invh.ihCustomerID customerid,CM.CustomerName CustomerName,
invd.idServWarrantyUpto ServWarrantyUpto,invd.idPartsWarrantyUpto posdPartsWarrantyUpto,
slid.sidSerialNo,invd.idItemID ItemID
FROM
losInvoiceheader Invh
INNER JOIN LOsInvoiceDetail invd ON invh.ihShopID =invd.idShopID AND invh.ihInvoiceID = invd.idInvoiceID
INNER JOIN losSerialIssueDetails slid ON invd.idItemID=slid.sidItemID and invd.idInvoiceID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
INNER JOIN aCustomerMaster CM on CM.CustomerID = Invh.ihCustomerID
WHERE invh.ihCancelled =0  and slid.sidInterfaceID =1504
UNION ALL
--(FOR Special Invoice - Cash. InterfaceID:5008)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,spInvh.ihShopID ShopID,spInvh.ihInvoiceID BillID, spInvh.ihInvoiceNo BillNo,
spInvh.ihInvoiceDate BillDate,spInvh.ihCustomerID customerid,CM.CustomerName CustomerName,
spInvd.idServWarrantyUpto ServWarrantyUpto,spInvd.idPartsWarrantyUpto posdPartsWarrantyUpto,
slid.sidSerialNo,spInvd.idItemID ItemID
FROM
losSpecialInvoiceHeader spInvh
INNER JOIN losSpecialInvoiceDetail spInvd ON spInvh.IhInvoiceID=spInvd.idInvoiceId AND spInvh.IhShopID =spInvd.idShopid
INNER JOIN loiSerialIssueDetails slid ON spInvd.idItemID=slid.sidItemID AND spInvd.idInvoiceID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
INNER JOIN aCustomerMaster CM ON CM.CustomerID = spInvh.ihCustomerID
WHERE
spInvh.ihCancelled =0 AND spInvh.ihTransFinished =1 and slid.sidInterfaceID =5008 AND spInvh.IhCashInvoice =1
UNION ALL
--(FOR Special Invoice - CREDIT. InterfaceID:5023)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,spInvh.ihShopID ShopID,spInvh.ihInvoiceID BillID,spInvh.ihInvoiceNo BillNo,
spInvh.ihInvoiceDate BillDate,spInvh.ihCustomerID customerid,CM.CustomerName CustomerName,
spInvd.idServWarrantyUpto ServWarrantyUpto,spInvd.idPartsWarrantyUpto posdPartsWarrantyUpto,
slid.sidSerialNo,spInvd.idItemID ItemID
FROM
losSpecialInvoiceHeader spInvh
INNER JOIN losSpecialInvoiceDetail spInvd ON spInvh.IhInvoiceID=spInvd.idInvoiceId AND spInvh.IhShopID =spInvd.idShopid
INNER JOIN loiSerialIssueDetails slid ON spInvd.idItemID=slid.sidItemID AND spInvd.idInvoiceID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
INNER JOIN aCustomerMaster CM ON CM.CustomerID = spInvh.ihCustomerID
WHERE
spInvh.ihCancelled =0 AND spInvh.ihTransFinished =1 and slid.sidInterfaceID =5023 AND spInvh.IhCashInvoice =0
UNION ALL
--(FOR Special Despatch - Cash. InterfaceID:5009)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,spInvh.ihShopID ShopID,spInvh.ihInvoiceID BillID,spInvh.ihInvoiceNo BillNo,
spInvh.ihInvoiceDate BillDate,spInvh.ihCustomerID customerid,CM.CustomerName CustomerName,
spInvd.idServWarrantyUpto ServWarrantyUpto,spInvd.idPartsWarrantyUpto posdPartsWarrantyUpto,
slid.sidSerialNo,spInvd.idItemID ItemID
FROM
losSpecialInvoiceHeader spInvh
INNER JOIN losSpecialInvoiceDetail spInvd ON spInvh.IhInvoiceID=spInvd.idInvoiceId AND spInvh.IhShopID =spInvd.idShopid
INNER JOIN loiSerialIssueDetails slid ON spInvd.idItemID=slid.sidItemID AND spInvd.idInvoiceID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
INNER JOIN aCustomerMaster CM ON CM.CustomerID = spInvh.ihCustomerID
WHERE
spInvh.ihCancelled =0 AND spInvh.ihTransFinished =1 and slid.sidInterfaceID =5009 AND spInvh.IhCashInvoice =1
UNION ALL
--(FOR Special Despatch - CREDIT. InterfaceID:5009)
SELECT
slid.sidInterfaceID,vi.code,vi.itemdescription,spInvh.ihShopID ShopID,spInvh.ihInvoiceID BillID,spInvh.ihInvoiceNo BillNo,
spInvh.ihInvoiceDate BillDate,spInvh.ihCustomerID customerid,CM.CustomerName CustomerName,
spInvd.idServWarrantyUpto ServWarrantyUpto,spInvd.idPartsWarrantyUpto posdPartsWarrantyUpto,
slid.sidSerialNo,spInvd.idItemID ItemID
FROM
losSpecialInvoiceHeader spInvh
INNER JOIN losSpecialInvoiceDetail spInvd ON spInvh.IhInvoiceID=spInvd.idInvoiceId AND spInvh.IhShopID =spInvd.idShopid
INNER JOIN loiSerialIssueDetails slid ON spInvd.idItemID=slid.sidItemID AND spInvd.idInvoiceID = slid.sidTransactionID
INNER JOIN vwItemDescription vi ON vi.ItemID = slid.sidItemID
INNER JOIN aCustomerMaster CM ON CM.CustomerID = spInvh.ihCustomerID
WHERE
spInvh.ihCancelled =0 AND spInvh.ihTransFinished =1 and slid.sidInterfaceID =5009 AND spInvh.IhCashInvoice =0'
GO
/****** Object:  View [dbo].[vwGodownDamageClearing]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownDamageClearing]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGodownDamageClearing    Script Date: 18/01/2003 9:45:37 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwGodownDamageClearing] as
select dchGodownid, dchClearingID, dchClearingNO, dchClearingDate, dchClearingDoneBY, dchRemarks,
dcditemid,ItemDescription, sum(dcdAvailableQty) as BeforeVerify,sum(dcdWriteOffQty) as AfterVerify
from loiDamageClearingHeader, loiDamageClearingDetails, vwItemDescription
where dchGodownID = dcdGodownID and dchClearingID = dcdClearingID and dcdItemID = ItemID
group by dchGodownid, dchClearingID, dchClearingNO, dchClearingDate, dchClearingDoneBY, dchRemarks,
dcditemid,ItemDescription'
GO
/****** Object:  View [dbo].[vwGodownIssueArrivalLocationWise]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownIssueArrivalLocationWise]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGodownIssueArrivalLocationWise    Script Date: 18/01/2003 9:45:37 PM ******/
-----------------------------------------------------------------------------
-- View               : vwGodownIssueArrivalLocationWise
-- Created by         : Kishore
-- Created On         : 18/12/2002
-- Brief Description  : This view combines loiLocationArrivalDetails and
--                      loiLocationIssueDetails. The mode column
--                      is -1 if it is issue and 1 if it is arrival
-----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwGodownIssueArrivalLocationWise] AS
--
SELECT ladGodownId GodownId, ladTransId TransId, ladLocationId LocationId,
lLocationName LocationName, ladItemId ItemId, ItemCode, ItemDescription ItemName,
ladItemQty Quantity, ladInterfaceId InterfaceId, 1 Mode, ladCancel Cancelled
FROM loiLocationArrivalDetails, loiLocation, aItem
WHERE loiLocationArrivalDetails.ladLocationId = loiLocation.lLocationId
ANd loiLocationArrivalDetails.ladGodownId = loiLocation.lGodownId
AND loiLocationArrivalDetails.ladItemId = aItem.ItemId
--AND ladCancel <> 1
UNION ALL
SELECT lidGodownId GodownId, lidTransactionId TransId, lidLocationId LocationId,
lLocationName LocationName, lidItemId ItemId, ItemCode, ItemDescription ItemName,
lidItemQty Quantity, lidInterfaceId InterfaceId, -1 Mode, lidCancel Cancelled
FROM loiLocationIssueDetails, loiLocation, aItem
WHERE loiLocationIssueDetails.lidLocationId = loiLocation.lLocationId
ANd loiLocationIssueDetails.lidGodownId = loiLocation.lGodownId
AND loiLocationIssueDetails.lidItemId = aItem.ItemId
--AND lidCancel <> 1'
GO
/****** Object:  View [dbo].[vwGdnBinCardBadQtySummary]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardBadQtySummary]'))
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwGdnBinCardBadQtySummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 28-07-2010
-- Description :
--    To compute godown bad stock in transactions summary method.
--    This view is created based on vwGdnBinCardBadQty.
--    Summary Date filtering is additionally added.
--    Group By clause was removed to improve performance.
-- ===============================================
CREATE VIEW [dbo].[vwGdnBinCardBadQtySummary] AS
--write off
select wd.wdGodownid godownid, wd.wditemid ItemID, wh.whDate GDate,
NULL Transid, NULL TransNo, wd.wdWriteoffQty badtransqty,
''Write Off'' as [Type], 1 mode, NULL updatetime
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid = wd.wdid
and wh.whgodownid = wd.wdgodownid
and wh.whcancelled = 0
and wh.whType = ''W'' and wh.whDate>''20100803''
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedbadStock-svdAvailbadStock,
''Bad Verification Plus'', 1 mode, NULL
from  loistockverificationheader, loistockverificationdetail where
svhid = svdid and svhgodownid = svdgodownid and svdVerifiedbadStock > svdAvailbadStock
and svhCancelled=0 and svhDate>''20100803''
union all
--stock verification deduct
select svdGodownid, svdItemid, svhDate, NULL, NULL SvAddNo,
svdAvailbadStock - svdVerifiedbadStock,
''Bad Verification Minus'', -1 mode, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdAvailbadStock > svdVerifiedbadStock
and svhCancelled=0 and svhDate>''20100803''
union all
--damage qty clearance
select dcdgodownid, dcdItemID, dchClearingDate, NULL, NULL,
dcdWriteOffQty, ''Damage Cleared'', -1 mode, NULL
from  LOiDamageClearingHeader, LOiDamageClearingdetails
where dchClearingID = dcdClearingID and dchgodownid = dcdgodownid
and dchcancelled = 0 and dchClearingDate>''20100803'''
GO
/****** Object:  View [dbo].[TestView]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TestView]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TestView] as
select   posditemid,ItemDescription,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) cUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) dUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) posdUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshExchangeRate) cActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshDepExRate) dActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice)) posdActualUnitPrice,
posdquantity,posdRateType, poshBilldate,poshbillID,
poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,
posdcostprice * poshExchangeRate ccostprice, ''S'' as type,
((posdUnitPrice / posdquantity) - posdcostprice) margin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount
from
losposdetail, losposheader,aitem
where
poshBillid = posdBillid and
ItemID=posditemid and
poshShopid = posdshopid AND POSHCANCELLED = 0
-------------------------------------------------------------- 2
UNION ALL
select
iditemid, ItemDescription,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity))  posdUnitPrice,
convert(numeric(18,2), (idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2), (idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2), (idActualUnitPrice))  posdActualUnitPrice,
idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,
idcostprice * ihDepExRate,idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) margin,
((idUnitPrice / idquantity) - idcostprice) * ihDepExRate  dmargin,
((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate) dAmount
from losinvoiceheader ih, losinvoicedetail invd, aitem
where ih.ihInvoiceid = invd.idInvoiceid  and itemid=invd.iditemid and ih.ihshopid = invd.idshopid AND
IHCANCELLED = 0 and ihproforma = 0 and ihtype = ''i''
----------------------------------------------------------------
UNION ALL
----------------------------------------------------------------3
select
seditemid,ItemDescription,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehExchangeRate) cUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehDepExRate) dUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity))  UnitPrice,
convert(numeric(18,2),(sedActualUnitPrice) * sehExchangeRate) cActualUnitPrice,
convert(numeric(18,2),(sedActualUnitPrice) * sehDepExRate) dActualUnitPrice,
convert(numeric(18,2),(sedActualUnitPrice)) ActualUnitPrice,
sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,
sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, ''S'',
((sedUnitPrice / sedquantity)  - sedcostprice) margin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate  cmargin,
convert(numeric(18, 2),sedUnitPrice)  Amount,convert(numeric(18, 2),sedUnitPrice * sehExchangeRate) cAmount,
convert(numeric(18, 2),sedUnitPrice * sehDepExRate) dAmount
from losposexchangeheader,losposexchangedetail,aitem
where itemid=seditemid and  sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
---------------------------------------------------------------
UNION ALL
---------------------------------------------------------------4
select
iditemid, ItemDescription,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)) UnitPrice,
convert(numeric(18,2),(idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2),(idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2),(idActualUnitPrice)) ActualUnitPrice,
reqqty, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / reqqty) -idcostprice) margin,
((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate dmargin ,
((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount, convert(numeric(18, 2),idUnitPrice * ihExchangeRate)  cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate)  Amount
from losspecialinvoicedetail, losspecialinvoiceheader,aitem
where  itemid=iditemid and ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 0 and ihproforma = 0 and IhTransFinished = 1 and ihNoofOCDetails=0'
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedBillDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SelectedBillDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ======================================================================================
-- Author: LAWRENCE M.
-- Create date: 29 November 2010
-- Description: To show the Bill details based on the selected Bill numbers
-- This stored procedure is used to show the report
-- ======================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 19 April 2011
-- Description: If the selected bill has any Extras[Added Items] need to show Seperatly
--    Shopid also added in the filtering condition
-- ======================================================================================
-- Modified By: LAWRENCE M.
-- Modified date: 29 September 2011
-- Description: To add the Tax fields for showing the F&B master bill Reports
-- ======================================================================================
CREATE PROCEDURE [dbo].[SP_SelectedBillDetails](@BillID AS INT,@OutletId AS INT)
AS
BEGIN
DECLARE @intFirstRow AS INT
DECLARE @intMaxRow AS INT
DECLARE @intDishtype AS INT
DECLARE @intBillType AS INT
CREATE TABLE #TempSelectedBill
(
intDetailId INT, --IDENTITY(1,1) NOT NULL,
intDishId INT,
intType INT,
intBillid INT,
decTQty DECIMAL(18,2),
decTRate DECIMAL(18,2)
)
CREATE TABLE #FinalSelectedBill
(
strDishCode VARCHAR(50),
strDishName VARCHAR(250),
intDishID INT,
decFQty DECIMAL(18,2),
decFRate DECIMAL(18,2),
intFBillID INT
)
INSERT INTO  #TempSelectedBill (intDetailId,intDishId,intType,intBillid,decTQty,decTRate)
SELECT fb_pd_processdetailid ,fb_pd_dishid,fb_pd_addedItemtype,fb_pd_processid,fb_pd_reusedqty,
fb_pd_Actualrate
FROM LosPosFAndBHeader INNER JOIN Fb_processdetail ON fb_pd_processid=poshBillID
AND poshShopID=fb_pd_outletid AND fb_pd_companyid=poshCompanyID
WHERE poshBillID=@BillID and poshShopID=@OutletId
AND poshShopID=@OutletId
SET @intMaxRow=0
SET @intFirstRow=1
SELECT @intMaxRow=MAX(intDetailId) from #TempSelectedBill
IF @intMaxRow>0
BEGIN
WHILE @intMaxRow>=@intFirstRow
BEGIN
SET @intBillType=0
SELECT @intBillType=intType FROM #TempSelectedBill WHERE intDetailId=@intFirstRow
IF @intBillType=0
BEGIN
INSERT INTO #FinalSelectedBill(strDishCode,strDishName,intDishID,decFQty,decFRate,intFBillID)
SELECT fb_dd_dishcode,fb_dd_dishname,fb_dd_dishid,decTQty,decTRate,@BillID
FROM #TempSelectedBill INNER JOIN Fb_dishdetails ON intDishId=fb_dd_dishid
WHERE intBillid=@BillID AND intDetailId=@intFirstRow ORDER BY intDetailId
END
ELSE IF @intBillType=1
BEGIN
INSERT INTO #FinalSelectedBill (strDishCode,strDishName,intDishID,decFQty,decFRate,intFBillID)
SELECT fb_dd_dishcode,''    ''+fb_dd_dishname+''[Extras]'',fb_dd_dishid,decTQty,decTRate,@BillID
FROM #TempSelectedBill INNER JOIN Fb_dishdetails ON intDishId=fb_dd_dishid
WHERE intBillid=@BillID AND intDetailId=@intFirstRow ORDER BY intDetailId
END
ELSE
BEGIN
INSERT INTO #FinalSelectedBill (strDishCode,strDishName,intDishID,decFQty,decFRate,intFBillID)
SELECT itemcode,''    ''+itemdescription+''[Extras]'',ITEMID,decTQty,decTRate,@BillID
FROM #TempSelectedBill INNER JOIN AITEM ON intDishId=ITEMID
WHERE intBillid=@BillID AND intDetailId=@intFirstRow ORDER BY intDetailId
END
SET @intFirstRow=@intFirstRow+1
END
SELECT strDishCode AS DishCode,strDishName AS DishName,intDishID AS DishId,decFQty AS Qty,
decFRate AS Rate,decFQty*decFRate AS Total,*
FROM #FinalSelectedBill INNER JOIN LosPosFAndBHeader ON intFBillID=poshBillID
INNER JOIN Fb_processdetail ON  fb_pd_processid=poshBillID AND
fb_pd_outletid=poshShopID AND fb_pd_companyid=poshCompanyID  and fb_pd_dishid=intDishID
WHERE poshShopID=@OutletId
END
DROP TABLE #TempSelectedBill
DROP TABLE #FinalSelectedBill
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_audittool_trans_details]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_audittool_trans_details]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[sp_audittool_trans_details] @journalid as integer,@accid as integer
as
begin
--Coded by Rajesh Kamalakshan-----------------------------------------------------------
--dated 24-2-2007-----------------------------------------------------------------------
create table #listdata (fieldname  varchar(25),fieldvalues  varchar(50))
declare @amount numeric(18,2)
declare @actulamount numeric(18,2)
declare @departmentamount  numeric(18,2)
declare @departmentid integer
declare @departmentname  varchar(100)
declare @currencyid  integer
declare @currencyname  varchar(50)
declare @financialyearid integer
declare @financialyear  varchar(25)
declare @jtype as varchar(25)
declare @jrefno as varchar(25)
declare @lastmodified as varchar(25)
declare @paymentdepexrate as numeric(18,2)
declare @paymentexchangerate as numeric(18,2)
	select @financialyearid=a.financialid,@amount=b.amount,@actulamount=b.actualamount,@departmentamount=b.depamount,@departmentid=b.departmentid,@currencyid=a.currencyid,@jtype=a.type,@jrefno=a.referenceno  from moajournalheader a,moajournaldetails b where a.journalid=b.journalid and a.journalid=@journalid and a.cancel=0 and b.accountid=@accid
	select @departmentname=departmentname from adepartmentmaster where departmentid=@departmentid
	insert into #listdata values(''Department Name'',@departmentname)
	insert into #listdata values(''Department ID'',@departmentid)
	select @financialyear=startyear from afinancialyear where financialid=@financialyearid
	insert into #listdata values(''Financial Year'',@financialyear)
	SELECT @currencyname=CURRENCYNAME FROM ACURRENCYMASTER WHERE CURRENCYID=@currencyid
	insert into #listdata values(''Currency'',@currencyname )
	insert into #listdata values(''Amount'',@amount )
	insert into #listdata values(''Actual Amount'',@actulamount )
	insert into #listdata values(''Department Amount'',@departmentamount )
	if @jtype=''P''
		begin
			select @lastmodified=lastmodified,@paymentdepexrate=phdepexrate,@paymentexchangerate=phexchangerate,@financialyearid=phfinancialid,@departmentid=phdepartmentid from aHQPaymentVoucherHeader where phpaymentno=@jrefno
			insert into #listdata values(''Payment Details'','''' )
			insert into #listdata values(''Last Modified'',@lastmodified)
			insert into #listdata values(''Dep Ext Rate '',@paymentdepexrate)
			insert into #listdata values(''Ext Rate '',@paymentexchangerate)
			select @financialyear=startyear from afinancialyear where financialid=@financialyearid
			insert into #listdata values(''Financial Year'',@currencyname)
			select @departmentname=departmentname from adepartmentmaster where departmentid=@departmentid
			insert into #listdata values(''Department Name'',@departmentname)
			insert into #listdata values(''Department ID'',@departmentid)
		end
	if @jtype=''R''
		begin
			select @lastmodified=lastmodified,@paymentdepexrate=depexrate,@paymentexchangerate=exchangerate,@financialyearid=financialid,@departmentid=departmentid from ReceiptVoucherHeader where receiptno=@jrefno
			insert into #listdata values(''Receipt Details'','''' )
			insert into #listdata values(''Last Modified'',@lastmodified)
			insert into #listdata values(''Dep Ext Rate '',@paymentdepexrate)
			insert into #listdata values(''Ext Rate '',@paymentexchangerate)
			select @currencyname=startyear from afinancialyear where financialid=@financialyearid
			insert into #listdata values(''Financial Year'',@currencyname)
			select @departmentname=departmentname from adepartmentmaster where departmentid=@departmentid
			insert into #listdata values(''Department Name'',@departmentname)
			insert into #listdata values(''Department ID'',@departmentid)
		end
	if @jtype=''DCN''
		begin
			SELECT @lastmodified=DCNRECMODIFYUSER,@paymentdepexrate=DCNDEPEXRATE,@paymentexchangerate=DCNEXCHANGERATE,@financialyearid=DCNFINANCIALID,@departmentid=DCNDEPARTMENTID FROM DEBITCREDITNOTE WHERE DCNNO=@jrefno
			insert into #listdata values(''Debit credit Note'','''' )
			insert into #listdata values(''Last Modified'',@lastmodified)
			insert into #listdata values(''Dep Ext Rate '',@paymentdepexrate)
			insert into #listdata values(''Ext Rate '',@paymentexchangerate)
			select @currencyname=startyear from afinancialyear where financialid=@financialyearid
			insert into #listdata values(''Financial Year'',@currencyname)
			select @departmentname=departmentname from adepartmentmaster where departmentid=@departmentid
			insert into #listdata values(''Department Name'',@departmentname)
			insert into #listdata values(''Department ID'',@departmentid)
		end
	if @jtype=''J''
		begin
			SELECT @paymentdepexrate=DEPEXRATES,@paymentexchangerate=EXCHANGERATE,@departmentid=DEPARTMENTID,@financialyearid=FINANCIALID FROM JournalTransHeader WHERE JOURNALNO=@jrefno
			insert into #listdata values(''Journal Details'','''' )
			insert into #listdata values(''Last Modified'',''Not Available'')
			insert into #listdata values(''Dep Ext Rate '',@paymentdepexrate)
			insert into #listdata values(''Ext Rate '',@paymentexchangerate)
			select @currencyname=startyear from afinancialyear where financialid=@financialyearid
			insert into #listdata values(''Financial Year'',@currencyname)
			select @departmentname=departmentname from adepartmentmaster where departmentid=@departmentid
			insert into #listdata values(''Department Name'',@departmentname)
			insert into #listdata values(''Department ID'',@departmentid)
		end
	select * from #listdata
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_audittool_ledger]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_audittool_ledger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create procedure [dbo].[sp_audittool_ledger] @accid as integer,@fromdate as datetime,@todate as datetime--,@credit as bit
as
begin
--Coded by Rajesh Kamalakshan-----------------------------------------------------------
--dated 24-2-2007-----------------------------------------------------------------------
	declare @ledgerjournalid integer
--	declare @ledgercredit bit
	declare @ledgercredit integer
	declare @a integer
	declare @b numeric
	declare @c varchar(250)
	declare @lbalance numeric
	declare @lamount varchar(50)
	declare @jtype as varchar(25)
	declare @jrefid as varchar(50)
	declare @postingrefid as integer
	declare @postintegerfielscount as integer
	declare @postintegerreferencecount as integer
	DECLARE @TABLECOUNT AS INTEGER
	set @lbalance=7089.63
--	create table #tledger(journalid integer,ldate datetime,lreceipt varchar(50),credit bit,ledgercode integer,
	create table #tledger(journalid integer,ldate datetime,lreceipt varchar(50),credit integer,ledgercode integer,
	ledgername varchar(250),remarks  varchar(1000),amount varchar(50) ,referenceid integer default 0,balance varchar(50),type varchar(25),diff integer)
--	ledgername varchar(250),remarks  varchar(1000),amount varchar(50) ,referenceid integer default 0,balance varchar(50),type varchar(25),diff bit)
	insert #tledger select a.journalid,b.journaldate,b.referenceno,a.journalcredit,c.accountid,c.accountdesc,b.remarks,a.amount,0,0,b.type,0
	from moajournaldetails a,moajournalheader b,aaccountmaster c
	where a.accountid=@accid and b.journalid=a.journalid and (b.journaldate>=@fromdate and b.journaldate<=@todate)
	and c.accountid= @accid and b.cancel=0
	order by b.journaldate
	DECLARE ledger_cursor CURSOR for
	select journalid,credit,amount,type,lreceipt from #tledger order by credit
	OPEN ledger_cursor
	FETCH NEXT FROM ledger_cursor
	into @ledgerjournalid,@ledgercredit,@lamount,@jtype,@jrefid
	WHILE @@FETCH_STATUS = 0
		begin
			set @postingrefid=0
			if @ledgercredit=0
				begin
					--select @b=sum(amount) from moajournaldetails  where  journalid=@ledgerjournalid
					--and journalcredit=1  group by journalid
					select @a=a.accountid,@c=b.accountdesc from moajournaldetails a,aaccountmaster b where a.journalid=@ledgerjournalid and a.journalcredit=1 and b.accountid=a.accountid
					set @lbalance=@lbalance+@lamount
				end
			else if @ledgercredit=1
				begin
					--select @b=sum(amount) from moajournaldetails  where  journalid=@ledgerjournalid
					--and journalcredit=0  group by journalid
					select @a=a.accountid,@c=b.accountdesc from moajournaldetails a , aaccountmaster b where a.journalid=@ledgerjournalid and a.journalcredit=0 and b.accountid=a.accountid
					set @lbalance=@lbalance-@lamount
				end
			if @jtype=''P''
				begin
					--for payment reference searches the debit credit note
					select @postingrefid=journalid from moajournalheader where referenceno
					in (select dcnno from debitcreditnote where dcnid
					in(select refdcnid from aHQPaymentVoucherHeader where phpaymentno=@jrefid)) and  cancel=0
					if @@rowcount=0
						begin
							--for payment reference searches the receipt
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select receiptno from ReceiptVoucherHeader where receiptid
							in(select refreceiptid from aHQPaymentVoucherHeader where phpaymentno=@jrefid)) and  cancel=0
						end
					if @@rowcount=0
						begin
							--payment searches shipment
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select phpaymentno from aHQPaymentVoucherHeader where phpaymentid
							in(select refpaymentid from aHQPaymentVoucherHeader where phpaymentno=@jrefid)) and  cancel=0
						end
				end
			else if @jtype=''R''
				begin
					select @postingrefid=journalid from moajournalheader where referenceno
					in (select phpaymentno from aHQPaymentVoucherHeader where phpaymentid
					in(select paymentid from ReceiptVoucherHeader where receiptno=@jrefid)) and  cancel=0
				end
			else if @jtype=''J''
				begin
					--for joural reference searches the payment
					select @postingrefid=journalid from moajournalheader where referenceno
					in(select phpaymentno from aHQPaymentVoucherHeader where phpaymentid
					in(select paymentid from JournalTransHeader where journalno=@jrefid))  and cancel=0
					if @@rowcount=0
						begin
							--for joural reference searches the journal
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select journalno from JournalTransHeader where journaltransid
							in(select parentjournalid from JournalTransHeader where journalno=@jrefid)) and  cancel=0
						end
					if @@rowcount=0
						begin
							--for joural reference searches the bills
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select billsno from bills where billsid
							in(select billid from JournalTransHeader where journalno=@jrefid)) and  cancel=0
						end
					if @@rowcount=0
						begin
							--for joural reference searches receipt
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select receiptno from ReceiptVoucherHeader where receiptid
							in(select receiptid from JournalTransHeader where journalno=@jrefid)) and  cancel=0
						end
				end
			else if @jtype=''DCN''
				begin
					--for dcn to dcn
					select @postingrefid=journalid from moajournalheader where referenceno
					in (select dcnno from debitcreditnote where dcnid
					in(select parentdcnid from debitcreditnote where dcnno=@jrefid)) and  cancel=0
					if @@rowcount=0
						begin
							select @postingrefid=journalid from moajournalheader where referenceno
							in (select receiptno from ReceiptVoucherHeader where receiptid
							in(select parentreceiptid from debitcreditnote where dcnno=@jrefid)) and  cancel=0
						end
				end
			
			set @postintegerfielscount=(select COUNT(*) FROM #tledger WHERE JOURNALID=@postingrefid)
			set @postintegerreferencecount=(select COUNT(*) FROM #tledger WHERE referenceid=@postingrefid)
				IF @postintegerfielscount >0 and @postintegerreferencecount=0
					begin
						update #tledger set referenceid=@postingrefid where (journalid=@ledgerjournalid or journalid=@postingrefid) and  referenceid = 0
					end
			update #tledger set ledgercode=@a,ledgername=@c,balance=@lbalance where journalid=@ledgerjournalid
		FETCH NEXT FROM ledger_cursor
		into @ledgerjournalid,@ledgercredit,@lamount,@jtype,@jrefid
	end
	close ledger_cursor
	deallocate ledger_cursor
--------------for updating the diffrence bit field
	declare @difrefid as integer
	declare @difbalance as integer
	DECLARE diffrence_cursor CURSOR for
	select sum(v.debit)-sum(v.credit)as balance,v.referenceid from(
	select case when credit=0 then cast(amount as numeric(18,2)) else 0  end as debit ,
	case when credit=1 then cast(amount as numeric(18,2)) else 0 end as credit,
	referenceid
	from #tledger
	group by referenceid,credit,amount) v --COMMENTED FOR SEENCO AN ERROR REPORTTED CANNOT GROUP BY BIT COLUMN
--	group by referenceid,amount) v
	group by referenceid
	order by referenceid
	OPEN diffrence_cursor
	FETCH NEXT FROM diffrence_cursor
	into  @difbalance,@difrefid
	WHILE @@FETCH_STATUS = 0
		begin
			if @difbalance<>0
				begin
					update #tledger set diff=1 where referenceid=@difrefid
				end
		FETCH NEXT FROM diffrence_cursor
		into  @difbalance,@difrefid
		end
	close diffrence_cursor
	deallocate diffrence_cursor
----------------------------------------------------------
	declare @Cnt int
	set @Cnt=(select Count(*) from #tledger)
--	select * from #tledger orde7r by ldate
	--create table #tledger(journalid integer,ldate datetime,lreceipt varchar(50),credit bit,ledgercode integer,
	--ledgername varchar(250),remarks  varchar(1000),amount varchar(50) ,referenceid integer default 0,balance varchar(50),type varchar(25),diff bit)
	SELECT @TABLECOUNT=COUNT(*) FROM SYSOBJECTS WHERE NAME =''REPORTOUT'' AND XTYPE=''U''
	IF @TABLECOUNT>=1
		begin
			drop table REPORTOUT			
		end
	CREATE tABLE REPORTOUT (RDATE  datetime,rreceipt  varchar(50),rtype  varchar(5),rledgername  varchar(250),ldebitamt  varchar(50),
--	lcreditamt  varchar(50),rbalance  varchar(50),rcnt  integer,rremarks  varchar(1000),rjournalid  integer, rreferenceid  integer,rdiff bit)
	lcreditamt  varchar(50),rbalance  varchar(50),rcnt  integer,rremarks  varchar(1000),rjournalid  integer, rreferenceid  integer,rdiff integer)
	insert REPORTOUT select ldate,lreceipt,case credit when 0 then ''To'' when 1  then ''By'' end as toby,ledgername,case credit when 0 then amount when 1  then '''' end as ldebit,
	case credit  when 1 then amount when 0  then '''' end as lcrebit,balance,@Cnt cnt,remarks,journalid,referenceid,diff from  #tledger order by ldate,credit
	SELECT * FROM REPORTOUT order by RDATE,rtype
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SP_MONTHLYCREDIT]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MONTHLYCREDIT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--EXEC SP_MONTHLYCREDIT 366,1
--EXEC SP_MONTHLYCREDIT 48,2
CREATE PROCEDURE [dbo].[SP_MONTHLYCREDIT](@INTCUSTOMERID  INT,@SHOPID INT)
AS
DECLARE @INTMONTH  INT
DECLARE @INTYEAR  INT
DECLARE @CRLIMIT  NUMERIC(18,2)
DECLARE @DRLIMIT NUMERIC(18,2)
DECLARE @INVOICEID INT
DECLARE @COUNT INT
DECLARE @INDEX INT
BEGIN
CREATE TABLE #TEMP(ID INT IDENTITY,TEMPINVOICEID INT)
SET @CRLIMIT = 0
SET @DRLIMIT = 0
SET @INTMONTH = (SELECT MONTH(PACKAGEDATE) FROM aPAckageSettings)
SET @INTYEAR =(SELECT YEAR(PACKAGEDATE) FROM APACKAGESETTINGS)
--1.CREDIT INVOICE
SET @CRLIMIT =(SELECT ISNULL(SUM(IHINVOICEAMOUNT),0) FROM losInvoiceheader WHERE IHTYPE=''I''
AND IHCANCELLED = 0 AND IHPOSTED = 0 AND  MONTH(IHINVOICEDATE)=@INTMONTH
AND YEAR(IHINVOICEDATE)=@INTYEAR AND IHCUSTOMERID = @INTCUSTOMERID )
--2.SERVICE INVOICE
SET @CRLIMIT  = @CRLIMIT +(SELECT ISNULL(SUM(SERINVHAMOUNT),0) FROM  losserviceinvheader
WHERE MONTH(SERINVHDATE)=@INTMONTH AND
YEAR(SERINVHDATE)=@INTYEAR AND SERINVHCANCELLED = 0 AND SERINVHPOSTED = 0
AND SERINVHCUSTOMERID=@INTCUSTOMERID )
--3.SPCIAL INVOICE
SET @CRLIMIT  = @CRLIMIT +(SELECT ISNULL(SUM(IHINVOICEAMOUNT),0) FROM  losSpecialInvoiceHeader
WHERE MONTH(IHINVOICEDATE)=@INTMONTH AND
YEAR(IHINVOICEDATE)=@INTYEAR  AND IHRETURNBEFOREDESID IS NULL AND IHCANCELLED = 0 AND
IHPOSTED = 0 AND IHCUSTOMERID=@INTCUSTOMERID)
-----------------------------------------------------------------------------------------
IF @CRLIMIT > 0
BEGIN
--4. GOODS RETURN
SET @DRLIMIT = 0
INSERT INTO #TEMP
SELECT IHINVOICEID FROM losInvoiceheader WHERE IHTYPE=''I'' AND IHCANCELLED = 0  AND IHPOSTED = 0
AND IHCUSTOMERID = @INTCUSTOMERID
SET @COUNT = (SELECT COUNT(TEMPINVOICEID) FROM #TEMP)
SET @INDEX = 1
WHILE(@INDEX < = @COUNT)
BEGIN
SET @INVOICEID = (SELECT TEMPINVOICEID FROM #TEMP WHERE ID = @INDEX )
SET @DRLIMIT  = @DRLIMIT + (SELECT ISNULL(SUM(grndunitprice),0) FROM  losGoodsReturnNoteHeader inner join losGoodsReturnNoteDetail
on grnhgoodsreturnnoteid = grndreturnnoteid and grnhshopid = grndshopid
WHERE  grnhcustomerid=@INTCUSTOMERID and grnhshopid = @SHOPID AND grnhinvoiceid =@INVOICEID
And GRNHCANCEL =0 And GRNHPOSTED =0)
SET @INDEX = @INDEX + 1
END
DELETE FROM #TEMP --BECAUSE FILL REMAINING TABLE IDS
--5.GOODS BEFORE DESPATCH AND AFTER DESPATCH
----------------
INSERT INTO #TEMP
SELECT IHINVOICEID FROM losSpecialInvoiceHeader WHERE IHRETURNBEFOREDESID IS NOT NULL AND IHCANCELLED = 0  AND IHPOSTED = 0
AND IHCUSTOMERID = @INTCUSTOMERID
SET @COUNT = (SELECT COUNT(TEMPINVOICEID) FROM #TEMP)
SET @INDEX = 1
WHILE(@INDEX < = @COUNT)
BEGIN
SET @INVOICEID = (SELECT TEMPINVOICEID FROM #TEMP WHERE ID = @INDEX )
SET @DRLIMIT  = @DRLIMIT + (SELECT ISNULL(SUM(IHINVOICEAMOUNT),0) FROM  losSpecialInvoiceHeader,#TEMP
WHERE  Ihcustomerid=@INTCUSTOMERID and Ihshopid = @SHOPID AND Ihinvoiceid =@INVOICEID)
SET @INDEX = @INDEX + 1
END
----------------
END
DROP TABLE #TEMP
select  isnull(@CRLIMIT,0),isnull(@DRLIMIT,0)
--
--select  isnull(@CRLIMIT,0)
END' 
END
GO
/****** Object:  View [dbo].[vwshopservicesales]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopservicesales]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwshopCreditInvoice]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopCreditInvoice]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Last Modified on  : 04/08/2003
--Modified by  : R Harikrishnan
-------------------------------------------------------------------------
--Comments  : Added Exchange Rates
--Last Modified on  : 28/04/2003, 19/04/2004
--Modified by  : venki, Hariharan
--Comments  : added a feature for bonded ware house invoices
--   : Other charges Included
--   : Other charges given in group by clause to avoid doubling in Invoice queries
-------------------------------------------------------------------------
--Ref.No.1
--Modified on  : 17/08/2011
--Modified by  : AADYAKUMAR D V
--Comments     : Added F&B transaction  ]
---jyothish corrected idunitprice and idcdcustcur1\ 20111027
-------------------------------------------------------------------------
--Ref.No.2
--Modified on  : 10/12/2011
--Modified by  : SHINE DAS
--Comments     : Union All condition violated here. Varchar tried to union with
-- int. So conversion done for the same. (Issue raised from ASK.)
-------------------------------------------------------------------------
--Ref.No.3
--Modified on  : 12/12/2011
--Modified by  : AADYAKUMAR D V
--Comments     : Modified Ref.No.2 by changing column,also modify column dummy value
-------------------------------------------------------------------------
CREATE view [dbo].[vwshopCreditInvoice] as
select ihshopid, ihdutypaidby,sum(d.idunitprice)  idunitprice, sum(d.idcdcustcur) idcdcustcur,ioAmount,
h.ihcompanyid companyid, h.ihdepartmentid, h.ihshopid shopid, h.ihinvoiceid invoiceid,
h.ihinvoiceno invoiceno, h.ihinvoicedate invoicedate, h.ihduedate,
h.ihcustomerid customerid, ''PCI'' as type,
isnull(ihreferenceno,'''') referenceno,
isnull(ihremarks,'''') remarks, h.updatetime, ihexchangerate, ihfinancialid,
ihdepexrate,case when (select futurevarchar from ashops where shopid=ihshopid )=''B''
and ihdutypaidby='''' then  sum(d.idunitprice)+sum(d.idcdcustcur) + isnull(ocd.ioAmount,0)
else sum(d.idunitprice) + isnull(ocd.ioAmount,0)  end Amount,
0 as settled,h.ihexchangerates
from
losinvoiceheader h
left outer join
(select
ioShopID,ioInvoiceID,sum(ioAmount) ioAmount
from
losInvoiceOC
group by
ioShopID,ioInvoiceID) ocd
on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID, losinvoicedetail d
where
h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and
h.ihcancelled=0 and h.ihproforma=0 and h.ihcashinvoice=0 and ihtype =''i''
group by
h.ihcompanyid, h.ihdepartmentid, h.ihshopid , h.ihinvoiceid, h.ihinvoiceno,
h.ihinvoicedate, h.ihcustomerid, h.ihduedate, h.ihreferenceno, h.ihremarks,
h.updatetime,h.ihexchangerate, ihfinancialid, h.ihdepexrate,h.ihdutypaidby,
h.ihexchangerates, ocd.ioAmount
--,ihshopid, ihdutypaidby, idunitprice,idcdcustcur,ioAmount
--Ref.No.1 -------------------start----------------------------------------------
union all
select
----fb_pd_reusedqty,fb_pd_rate
poshShopID ihshopid,
--0 ihdutypaidby, --Ref.No.3
'''' ihdutypaidby, --Ref.No.3
fb_pd_rate idunitprice,0 idcdcustcur,0 ioAmount,
poshCompanyID companyid,poshDepartmentid ihdepartmentid,poshShopID shopid,poshBillID invoiceid,
poshBillNo invoiceno,convert(varchar, poshBillDate, 101) invoicedate,poshBillDate ihduedate,
poshcustomerid customerid,''fandb'' as type,
--isnull(poshfolioid,'''') referenceno,  --Ref.No.2
--convert (varchar(50), (isnull(poshfolioid,0))) referenceno,    --Ref.No.2  --Ref.No.3
isnull(poshgbillno,'''') referenceno,  --Ref.No.3
isnull(poshremarks,'''') remarks,updatetime,poshexchangerate ihexchangerate,poshFinancialId ihfinancialid,
poshdepexrate ihdepexrate,poshbillamount  Amount,
0 as settled,poshexchangerates ihexchangerates
from losposfandbheader
inner join fb_processdetail on fb_pd_processid = poshbillid and fb_pd_outletid = poshshopid
and poshbillorprocess = ''B'' and poshcashsale=0 and poshbilltype=''CR''
group by
poshCompanyID,poshDepartmentid ,poshShopID ,poshBillID , poshBillNo ,poshBillDate ,poshBillDate ,
poshcustomerid , poshfolioid , poshremarks,updatetime,poshexchangerate ,poshFinancialId ,
poshdepexrate ,poshbillamount,poshexchangerates,fb_pd_rate,
poshgbillno--Ref.No.3
--Ref.No.1 -------------------end----------------------------------------------'
GO
/****** Object:  View [dbo].[vwshopSalesAccountWise]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopSalesAccountWise]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By : Benzigar S D
-- Created On : 29-11-2008
---------------------------------------------------------------------------------------------------
--<<Ref-01>>
--Modified ON :- 14/05/2012
--Modified By :- MANUNADH.U
--Comment     :- Correct the calculation of TotalDiscount and Discper after GST implementation (To show
--				 in the rptshopsalesaccountwise.rpt - P&C-Sales Report - Shop Sales Account wise)
---------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwshopSalesAccountWise] AS
--pos
select poshBillId, poshShopId, poshBillDate, poshBillNo, posditemid,code,itemdescription,posdpquantity,
posdunitprice totalamount,posdunitprice/posdpquantity unitprice,posdactualunitprice,posdcostprice,
--<<Ref-01>>
--(posdactualunitprice*posdpquantity)- posdunitprice TotalDiscount,
--(((posdactualunitprice*posdpquantity)- posdunitprice)/(posdactualunitprice*posdpquantity))*100 Discper,
case when (posdactualunitprice * posdpquantity) < (posdunitprice - posdItemTaxAmount ) then 0
else (posdactualunitprice * posdpquantity) - (posdunitprice - posdItemTaxAmount) end as TotalDiscount
,case when (posdactualunitprice * posdpquantity) < (posdunitprice - posdItemTaxAmount ) then 0
else (((posdactualunitprice * posdpquantity) - (posdunitprice - posdItemTaxAmount)) /(posdactualunitprice* posdpquantity) )* 100 end as Discper,
--<<Ref-01>>
poshcancelledremarks Remarks,poshCustomerName, AccountDesc
from losposheader, aAccountMaster,losposdetail,vwitemdescription
where poshcancelled = 0
and poshCashAccid = accountid
and poshCompanyID = CompanyId
and poshBillId=posdbillid
and poshShopId=posdshopid
and itemid=posditemid
Union all
--credit invoice
select ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,iditemid,
code,itemdescription,
idPQuantity,idunitprice totalamount,idunitprice/idPQuantity unitprice,idActualUnitPrice,idcostprice,
(idactualunitprice*idpquantity)- idunitprice TotalDiscount,
case when idactualunitprice*idpquantity<> 0 then(((idactualunitprice*idpquantity)- idunitprice)/(idactualunitprice*idpquantity))*100  end Disper,
ihremarks remarks,CustomerName, ''Credit Invoice'' AccountDesc
from losinvoiceheader, acustomermaster,losinvoicedetail,vwitemdescription
where ihcancelled = 0
and ihcustomerid = customerid
and ihproforma = 0
and ihtype = ''i''
and ihinvoiceid=idinvoiceid
and ihshopid=idshopid
and itemid=iditemid
Union all
--exchange
select sehexchangeid, sehShopId, sehexchangedate, sehExchangeno,seditemid,
code,itemdescription,sedPQuantity,sedunitprice totalamount,
sedunitprice/sedPQuantity unitprice, sedActualUnitPrice,sedcostprice,
(sedactualunitprice*sedpquantity)- sedunitprice TotalDiscount,
case when sedactualunitprice*sedpquantity<> 0 then(((sedactualunitprice*sedpquantity)- sedunitprice)/(sedactualunitprice*sedpquantity))*100  end Disper,
sehremarks remarks, h.sehExchangerName, AccountDesc
from losposexchangeheader h, aAccountMaster a,losposexchangedetail e,vwitemdescription
where sehcancelled = 0
and sehCashAccID = a.accountid
and sehCompanyId = a.CompanyId
and sehexchangeid=sedexchangeid
and sedBillorExchange=''E''
and itemid=seditemid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockSplInvRet]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockSplInvRet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last modified by   : Kishore
-- Modified Date      : 07/08/2003
-- Comments	      : V3
-- TO update stock table when transaction is saved in special invoice return
-- sales transaction
-- Created   					(30/12/2002)
-- Verfied bY hariharan  			(03/01/2003)
-- Changed depending on comparison with v2 	(06/06/2003)
-- Added Free Item concept 			(07/08/2003)
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateShopStockSplInvRet] (@intInvoiceId int,
						@intShopId int,
						@process char(1)) AS
begin
	declare
		@cur_InvoiceId int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@cur_FreeQty numeric(18, 3),
		@intCount int
		
	set nocount on
	declare cursor_Detail  cursor for
		select idInvoiceId, idShopId, idItemId, ReqQty, idFreeQuantity
		from losSpecialInvoiceDetail
		where idInvoiceId = @intInvoiceId
		and idShopId = @intShopId
		and idratetype = 1 and reqQty < 0         -- To select only returned items
							  -- copied from v2
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_InvoiceId, @cur_ShopId, @cur_ItemId,
		@cur_itemQty, @cur_FreeQty
	while @@fetch_status = 0
	begin
		-- since reqqty will be stored as -ve in return case,
		-- the cursor variable is added to the stock
		-- in effect to reduce the stock as it will become -> stock - @cur_itemQty
		if @process = ''R''
		begin
			update mosShopStock set stock = stock + @cur_itemQty + @cur_FreeQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		-- since reqqty will be stored as -ve in return case,
		-- the cursor variable is substracted from the stock
		-- in effect to reduce the stock as it will become -> stock + @cur_itemQty
		if @process = ''F''
		begin
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock (ShopId, StockDate, ShipmentID, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update mosShopStock set stock = stock - (@cur_itemQty + @cur_FreeQty)
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		fetch next from cursor_Detail into
			@cur_InvoiceId, @cur_ShopId, @cur_ItemId,
			@cur_itemQty, @cur_FreeQty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  View [dbo].[vwfixedassetsconvertedfromstock]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfixedassetsconvertedfromstock]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Created  by 	: Hariharan
--Modiied 	: 01/02/2004
-- for finding the value based on the asset conversions
-- aded date field into the query venkitesh 080403
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE view [dbo].[vwfixedassetsconvertedfromstock] as
select whid,whno,whgodownid,whDate, sum(wdwriteoffqty*wdcostprice) stockvalue,
sum(isnull(actrefamount,0))  assetamount from
loiwriteoffheader
left outer join fixedasset ast on whid = writeoffrefid
and whgodownid = godownrefid AND 0 = ast.Cancelled, loiwriteoffdetail where whid = wdid
and whgodownid = wdgodownid and whtype=''a''
and whcancelled =0  and whtransfinished=1
group by whid, whgodownid,whno,whdate'
GO
/****** Object:  View [dbo].[vwfixedassetbills]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwfixedassetbills]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwfixedassetbills    Script Date: 18/01/2003 9:45:36 PM ******/
--created by 	: Hariharan
--Created Date	: 07/11/2002
--Last Modified : 06/01/2003
--Modified by	: leo
CREATE view [dbo].[vwfixedassetbills] as
select fxb.companyid, fxb.billsid, fxb.billsno, fxb.departmentid, max(fxb.billamount) billamount,
sum(isnull(actrefamount,0)) assetamount from (
select b.companyid, b.billsid, b.billsno, b.departmentid, sum(bd.amount) billamount
from bills b, billsdebitdetails bd ,
(select a.companyid, a.accountid, a.accountdesc from Aaccountmaster a, vwgroupmasterwithlevel vw
where vw.groupid = a.groupid and vw.parentgroupid =
(select fixedassetgroupid from asettings )) fa where b.billsid = bd.billsid and
b.companyid = bd.companyid and bd.accountid = fa.accountid and fa.companyid = bd.companyid
group by b.companyid, b.billsid, b.billsno, b.departmentid) fxb left outer join
fixedasset ast on fxb.billsid = ast.billsrefid group by fxb.companyid, fxb.billsid,
fxb.billsno, fxb.departmentid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockLP]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockLP]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateShopStockLP    Script Date: 18/01/2003 9:45:47 PM ******/
-- Created by   : Kishore
-- Created Date : 31/12/2002
-- Comments	: V3
-- TO update stock table when transaction is done in local purchase
-- sales transaction
-- Verified By  : Hariharan R
CREATE proc [dbo].[spUpdateShopStockLP] (@intBillID int,
			@intShopId int, @process char(1)) as
begin
	declare
		@cur_BillID int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@intCount int
	set nocount on
	declare cursor_Detail  cursor for
		select lpdbillid, lpdShopID, lpdItemID, lpdItemQuantity
		from loslocalpurchasedetail
		where lpdbillid = @intBillID and lpdShopID = @intShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_BillID, @cur_ShopId, @cur_ItemId,
		@cur_itemQty
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			update mosShopStock set Stock = Stock - @cur_ItemQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId				
		end
		if @process = ''F''
		begin
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock (ShopId, StockDate, ShipmentId, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			update mosShopStock set stock = stock + @cur_ItemQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		fetch next from cursor_Detail into
			@cur_BillID, @cur_ShopId, @cur_ItemId,
			@cur_itemQty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockGReturn]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockGReturn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Created  by   : Kishore
-- Created  Date : 31/12/2002
-- Comments : V3
-- TO update stock table when transaction is saved in Goods return
-- sales transaction
-- Verified by  : Hariharan on 03/01/2003
------------------------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on : 17/10/2003
-- Comments     : Added free items concept
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
------------------------------------------------------------------------------------------
-- Modified by  : VinothMurugan V.
-- Modified on : 26/05/2010
-- Comments     : Goods Return item delete means cannt update the stock
------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateShopStockGReturn] (@intReturnId int,
@intShopId int, @process char(1)) AS
begin
declare
@cur_ReturnId int,
@cur_ShopId int,
@cur_ItemId int,
@cur_itemQty numeric(18, 3),
@cur_FreeItemQty numeric(18, 3),
@intCount int,
@cur_Damaged bit
set nocount on
declare cursor_Detail  cursor for
select grndReturnNoteId, grndShopId, grndItemId,
grndQuantity, grndFreeQuantity,
grndDamaged
from losGoodsReturnNoteDetail
where grndReturnNoteId = @intReturnId and grndShopId = @intShopId
open cursor_Detail
fetch next from cursor_Detail into
@cur_ReturnId, @cur_ShopId, @cur_ItemId,
@cur_itemQty, @cur_FreeItemQty, @cur_damaged
while @@fetch_status = 0
begin
if @process = ''R''  or @process = ''D''
begin
-- if damaged, then update bad stock
-- else update stock
if @cur_damaged = 1
begin
update mosShopStock
set BadStock = BadStock - (@cur_ItemQty + @cur_FreeItemQty)
where ItemId = @cur_ItemId and ShopId = @cur_ShopId
end
else
begin
update mosShopStock set stock = stock - (@cur_ItemQty + @cur_FreeItemQty)
where ItemId = @cur_ItemId and ShopId = @cur_ShopId
end
end
if @process = ''F''
begin
select @intCount = count(*) from mosShopStock
where ItemId = @cur_ItemId and ShopId = @intShopId
if @intCount = 0
begin
insert mosShopStock (ShopId, StockDate, ShipmentId, ItemId,
OpeningStock, Stock, OpeningBadStock, BadStock)
Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
end
-- if damaged, then update bad stock
-- else update stock
if @cur_damaged = 1
begin
update mosShopStock
set BadStock = BadStock + (@cur_ItemQty + @cur_FreeItemQty)
where ItemId = @cur_ItemId
and ShopId = @cur_ShopId
end
else
begin
update mosShopStock
set stock = stock + (@cur_ItemQty + @cur_FreeItemQty)
where ItemId = @cur_ItemId and ShopId = @cur_ShopId
end
end
fetch next from cursor_Detail into
@cur_ReturnId, @cur_ShopId, @cur_ItemId,
@cur_itemQty, @cur_FreeItemQty, @cur_damaged
end
close cursor_Detail
deallocate cursor_Detail
return 0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockExchange]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockExchange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified by   : Kishore
-- Modified Date : 05/06/2003
-- TO update stock table when transaction is saved in Goods Exchange
-- sales transaction
-- Added the initialization of variable @intCount
---------------------------------------------------------------------------------
-- Modified by   : Kishore
-- Modified on   : 08/08/2003
-- Comments      : Added the free item concepts
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
-------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateShopStockExchange]  (@intExchangeId int,
			@intShopId int, @process char(1)) as
Begin
	Declare
		@cur_ExchangeId int,
		@cur_ShopId int,
		@cur_ItemId int,
		@cur_itemQty numeric(18, 3),
		@cur_FreeQty numeric(18, 3),
		@intCount int,
		@cur_BillOrExchange char(1)
	set nocount on
	declare cursor_Detail  cursor for
		select sedExchangeId, sedShopId, sedItemId,
		case sedBillOrExchange when ''E'' then sedQuantity
		else sedExchangeQty end sedQuantity, sedBillOrExchange,
		Case sedBillOrExchange when ''E'' then sedFreeQty
		Else sedExcFreeQty End sedFreeQty
		from losPosExchangeDetail
		where sedExchangeId = @intExchangeId and sedShopId = @intShopId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_ExchangeId, @cur_ShopId, @cur_ItemId,
		@cur_itemQty, @cur_BillOrExchange, @cur_FreeQty
	set @cur_itemQty = isnull(@cur_itemQty,0)
	set @cur_FreeQty = isnull(@cur_FreeQty,0)
	while @@fetch_status = 0
	begin
		if @process = ''R''
		begin
			-- if type is exchange, stock should be reduced			
			if @cur_BillOrExchange = ''B''
			begin
				set @cur_ItemQty = -1 * @cur_ItemQty
				Set @cur_FreeQty = -1 * @cur_FreeQty
			end
			
			update mosShopStock set stock = stock + @cur_itemQty + @cur_FreeQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		if @process = ''F''
		begin
			set @intCount = 0
			select @intCount = count(*) from mosShopStock
				where ItemId = @cur_ItemId and ShopId = @intShopId
			if @intCount = 0
			begin
				insert mosShopStock (ShopId, StockDate, ShipmentId, ItemId,
					OpeningStock, Stock, OpeningBadStock, BadStock)
					Select @intShopId, getdate(), 1, @cur_ItemId, 0, 0, 0, 0
			end
			
			-- if type is exchange, stock should be reduced			
			if @cur_BillOrExchange = ''E''
			begin
				set @cur_ItemQty = -1 * @cur_ItemQty
				Set @cur_FreeQty = -1 * @cur_FreeQty
			end
			update mosShopStock set stock = stock + @cur_ItemQty + @cur_FreeQty
				where ItemId = @cur_ItemId and ShopId = @cur_ShopId
		end
		fetch next from cursor_Detail into
			@cur_ExchangeId, @cur_ShopId, @cur_ItemId,
			@cur_itemQty, @cur_BillOrExchange, @cur_FreeQty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
end' 
END
GO
/****** Object:  View [dbo].[vwLcReferredInPayments]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLcReferredInPayments]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by	: Kishore
-- Created on	: 22/09/2003
-- Comments	: Initially it was a derived table in payments
--                Made a separated view as the derived table began to
--                make problems like EXCEPTION_ACCESS_VIOLATION in VB
-----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwLcReferredInPayments] AS
SELECT BillId, Sum(PaidVendorEq) PaidVendorEq,
MAX(Amount) Amount
FROM vwLCMarginOutstanding lc
WHERE BillId is not null
GROUP BY BillId'
GO
/****** Object:  StoredProcedure [dbo].[sp_FandBCancelEdit]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_FandBCancelEdit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ====================================================================================
-- Author: LAWRENCE M.
-- Create date: 02 AUGUST 2011
-- Description: For getting the correct Edit value and Cancel value
--    in the Cash Detail Summary Report
-- Client : Wings Service
-- ====================================================================================
CREATE PROCEDURE [dbo].[sp_FandBCancelEdit] (@intOutletID AS INT,@TillNo AS INT)
as
BEGIN
	 CREATE TABLE #ETemp
	 (
	 ETempTillNo INT,
	 ETempOutletID INT,
	 ECountNo INT,
	 EValue Decimal(18,4)
	 )
	 CREATE TABLE #CTemp
	 (
	 TempCTillNo INT,
	 TempCOutletID INT,
	 CountCNo INT,
	 CValue Decimal(18,4)
	 )
	INSERT INTO #ETemp(ETempTillNo,ETempOutletID,EValue,ECountNo)
	select till_no,poshShopID,sum(poshbillamount * poshExchangeRate) value,Count(poshBillID) Count
	from losposfandbheader INNER JOIN
	TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	LosPosFAndBHeader.poshTillID = TillHistory.till_id
	inner join acurrencymaster  on acurrencymaster.CurrencyID=poshCurrencyID
	where poshRecModifyuser is not null and poshCancelled=0 AND till_no=@TillNo AND poshShopID=@intOutletID
	group by till_no,poshShopID
	
	INSERT INTO #CTemp(TempCTillNo,TempCOutletID,CValue,CountCNo)
	select till_no,poshShopID,sum(poshbillamount * poshExchangeRate) value,Count(poshBillID) Count
	from losposfandbheader INNER JOIN
	TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
	LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
	LosPosFAndBHeader.poshTillID = TillHistory.till_id
	inner join acurrencymaster  on acurrencymaster.CurrencyID=poshCurrencyID
	where poshCancelled=1 AND till_no=@TillNo AND poshShopID=@intOutletID
	group by till_no,poshShopID
	
	SELECT ETempTillNo till_no,ETempOutletID,ECountNo,EValue,CountCNo,CValue
	FROM #ETemp FULL OUTER JOIN #CTemp ON ETempTillNo=TempCTillNo AND TempCOutletID=ETempOutletID
END' 
END
GO
/****** Object:  View [dbo].[vwKeyPerformanceIndexes]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwKeyPerformanceIndexes]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By: Rajesh Kamalakshan
--Date :    25-11-2011
--Creatd as an underlying View fo showing perfomace indexes for SSRS report(As per Md request from sreelanks)
-------------------------------------------------------------------
CREATE VIEW [dbo].[vwKeyPerformanceIndexes]
AS
SELECT     lph.poshBillDate AS ''Date'', ''Pos Cash Sales'' AS PerformanceItemName, COUNT(*) AS CountofTransaction,
SUM(lph.poshBillAmount * lph.poshExchangeRate - ISNULL(psd.PosBankAmount, 0) * ISNULL(psd.posCompExRate, 0)) AS ''Amount''
FROM         dbo.LOsPosHeader AS lph LEFT OUTER JOIN
dbo.losPosChequeDetails AS psd ON psd.PoshBillID = lph.poshBillID
WHERE     (lph.poshCancelled = 0)
GROUP BY lph.poshBillDate
UNION ALL
SELECT     ihInvoiceDate AS ''Date'', ''Credit Sales'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(ihInvoiceAmount * ihexchangerate)
AS ''Amount''
FROM         dbo.LOsInvoiceHeader
WHERE     (ihCancelled = 0)
GROUP BY ihInvoiceDate
UNION ALL
SELECT     sehExchangeDate AS ''Date'', ''Exchange'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(sehBillAmount * sehExchangeRate)
AS ''Amount''
FROM         dbo.losposExchangeHeader
WHERE     (sehCancelled = 0)
GROUP BY sehExchangeDate
UNION ALL
SELECT     lph.poshBillDate AS ''Date'', ''Pos Credit Card Sales'' AS PerformanceItemName, COUNT(*) AS CountofTransaction,
SUM(lph.poshBillAmount * lph.poshExchangeRate - ISNULL(psd.PosBankAmount, 0) * ISNULL(psd.posCompExRate, 0)) AS ''Amount''
FROM         dbo.LOsPosHeader AS lph LEFT OUTER JOIN
dbo.losPosChequeDetails AS psd ON psd.PoshBillID = lph.poshBillID INNER JOIN
dbo.aAccountMaster AS am ON am.Misc = ''CC'' AND am.AccountID = lph.poshCashAccID
WHERE     (lph.poshCancelled = 0)
GROUP BY lph.poshBillDate
UNION ALL
SELECT     phPaymentDate AS ''Date'', ''Accounts Payments'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(phAmount * phdepexrate)
AS ''Amount''
FROM         dbo.aHQPaymentVoucherHeader
WHERE     (phCancelled = 0)
GROUP BY phPaymentDate
UNION ALL
SELECT     ReceiptDate AS ''Date'', ''Accounts Receipt'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(Amount * exchangerate) AS ''Amount''
FROM         dbo.ReceiptVoucherHeader
WHERE     (Cancelled = 0)
GROUP BY ReceiptDate
UNION ALL
SELECT     lph.poshBillDate AS ''Date'', ''POS Post Dated Cheque'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(ISNULL(psd.PosBankAmount,
0) * ISNULL(psd.posCompExRate, 0)) AS ''Amount''
FROM         dbo.LOsPosHeader AS lph INNER JOIN
dbo.losPosChequeDetails AS psd ON psd.PoshBillID = lph.poshBillID
WHERE     (lph.poshCancelled = 0)
GROUP BY lph.poshBillDate
UNION ALL
SELECT     ContraDate AS ''Date'', ''Contra'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(ContraAmount * ExchangeRate) AS ''Amount''
FROM         dbo.Contra
WHERE     (Cancelled = 0)
GROUP BY ContraDate
UNION ALL
SELECT     DCNDate AS ''Date'', ''Debit Note'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(DCNAmount * dcndepexrate) AS ''Amount''
FROM         dbo.DebitCreditNote
WHERE     (DCNDebit = 1) AND (DCNCancelled = 0)
GROUP BY DCNDate
UNION ALL
SELECT     DCNDate AS ''Date'', ''Credit Note'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(DCNAmount * dcndepexrate) AS ''Amount''
FROM         dbo.DebitCreditNote AS DebitCreditNote_1
WHERE     (DCNDebit = 0) AND (DCNCancelled = 0)
GROUP BY DCNDate
UNION ALL
SELECT     BillDate AS ''Date'', ''Bills'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(BillAmount * exchangerate) AS ''Amount''
FROM         dbo.Bills
WHERE     (Cancelled = 0)
GROUP BY BillDate
UNION ALL
SELECT     BillDate AS ''Date'', ''Service Invoice'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(BillAmount * exchangerate) AS ''Amount''
FROM         dbo.Bills AS Bills_1
WHERE     (Cancelled = 0)
GROUP BY BillDate
UNION ALL
SELECT     lphBillDate AS ''Date'', ''Local Purchase Bill(GRN)'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(lphBillAmount * lphexchangerate)
AS ''Amount''
FROM         dbo.LosLocalPurchaseHeader
GROUP BY lphBillDate
UNION ALL
SELECT     pbhBillDate AS ''Date'', ''Foreign Purchase'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(pbhBillAmount * pbhexchangerate)
AS ''Amount''
FROM         dbo.LOspPurchaseBillHeader
WHERE     (pbhCancelled = 0) AND (pbhBillDate IS NOT NULL)
GROUP BY pbhBillDate
UNION ALL
SELECT     IhInvoiceDate AS ''Date'', ''Special Invoice Cash'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(IhInvoiceAmount * ihexchangerate)
AS ''Amount''
FROM         dbo.losSpecialInvoiceHeader
WHERE     (IhCancelled = 0) AND (IhProforma = 0) AND (ihTransFinished = 1) AND (IhCashInvoice = 1) AND (ihNoofOCDetails = 0)
GROUP BY IhInvoiceDate
UNION ALL
SELECT     IhInvoiceDate AS ''Date'', ''Special Invoice Credit'' AS PerformanceItemName, COUNT(*) AS CountofTransaction, SUM(IhInvoiceAmount * ihexchangerate)
AS ''Amount''
FROM         dbo.losSpecialInvoiceHeader AS losSpecialInvoiceHeader_1
WHERE     (IhCancelled = 0) AND (IhProforma = 0) AND (ihTransFinished = 1) AND (IhCashInvoice = 0) AND (ihNoofOCDetails = 0)
GROUP BY IhInvoiceDate'
GO
/****** Object:  StoredProcedure [dbo].[spGodownLocationTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownLocationTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by : Kishore
-- Created on : 25/08/2003
-- Comments     : This sp updates the location wise stock in total stock verification
-------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spGodownLocationTotalStockVerification] (@intItemId as int,
@intGodownId as int,
@intSvdId as int,
@dtUpdate as DateTime,
@intArrivalDetailId as int OUTPUT,
@intIssueDetailId as int OUTPUT) AS
Begin
Declare @numSalesQty as Numeric(18, 8)
Declare @numVerifiedQty as Numeric(18, 3)
Declare @intLocationId as int
Declare @numCurLocationStock as Numeric(18, 3)
Set NoCount off
-- open the cursor to loop through the locations
Declare curLocations Cursor for
SELECT ladLocationId, ladItemQty FROM loiLocationArrivalDetails
WHERE ladGodownId = @intGodownId
AND ladTransId = @intSvdId
AND ladInterfaceId = 8010
AND ladCancel = 1
Open curLocations
Fetch Next From curLocations Into @intLocationId, @numVerifiedQty
While @@fetch_status = 0
Begin
-- get the sum qty involved in transactions
-- in this case only special despatch to shop is transacted
SELECT @numSalesQty = SUM(lidItemQty)
FROM loiLocationIssueDetails
WHERE lidTransactionId IN
(SELECT ddDespatchId
FROM meiSpecialDespatchToShopDetail Detail,
meiSpecialDespatchToShopHeader Header
WHERE Detail.ddDespatchId = Header.dhDespatchId
AND Detail.ddGodownId = Header.dhGodownId
AND Detail.ddItemId = @intItemId
AND Header.UpdateTime >= @dtUpdate
AND ddGodownId = @intGodownId)
AND lidGodownId = @intGodownId
AND lidInterfaceId = 5009 -- interfaceid of special despatch to shop
AND lidItemId = @intItemId
AND lidLocationId = @intLocationId
-- make the location stock of specified item at
-- specified location to zero
-- get current location stock
-- first get the currect location stock
SELECT @numCurLocationStock = qty
FROM
(SELECT LocationId, GodownId,
ItemId, SUM(qty) qty
FROM
(SELECT ladLocationId LocationId,
ladGodownId GodownId, ladItemId ItemId , SUM(ladItemQty) qty
FROM loiLocationArrivalDetails
WHERE ladGodownId = @intGodownId
AND ladItemId =  @intItemId
AND ladCancel = 0
AND ladLocationId = @intLocationId
GROUP BY ladLocationId, ladGodownId, ladItemId
UNION ALL
SELECT lidLocationId, lidGodownId, lidItemId, - SUM(lidItemQty)
FROM loiLocationIssueDetails
WHERE lidGodownId = @intGodownId
AND lidItemId = @intItemId
AND lidCancel = 0
AND lidLocationId = @intLocationId
GROUP BY lidLocationId, lidGodownId, lidItemId) a
GROUP BY LocationId, GodownId, ItemId
HAVING SUM(qty) <> 0 ) b,
LOiLocation
WHERE b.LocationId = LOiLocation.lLocationId
AND b.GodownId = loiLocation.lGodownId
AND b.ItemId = @intItemId  -- for extra safety
-- if stock > 0, insert to issue details
-- otherwise insert to arrival details
-- to make the net stock zero
If @numCurLocationStock > 0
Begin
INSERT INTO loiLocationIssueDetails
(lidinterfaceid, lidgodownid, lidTransactionId, liddetailid,
lidlocationid, liditemid, liditemqty, lidpackingtypeid,
lidpakingqty, lidcancel, lidadjustment)
VALUES
(8010, @intGodownId, @intSvdId, @intIssueDetailId,
@intLocationId, @intItemId,
ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
Set @intIssueDetailId = @intIssueDetailId + 1
End
Else
Begin
INSERT INTO loiLocationArrivalDetails
(ladinterfaceid, ladgodownid, ladtransid, laddetailid,
ladlocationid, laditemid, laditemqty, ladpackingtypeid,
ladpakingqty, ladcancel, ladadjustment)
VALUES
(8010, @intGodownId, @intSvdId, @intArrivalDetailId,
@intLocationId, @intItemId,
ABS(@numCurLocationStock), 1, ABS(@numCurLocationStock), 0, 1)
Set @intArrivalDetailId = @intArrivalDetailId + 1
End
-- now insert to arrival/issue details
If (@numVerifiedQty - @numSalesQty) > 0
Begin
print @intArrivalDetailId
INSERT INTO loiLocationArrivalDetails
(ladinterfaceid, ladgodownid, ladTransId, laddetailid,
ladlocationid, laditemid, laditemqty, ladpackingtypeid,
ladpakingqty, ladcancel, ladadjustment)
VALUES
(8010, @intGodownId, @intSvdId, @intArrivalDetailId,
@intLocationId, @intItemId,
ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 0)
Set @intArrivalDetailId = @intArrivalDetailId + 1
End
Else
Begin
INSERT INTO loiLocationIssueDetails
(lidinterfaceid, lidgodownid, lidTransactionId, liddetailid,
lidlocationid, liditemid, liditemqty, lidpackingtypeid,
lidpakingqty, lidcancel, lidadjustment)
VALUES
(8010, @intGodownId, @intSvdId, @intIssueDetailId,
@intLocationId, @intItemId,
ABS(@numVerifiedQty - @numSalesQty), 1, ABS(@numVerifiedQty - @numSalesQty), 0, 0)
Set @intIssueDetailId = @intIssueDetailId + 1
end
Fetch Next From curLocations Into @intLocationId, @numVerifiedQty
End
Close curLocations
Deallocate curLocations
End' 
END
GO
/****** Object:  View [dbo].[vwForeignShipWiseCostPrice]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwForeignShipWiseCostPrice]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on 		: 12/12/02
-- Modified by		: leo
-- Comments		: v3
-------------------------------------------------------
-- Modified on		: 11/06/2003
-- Modified by          : Kishore
-- Comments		: View modified to take the opening shipmentno and shipmentdate
--                        (On comparison with v2, field names are kept old names
--			  in v2 pbhBillDate is ShipmentDate & pbhBillNo is ShipmentNo)
-------------------------------------------------
				
-- Modified by          : venki02/09/03
-- Comments		: added department field
-------------------------------------------------------
CREATE VIEW [dbo].[vwForeignShipWiseCostPrice] AS
select cdItemID,
case chCostingId when 0 then sshipmentno else pbhBillno end pbhBillNo,
case chCostingId when 0 then sshipmentdate else pbhbilldate end pbhBillDate,
cdCostingPrice ,chDepartmentID
from loacostingdetail ld, loacostingheader lh ,losppurchasebillheader lp, aShipment a
where lh.chCostingID = ld.cdCostingID
and lh.chBillID = lp.pbhBillID
and chCancelled = 0
and sshipmentid = 1'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetDisposal]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetDisposal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetdepreciation]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersAssetdepreciation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--MOdifified by  : Hariharan , Hariharan , Hariharan
-- modified Date : 04/03/2004, 06/04/2004, 16/04/2004
--- pupose     : posting all asset depreciation  information
--  : Included exchangerates string
--  : Modified to Give the Post Group in insertion to MoajournalDetails
--  : Modified by Sreejith on 08/07/2010
--  : Comments:
--				There existed three input parameters including intDepartmentID
--				Exluded intDEpartmentID from the input and declared a dynamic variable with the same name
--				taking the value from depreciationheader
CREATE Procedure [dbo].[spUpdateLedgersAssetdepreciation]
@intassetdepreciationid as int ,
@intcompanyid as int
as
begin
Declare @intdepreciationid as int,
@intDepartmentID as int,---
@strDepreciationNo as varchar(50),
@dtDepreciationDate as datetime,
@intDetailID as int,
@intDepreciationAccountID as int,
@intfixedassetit as int,
@FixedAssetID as int,
@intfixedassetaccid as int,
@intwriteoffrefid as int,
@intconversiondiffaccid as int,
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@strrefNo as varchar(50),
@dtfixedassetDate as datetime,
@intVendorID as int,
@strRemarks as varchar(250),
@numrefamount as numeric(18,2),
@numAssetValue as numeric(18,2),
@numDiffValue as numeric(18,2),
@numdepriamt as numeric(18,2),
@dtutime as datetime,
@numdepRate as numeric(18,9),
@numconsRate as numeric(18,9),
@strexrates as varchar(250),
@numaccamt as numeric(18,2),
@intcurrencyid as int,
@intdepid as int,
@intAssetConversionAccid as int,
@DepreciationAccID as int,
@intdepriciationexpaccid as int,
@DepreciationAmount as numeric(18,9)
SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE
CompanyID = @intCompanyID
SELECT @strDepreciationNo = DepreciationNo,
@dtDepreciationDate = DepreciationDate,
@strRemarks = Remarks,@intFinancialID=FinancialID,
@dtutime=updatetime,@numdepRate = depexrate,@numconsRate = consexrate,
@strexrates = ExchangeRates,@intDepartmentID= DepartmentID---
FROM depreciationheader  WHERE
CompanyID = @intcompanyid and
Cancelled=0 and DepreciationID = @intassetdepreciationid
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
begin
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID,Type, CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtDepreciationDate, @strDepreciationNo,
@strRemarks, @intFinancialID,''ASDP'', @intcurrencyid, @dtDepreciationDate, @dtutime)
set @numdepriamt =0
Declare DepreciationdetailCur cursor for
SELECT dd.DepreciationAccountID,dd.DepreciationAmount,fa.FixedAssetID,
dd.assetAccountID,dd.Depexpaccid FROM depreciationdetail dd,fixedasset fa
where dd.companyid = fa.companyid and fa.FixedAssetID = dd.fixedassetid
and dd.CompanyID = @intCompanyID and dd.DepreciationID = @intassetdepreciationid
open DepreciationdetailCur
fetch next FROM DepreciationdetailCur into @DepreciationAccID, @DepreciationAmount,
@FixedAssetID,@intfixedassetaccid,@intdepriciationexpaccid
while @@Fetch_status =0
begin
exec spConvertequiamount @intDepartmentID , ''d'', @DepreciationAccID, ''a'', @strexrates,
@DepreciationAmount, @numaccamt output, ''''
insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
depamount, PostGroup)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@DepreciationAccID, @DepreciationAmount * @numconsrate, @numaccamt,
@intDepartmentID, @DepreciationAmount * @numdeprate, @intJournalDetailID)
set @intJournalDetailID = @intJournalDetailID +1
exec spConvertequiamount @intDepartmentID , ''d'', @intdepriciationexpaccid, ''a'', @strexrates,
@DepreciationAmount, @numaccamt output, ''''
insert into moajournaldetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
depamount, PostGroup)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdepriciationexpaccid,
@DepreciationAmount * @numconsrate, @numaccamt, @intDepartmentid,
@DepreciationAmount * @numdeprate, @intJournalDetailID-1)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DepreciationdetailCur into @DepreciationAccID, @DepreciationAmount,
@FixedAssetID,@intfixedassetaccid, @intdepriciationexpaccid
end
close DepreciationdetailCur
deallocate DepreciationdetailCur
end
update depreciationheader set postED =1 WHERE CompanyID = @intCompanyID and
DepreciationID = @intassetdepreciationid
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGTransGodownStock]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGTransGodownStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 		: 10/06/2003
-- Modified by		: Kishore
-- Comments		: Added the IsNull condition for gdtItemBadQty in the cursor opening
--			  (On comparison with v2)
-- Modified on 		: 17/09/2003
-- Modified by		: venki
-- Comments		: Adding empty row for stock table if itemcout is 0
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE PROCEDURE [dbo].[SpUpdateGTransGodownStock](@despatchid int,@Godownid int,@process char(1)) AS
Begin
	--Altered by lawrence for removing location 19-Dec-02
	declare
	@cur_despatchid int,
	@cur_godownid int,
	@cur_itemid int,
	@cur_shipmentid int, --Lawrence includeded shipmentid 27-Dec-02
	@cur_itembadqty numeric(18,3),
	@cur_itemgoodqty numeric(18,3),
	@intcount int
	set nocount on
	set @intcount=0
	declare cursor_Detail  cursor for
	select gtdDespatchID, gtdgodownid, gtditemid,
	isnull(gtditembadqty, 0) gtdItemBadQty,
	gtditemgoodqty, gtdShipmentID
	from MeiGodownTransferDetail
	where gtdDespatchID = @despatchid
	and gtdgodownid = @Godownid
	open cursor_Detail
	fetch next from cursor_Detail into
	@cur_despatchid, @cur_godownid, @cur_itemid,
	@cur_itembadqty, @cur_itemgoodqty,@cur_shipmentid
	while @@fetch_status = 0
	begin
			--added by venki forinserting empty row if itemcount=0
			select @intCount = count(*) from moigodownStock
			where gsitemid = @cur_Itemid and gsgodownid= @godownid
			if @intCount =0
			Begin
				insert moigodownStock (gsgodownID,gsStockDate, gsShipmentID, gsItemID,
				gsOpeningStock, gsStock, gsOpeningBadStock, gsBadStock)
				Select @godownid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
			End
			--
		if @process = ''R''
			update moigodownstock set gsstock = gsstock + @cur_itemgoodqty,
			gsbadstock = gsbadstock + @cur_itembadqty
			where gsitemid = @cur_itemid and gsgodownid = @cur_godownid
			and gsShipmentID=@cur_shipmentid
		if @process = ''F''
		begin
			update moigodownstock set gsstock = gsstock - @cur_itemgoodqty,
			gsbadstock = gsbadstock - @cur_itembadqty
			where gsitemid = @cur_itemid and gsgodownid = @cur_godownid
			and gsShipmentID=@cur_shipmentid
		end
		fetch next from cursor_Detail into
		@cur_despatchid, @cur_godownid, @cur_itemid,
		@cur_itembadqty, @cur_itemgoodqty,@cur_shipmentid
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownWriteOff]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownWriteOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified By 	: Kishore
-- Modified on  : 05/06/2003
-- Modified by	: Kishore
-- Comments     : Created  on 27/12/2002
--              : Added the @strTransType parameter (05/06/2003)
--                @strTransType : W - Write off
--                                R - Purchas return
--                                A - Asset convertion
-----------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 10/06/2003
-- Comments     : Added the IsNull condition while taking stock
--                (On comparison with v2)
---------------------------------------------------------------------------------------------------------------------------------------
-- Modified by  : venki
-- Modified on  : 17/09/2003
-- Comments     : added  forinserting empty row if itemcount=0
-- Verified by 	    : Hariharan
-- Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE PROCEDURE [dbo].[spUpdateGodownWriteOff] (@WriteOffId int,
		@GodownId int, @Type char(1), @strTransType Char(1))  AS
Begin
	declare
	@cur_woffid int,
	@cur_godownid int,
	@cur_itemid int,
	@cur_ItemGoodQty numeric(18,3),
	@cur_cost numeric(18,2),
	@cur_ShipmentID int,
	@recCount as int,
	@numBadQty as numeric(18, 3),
	@intcount as int
	set nocount on
	set @intcount=0
	declare cursor_Detail  cursor for
	select wdid, wdgodownid, wditemid, wdWriteoffQty, wdcostprice, wdshipmentid
	from loiWriteoffDetail where wdid = @WriteoffID and wdgodownid = @Godownid
	open cursor_Detail
	fetch next from cursor_Detail into
	@cur_woffid, @cur_godownid, @cur_itemid,
	@cur_ItemGoodQty, @cur_cost,  @cur_ShipmentID
	while @@fetch_status = 0
	begin
		--added by venki forinserting empty row if itemcount=0
			select @intCount = count(*) from moigodownStock
			where gsitemid = @cur_Itemid and gsgodownid= @godownid
			if @intCount =0
			Begin
				insert moigodownStock (gsgodownID,gsStockDate, gsShipmentID, gsItemID,
				gsOpeningStock, gsStock, gsOpeningBadStock, gsBadStock)
				Select @godownid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
			End
			--
		-- in write off, take bad qty as transaction qty
		-- in other cases take it as 0
		If @strTransType = ''W''
			Set @numBadQty = @cur_ItemGoodQty
		Else
			Set @numBadQty = 0
			
		if @TYpe=''f''
		Begin
			
			update moigodownstock
			set gsstock = IsNull(gsstock, 0) - @cur_ItemGoodQty,
			gsbadStock = IsNull(gsbadStock, 0) + @numBadQty
			where gsitemid = @cur_itemid
			and gsgodownid = @cur_godownid
			and gsshipmentid = @cur_ShipmentID
		End
		Else	--@type=''r''
		Begin
			update moigodownstock
			set gsstock = IsNull(gsstock, 0) + @cur_ItemGoodQty,
			gsbadStock = IsNull(gsbadStock, 0) - @numBadQty
			where gsitemid = @cur_itemid
			and gsgodownid = @cur_godownid
			and gsshipmentid = @cur_ShipmentID
		End
		fetch next from cursor_Detail into
		@cur_woffid, @cur_godownid, @cur_itemid,
		@cur_ItemGoodQty, @cur_cost,  @cur_ShipmentID
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownVerification]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spUpdateGodownVerification    Script Date: 18/01/2003 9:45:47 PM ******/
--Created By 	: Hariharan
--Created Date  : 02/01/2003
--Comments	: (V3)
--Verified after testing
CREATE proc [dbo].[spUpdateGodownVerification] @VerificationID int,
					@Godownid int, @Type char(1)  as
	declare
	@cur_verid int,
	@cur_godownid int,
	@cur_itemid int,
	@cur_itemgoodqty numeric(18,3),
	@cur_itemBadQty numeric(18,3),
	@cur_availgoodqty numeric(18,3),
	@cur_availBadQty numeric(18,3),
	@cur_packingtypeid int,
	@cur_cost numeric(18,2),
	@cur_ShipmentID int,
	@recCount as int
	--sp_help loistockverificationdetail
	set nocount on
	declare cursor_Detail  cursor for
		select svdid, svdgodownid, svditemid, svdVerifiedStock, svdVerifiedBadStock,
		svdcostprice, svdshipmentid, svdAvailStock, svdAvailBadStock from
		loiStockVerificationDetail where svdid = @VerificationID
		and svdgodownid = @Godownid
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_verid, @cur_godownid, @cur_itemid,
		@cur_itemgoodqty, @cur_itemBadQty, @cur_cost,  @cur_ShipmentID,
		@cur_availgoodqty, @cur_availBadqty
	while @@fetch_status = 0
	begin
		if @TYpe = ''f''  -- (fresh)
		Begin
			select @recCount = count(*) from moiGodownStock
					where gsitemid = @cur_itemid
					and gsgodownid = @cur_Godownid
			if @recCount = 0
			begin
				insert moiGodownStock(gsGodownID, gsShipmentID, gsItemID,
					gsStock, gsbadStock, gsItemCost, gsstockdate)
					select @cur_GodownID, @cur_Shipmentid, @cur_ItemID,
					@cur_itemgoodqty, @cur_itembadqty, @cur_Cost, getdate()
			end
			else
			begin
				update moiGodownStock set gsstock =  @cur_itemgoodqty,
					gsbadStock = @cur_itemBadQty where gsitemid = @cur_itemid and
					gsgodownid = @cur_godownid
			end
		End
		Else	--@type=''r'' (reverse)
		Begin
			update moiGodownStock set gsstock = gsstock  + @cur_availgoodqty - @cur_itemgoodqty,
				gsbadStock = gsbadStock + @cur_availBadQty - @cur_itemBadQty where
				gsitemid = @cur_itemid and gsgodownid = @cur_godownid
		End
		fetch next from cursor_Detail into
			@cur_verid, @cur_godownid, @cur_itemid,
			@cur_itemgoodqty, @cur_itemBadQty, @cur_cost,  @cur_ShipmentID,
			@cur_availgoodqty, @cur_availBadqty
	end
	close cursor_Detail
	deallocate cursor_Detail
	return 0' 
END
GO
/****** Object:  View [dbo].[vwShopItemSales]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSales]'))
EXEC dbo.sp_executesql @statement = N'
--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
---------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopItemSales] AS
-- 1
select
posditemid,
convert(numeric(18, 2), posdActualUnitPrice *  poshExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), posdActualUnitPrice *  poshDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), posdActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18, 2), (posdUnitPrice /CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshExchangeRate) cUnitPrice,   --RefNo:1
convert(numeric(18, 2), (posdUnitPrice / CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshDepExRate) dUnitPrice,     --RefNo:1
convert(numeric(18, 2), (posdUnitPrice / 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,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount ,
convert(numeric(18, 2),posdActualUnitPrice * posdquantity) ActualAmount,--sree
convert(numeric(18, 2),posdActualUnitPrice * poshExchangeRate *posdquantity) cActualAmount,  --sree
convert(numeric(18, 2),posdActualUnitPrice * poshDepExRate *posdquantity) dActualAmount,     --sree
poshcustomerid
from
losposdetail, losposheader
where
poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0
union all
---- 2
--select
-- iditemid, convert(numeric(18,2),
-- (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,
-- convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,
-- convert(numeric(18,2), (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, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
-- convert(numeric(18, 2),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, 2), idActualUnitPrice *  ihexchangerate) cActualUnitPrice,  --sree
convert(numeric(18, 2), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), idActualUnitPrice) ActualUnitPrice,  --sree
case when (idquantity<>0) then convert(numeric(18,2),(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,2),(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
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,
convert(numeric(18, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate) dAmount,
convert(numeric(18, 2),idActualUnitPrice * idquantity) ActualAmount,--sree
convert(numeric(18, 2),idActualUnitPrice * ihexchangerate *idquantity) cActualAmount,  --sree
convert(numeric(18, 2),idActualUnitPrice * ihDepExRate *idquantity) dActualAmount,     --sree
ih.ihCustomerID
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, 2), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), sedActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1
convert(numeric(18,2),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1
convert(numeric(18,2),(sedUnitPrice / 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,
convert(numeric(18, 2),sedUnitPrice)  Amount,convert(numeric(18, 2),sedUnitPrice * sehExchangeRate) cAmount,
convert(numeric(18, 2),sedUnitPrice * sehDepExRate) dAmount,
convert(numeric(18, 2),sedActualUnitPrice * sedquantity) ActualAmount,--sree
convert(numeric(18, 2),sedActualUnitPrice * sehExchangeRate *sedquantity) cActualAmount,  --sree
convert(numeric(18, 2),sedActualUnitPrice * sehDepExRate *sedquantity) dActualAmount,     --sree
0
from
losposexchangeheader,losposexchangedetail
where
sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
union all
-- 4
select
iditemid,
convert(numeric(18, 2), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), idActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,   --RefNo:1
convert(numeric(18,2),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1
convert(numeric(18,2),(idUnitPrice / 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,
convert(numeric(18, 2),idUnitPrice) Amount, convert(numeric(18, 2),idUnitPrice * ihExchangeRate)  cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate)  Amount,
convert(numeric(18, 2),idActualUnitPrice * reqqty) ActualAmount,--sree
convert(numeric(18, 2),idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree
convert(numeric(18, 2),idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree
IhCustomerID
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, 2), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), idActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,            --RefNo:1
convert(numeric(18,2), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,               --RefNo:1
convert(numeric(18,2), (idUnitPrice / 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,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount,
convert(numeric(18, 2),-idActualUnitPrice * reqqty) ActualAmount,--sree
convert(numeric(18, 2),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree
convert(numeric(18, 2),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree
IhCustomerID
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,2), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) cUnitPrice ,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehDepExRate) dUnitPrice,
convert(numeric(18,2), -(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, 2),- sedUnitPrice) Amount,
convert(numeric(18, 2),- sedUnitPrice * sehexchangerate)  cAmount,
convert(numeric(18, 2),- 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, 2), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), sedActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehExchangeRate) cUnitPrice ,   --RefNo:1
convert(numeric(18,2), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehDepExRate) dUnitPrice,       --RefNo:1
convert(numeric(18,2), -(sedUnitPrice / 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,
convert(numeric(18, 2),- sedUnitPrice) Amount,
convert(numeric(18, 2),- sedUnitPrice * sehexchangerate)  cAmount,
convert(numeric(18, 2),- sedUnitPrice * sehDepExRate)  dAmount ,
convert(numeric(18, 2),-sedActualUnitPrice * sedExchangeQty) ActualAmount,--sree
convert(numeric(18, 2),-sedActualUnitPrice * sehExchangeRate *sedExchangeQty) cActualAmount,  --sree
convert(numeric(18, 2),-sedActualUnitPrice * sehDepExRate *sedExchangeQty) dActualAmount ,    --sree
0
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, 2), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), idActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,     --RefNo:1
convert(numeric(18,2), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,         --RefNo:1
convert(numeric(18,2), -(idUnitPrice / 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,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount,
convert(numeric(18, 2),-idActualUnitPrice * reqqty) ActualAmount,--sree
convert(numeric(18, 2),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree
convert(numeric(18, 2),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree
IhCustomerID
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,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhExchangeRate) cUnitPrice,
-- convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhDepExRate) dUnitPrice,
-- convert(numeric(18,2),( 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, 2),-grndUnitPrice) Amount,convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate) cAmount,
-- convert(numeric(18, 2),-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, 2), idActualUnitPrice *  grnhExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), idActualUnitPrice *  grnhDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), idActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2),( GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhExchangeRate) cUnitPrice,    --RefNo:1
convert(numeric(18,2),( GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhDepExRate) dUnitPrice,        --RefNo:1
convert(numeric(18,2),( GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END) ) 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,
convert(numeric(18, 2),-grndUnitPrice) Amount,convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate) cAmount,
convert(numeric(18, 2),-grndUnitPrice * grnhDepExRate) dAmount,
convert(numeric(18, 2),-idActualUnitPrice * GRNDQuantity) ActualAmount,--sree
convert(numeric(18, 2),-idActualUnitPrice * grnhExchangeRate *GRNDQuantity) cActualAmount,  --sree
convert(numeric(18, 2),-idActualUnitPrice * grnhDepExRate *GRNDQuantity) dActualAmount,     --sree
GrnhCustomerID
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, 2), repinvdsellrate *  serinvhcmpexrate) cActualUnitPrice,  --sree
convert(numeric(18, 2), repinvdsellrate *  seinvhDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), repinvdsellrate) ActualUnitPrice,  --sree
convert(numeric(18,2) , repinvdrate  *  serinvhcmpexrate) cUnitPrice,
convert(numeric(18,2) , repinvdrate  *  seinvhDepExRate) dUnitPrice,
convert(numeric(18,2) , repinvdrate ) 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,
convert(numeric(18, 2),RepInvDRate * repinvpackqty) Amount,
convert(numeric(18, 2),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,
convert(numeric(18, 2),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,
convert(numeric(18, 2),repinvdsellrate * repinvdqty) ActualAmount,--sree
convert(numeric(18, 2),repinvdsellrate * serinvhcmpexrate *repinvdqty) cActualAmount,  --sree
convert(numeric(18, 2),repinvdsellrate * seinvhDepExRate *repinvdqty) dActualAmount ,    --sree
serinvhCustomerId
from
losinvoicedpartsreplacedetails, losserviceinvheader
where
serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND
serinvhcancelled = 0
union all
-- 9
select
reditemid,
convert(numeric(18, 2), redActualUnitPrice *  rehExchangeRate) cActualUnitPrice,  --sree
convert(numeric(18, 2), redActualUnitPrice *  rehDepExRate) dActualUnitPrice,   --sree
convert(numeric(18, 2), redActualUnitPrice) ActualUnitPrice,  --sree
convert(numeric(18,2),(redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END) * rehExchangeRate) cUnitPrice,                       --RefNo:1
convert(numeric(18,2), (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END)  *  rehDepExRate) dUnitPrice, --RefNo:1
convert(numeric(18,2), (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, 2),redUnitPrice) Amount,convert(numeric(18, 2),redUnitPrice * rehExchangeRate) cAmount,
convert(numeric(18, 2),redUnitPrice * rehDepExRate) Amount,
convert(numeric(18, 2),redActualUnitPrice * redquantity) ActualAmount,--sree
convert(numeric(18, 2),redActualUnitPrice * rehExchangeRate *redquantity) cActualAmount,  --sree
convert(numeric(18, 2),redActualUnitPrice * rehDepExRate *redquantity) dActualAmount,     --sree
rehcustomerid
from
losExportDetail, losExportHeader
where
rehExportID = redExportID and rehShopID = redShopID AND
rehCancelled = 0 and rehproforma = 0 and rehtype = ''i'''
GO
/****** Object:  View [dbo].[vwShopItemSalesWithCustomerAndPack]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesWithCustomerAndPack]'))
EXEC dbo.sp_executesql @statement = N'
--Created By                   : Benzigar S D
--Created On                   : 06-05-2008
--Comments                     : To Show shop item details with customer and Packing type
CREATE VIEW [dbo].[vwShopItemSalesWithCustomerAndPack]  AS
-- 1
select
posditemid,
case  posdquantity when 0 then 0 else
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) end cUnitPrice,
case  posdquantity when 0 then 0 else
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) end dUnitPrice,
case  posdquantity when 0 then 0 else
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) end posdUnitPrice,
posdquantity,posdRateType, poshBilldate,poshbillID,
poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,
posdcostprice * poshExchangeRate ccostprice, ''S'' as type,
case posdquantity when 0 then 0 else
((posdUnitPrice / posdquantity) - posdcostprice) end  margin,
case posdquantity when 0 then 0 else
((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate end rgin,
case posdquantity when 0 then 0 else
((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate end cmargin,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount,
posdpackingtypeid Packingtypeid,
poshCustomername Customername, poshcustomerid CustomerID
from
losposdetail, losposheader
where
poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0
union all
-- 2
select
iditemid,case  idquantity when 0 then 0 else convert(numeric(18,2),
(idUnitPrice / idquantity)  *  ihExchangeRate)end  cUnitPrice,
case  idquantity when 0 then 0 else
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate)end  dUnitPrice,
case  idquantity when 0 then 0 else
convert(numeric(18,2), (idUnitPrice / idquantity)) end  posdUnitPrice,
idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,
idcostprice * ihDepExRate,idcostprice * ihExchangeRate, ''S'',
case  idquantity when 0 then 0 else
((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) end margin,
case  idquantity when 0 then 0 else
((idUnitPrice / idquantity) - idcostprice) * ihDepExRate end dmargin,
case  idquantity when 0 then 0 else
((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate end cmargin,
convert(numeric(18, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate) dAmount,
idpackingtypeid PackingTypeid,
acu.Customername Customername,ihCustomerID CustomerID
from
losinvoiceheader ih, losinvoicedetail invd,acustomermaster acu
where
ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND
IHCANCELLED = 0 and ihproforma = 0 and ihtype = ''i''  and ih.ihcustomerid=acu.customerid
union all
--3
select
seditemid,
case sedquantity when 0 then 0 else
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehExchangeRate) end cUnitPrice,
case sedquantity when 0 then 0 else
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehDepExRate)end  dUnitPrice,
case sedquantity when 0 then 0 else
convert(numeric(18,2),(sedUnitPrice / sedquantity) ) end UnitPrice,
sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,
sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, ''S'',
case sedquantity when 0 then 0 else
((sedUnitPrice / sedquantity)  - sedcostprice) end margin,
case sedquantity when 0 then 0 else
((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate end  dmargin,
case sedquantity when 0 then 0 else
((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate end cmargin,
convert(numeric(18, 2),sedUnitPrice)  Amount,convert(numeric(18, 2),sedUnitPrice * sehExchangeRate) cAmount,
convert(numeric(18, 2),sedUnitPrice * sehDepExRate) dAmount,
sedpackingtypeid Packingtypeid,
sehexchangerName Customername,'''' CustomerID
from
losposexchangeheader,losposexchangedetail
where
sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
union all
-- 4
select
iditemid,case reqqty when 0 then 0 else
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihExchangeRate) end cUnitPrice,
case reqqty when 0 then 0 else
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihDepExRate) end dUnitPrice,
case reqqty when 0 then 0 else
convert(numeric(18,2),(idUnitPrice / reqqty)) end UnitPrice  ,reqqty,
idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''S'',
case reqqty when 0 then 0 else
((idUnitPrice / reqqty) -idcostprice) end margin,
case reqqty when 0 then 0 else
((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate end dmargin ,
case reqqty when 0 then 0 else
((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate end cmargin,
convert(numeric(18, 2),idUnitPrice) Amount, convert(numeric(18, 2),idUnitPrice * ihExchangeRate)  cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate)  Amount,
idpackingtypeid Packingtypeid,
acu.customername Customername,ihCustomerID CustomerID
from
losspecialinvoicedetail, losspecialinvoiceheader, acustomermaster acu
where
ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND
IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0
and IhTransFinished = 1  and ihcustomerid=acu.customerid
union all
-- 5
select
seditemid,
case sedquantity when 0 then 0 else
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) end cUnitPrice ,
case sedquantity when 0 then 0 else
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehDepExRate) end dUnitPrice,
case sedquantity when 0 then 0 else
convert(numeric(18,2), -(sedUnitPrice / sedquantity)) end UnitPrice,
-sedExchangeQty, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,
sehShopID, sedcostprice, sedcostprice * sehDepExRate, sedcostprice * sehExchangeRate, ''R'' ,
case sedquantity when 0 then 0 else
-((sedUnitPrice / sedquantity) - sedcostprice) end margin,
case sedquantity when 0 then 0 else
-((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate end dmargin,
case sedquantity when 0 then 0 else
-((sedUnitPrice / sedquantity)  - sedcostprice) *  sehExchangeRate end cmargin,
convert(numeric(18, 2),- sedUnitPrice) Amount,
convert(numeric(18, 2),- sedUnitPrice * sehexchangerate)  cAmount,
convert(numeric(18, 2),- sedUnitPrice * sehDepExRate)  dAmount,
sedpackingtypeid Packingtypeid,
sehExchangerName CustomerName,'''' Customerid
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,  case reqqty when 0 then 0 else
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate)end cUnitPrice,
case reqqty when 0 then 0 else
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihDepExRate)end dUnitPrice,
case reqqty when 0 then 0 else
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) end UnitPrice, reqqty,
idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''R'',
case reqqty when 0 then 0 else
-((idUnitPrice / reqqty) - idcostprice) end margin,
case reqqty when 0 then 0 else
-((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate end dmargin ,
case reqqty when 0 then 0 else
-((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate end cmargin,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount,
idpackingtypeid Packingtypeid,
acu.customername Customername,ihCustomerID CustomerID
from
losspecialinvoicedetail,losspecialinvoiceheader,acustomermaster acu
where
ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 and ihcustomerid=acu.customerid
union all
-- 7
-- (- Qty has to be minus so when multiplying - * - =+ so i am removing the - on values )
--venkitesh 150403
select
grnditemid, case GRNDQuantity when 0 then 0 else
convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhExchangeRate) end  cUnitPrice,
case GRNDQuantity when 0 then 0 else
convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhDepExRate)end dUnitPrice,
case GRNDQuantity when 0 then 0 else
convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity) ) end UnitPrice,
-GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,
GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,
grncostprice * grnhExchangeRate, ''R'' as type,
case GRNDQuantity when 0 then 0 else
((GRNDUnitPrice / GRNDQuantity) - grncostprice) end margin,
case GRNDQuantity when 0 then 0 else
((GRNDUnitPrice / GRNDQuantity) - grncostprice) * grnhDepExRate end dmargin,
case GRNDQuantity when 0 then 0 else
((GRNDUnitPrice / GRNDQuantity) - grncostprice) *  grnhExchangeRate end cmargin,
convert(numeric(18, 2),-grndUnitPrice) Amount,convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate) cAmount,
convert(numeric(18, 2),-grndUnitPrice * grnhDepExRate) dAmount,
'''' Packingtypeid,
acu.customername Customername,grnhCustomerID CustomerID
from
losgoodsreturnnoteheader, losgoodsreturnnotedetail,acustomermaster acu
where
GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and
grnhShopid =  GRNDShopid AND GrnhCancel = 0 and grnhcustomerid=acu.customerid
UNION ALL
-- 8
select
repinvdpartsid, convert(numeric(18,2) , repinvdrate  *  serinvhcmpexrate) cUnitPrice,
convert(numeric(18,2) , repinvdrate  *  seinvhDepExRate) dUnitPrice,
convert(numeric(18,2) , repinvdrate ) UnitPrice, repinvdqty, 0 as ratetype, serinvhdate ,
serinvhid , serinvNo , serinvhShopid, repinvdcostprice, repinvdcostprice *  seinvhDepExRate,
repinvdcostprice * serinvhcmpexrate, ''b'',
(repinvdrate - repinvdcostprice) margin,
(repinvdrate - repinvdcostprice) *  seinvhDepExRate dmargin,
(repinvdrate  - repinvdcostprice) *  serinvhcmpexrate cmargin,
convert(numeric(18, 2),RepInvDRate * repinvpackqty) Amount,
convert(numeric(18, 2),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,
convert(numeric(18, 2),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,
repinvpackid Packingtypeid,
acu.customername Customername,'''' CustomerID
from
losinvoicedpartsreplacedetails, losserviceinvheader,acustomermaster acu
where
serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND
serinvhcancelled = 0 and serinvhcustomerid=acu.customerid
union all
-- 9
select
reditemid,case redquantity when 0 then 0 else
convert(numeric(18,2), (redUnitPrice / redquantity) * rehExchangeRate)end cUnitPrice,
case redquantity when 0 then 0 else
convert(numeric(18,2), (redUnitPrice / redquantity)  *  rehDepExRate)end dUnitPrice,
case redquantity when 0 then 0 else
convert(numeric(18,2), (redUnitPrice / redquantity)) end posdUnitPrice,
redquantity, redRateType, rehExportDate, rehExportID, rehExportNo, rehShopid, redcostprice,
redcostprice * rehDepExRate, redcostprice * rehExchangeRate, ''S'',
case redquantity when 0 then 0 else
((redUnitPrice / redquantity) * rehExchangeRate - redcostprice)end margin,
case redquantity when 0 then 0 else
((redUnitPrice / redquantity) - redcostprice) * rehDepExRate end dmargin,
case redquantity when 0 then 0 else
((redUnitPrice / redquantity) - redcostprice) * rehExchangeRate end cmargin,
convert(numeric(18, 2),redUnitPrice) Amount,convert(numeric(18, 2),redUnitPrice * rehExchangeRate) cAmount,
convert(numeric(18, 2),redUnitPrice * rehDepExRate) Amount,
redpckingtypeid Packingtypeid,
acu.customername Customername,'''' CustomerID
from
losExportDetail, losExportHeader, acustomermaster acu
where
rehExportID = redExportID and rehShopID = redShopID AND
rehCancelled = 0 and rehproforma = 0 and rehtype = ''i'' and  rehcustomerid=acu.customerid'
GO
/****** Object:  View [dbo].[vwshopitemsalesWithActualPrice]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopitemsalesWithActualPrice]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------
--Created On                  : 16 May 2009
--Created by                  : Shine Das
--Comments                    : The view is created by just copying the code from
--- "vwShopItemSales" and added cActualUnitPrice, dActualUnitPrice, posdActualUnitPrice.
--  The reason is to view Actual Amount of a sale. (i.e amount can be edited at the time
-- of sale. So some time actual amount will be different from selling amount). This
-- View is used to track these changes
----------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwshopitemsalesWithActualPrice] as
-----------------------------------------1
select
posditemid,ItemDescription,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) cUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) dUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) posdUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshExchangeRate) cActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice) *  poshDepExRate) dActualUnitPrice,
convert(numeric(18, 2), (posdActualUnitPrice)) posdActualUnitPrice,
posdquantity,posdRateType, poshBilldate,poshbillID,
poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,
posdcostprice * poshExchangeRate ccostprice, ''S'' as type,
((posdUnitPrice / posdquantity) - posdcostprice) margin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount
from losposdetail, losposheader,aitem
where poshBillid = posdBillid and ItemID=posditemid and poshShopid = posdshopid AND POSHCANCELLED = 0
--------------------------------------------------------------
UNION ALL
--------------------------------------------------------------- 2
select
iditemid, ItemDescription,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity))  posdUnitPrice,
convert(numeric(18,2), (idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2), (idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2), (idActualUnitPrice))  posdActualUnitPrice,
idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,
idcostprice * ihDepExRate,idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) margin,
((idUnitPrice / idquantity) - idcostprice) * ihDepExRate  dmargin,
((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate) dAmount
from losinvoiceheader ih, losinvoicedetail invd, aitem
where ih.ihInvoiceid = invd.idInvoiceid  and itemid=invd.iditemid and ih.ihshopid = invd.idshopid AND
IHCANCELLED = 0 and ihproforma = 0 and ihtype = ''i''
----------------------------------------------------------------
UNION ALL
----------------------------------------------------------------3
select
seditemid,ItemDescription,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehExchangeRate) cUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehDepExRate) dUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity))  UnitPrice,
convert(numeric(18,2),(sedActualUnitPrice) * sehExchangeRate) cActualUnitPrice,
convert(numeric(18,2),(sedActualUnitPrice) * sehDepExRate) dActualUnitPrice,
convert(numeric(18,2),(sedActualUnitPrice)) ActualUnitPrice,
sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,
sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, ''S'',
((sedUnitPrice / sedquantity)  - sedcostprice) margin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate  cmargin,
convert(numeric(18, 2),sedUnitPrice)  Amount,convert(numeric(18, 2),sedUnitPrice * sehExchangeRate) cAmount,
convert(numeric(18, 2),sedUnitPrice * sehDepExRate) dAmount
from losposexchangeheader,losposexchangedetail,aitem
where itemid=seditemid and  sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
---------------------------------------------------------------
UNION ALL
---------------------------------------------------------------4
select
iditemid, ItemDescription,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)) UnitPrice,
convert(numeric(18,2),(idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2),(idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2),(idActualUnitPrice)) ActualUnitPrice,
reqqty, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / reqqty) -idcostprice) margin,
((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate dmargin ,
((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount, convert(numeric(18, 2),idUnitPrice * ihExchangeRate)  cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate)  Amount
from losspecialinvoicedetail, losspecialinvoiceheader,aitem
where  itemid=iditemid and 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, ItemDescription,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) UnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)) ActualUnitPrice,
reqqty,idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''R'',
-((idUnitPrice / reqqty) - idcostprice) margin,
-((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,
-((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount
from losspecialinvoicedetail,losspecialinvoiceheader,aitem
where itemid=iditemid and ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 0 and ihproforma = 0 and ihTransFinished = 1 and ihNoofOCDetails<>0
---------------------------------------------------------------
UNION ALL
---------------------------------------------------------------5
select
seditemid, ItemDescription,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) cUnitPrice ,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehDepExRate) dUnitPrice,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)) UnitPrice,
convert(numeric(18,2), -(sedActualUnitPrice) * sehExchangeRate) cActualUnitPrice,
convert(numeric(18,2), -(sedActualUnitPrice) * sehDepExRate) dActualUnitPrice,
convert(numeric(18,2), -(sedActualUnitPrice)) ActualUnitPrice,
-sedExchangeQty, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,
sehShopID, sedcostprice, sedcostprice * sehDepExRate, sedcostprice * sehExchangeRate, ''R'' ,
-((sedUnitPrice / sedquantity) - sedcostprice) margin,
-((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,
-((sedUnitPrice / sedquantity)  - sedcostprice) *  sehExchangeRate cmargin,
convert(numeric(18, 2),- sedUnitPrice) Amount,
convert(numeric(18, 2),- sedUnitPrice * sehexchangerate)  cAmount,
convert(numeric(18, 2),- sedUnitPrice * sehDepExRate)  dAmount
from losposexchangeheader, losposexchangedetail,aitem
where itemid=seditemid and  sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  =  ''B'' and sedexchangeqty>0
---------------------------------------------------------------
UNION ALL
---------------------------------------------------------------6  Special invoice return
select
iditemid,ItemDescription,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) UnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)  *  ihExchangeRate) cActualUnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)  *  ihDepExRate) dActualUnitPrice,
convert(numeric(18,2), -(idActualUnitPrice)) ActualUnitPrice,
reqqty, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''R'',
-((idUnitPrice / reqqty) - idcostprice) margin,
-((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,
-((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount
from losspecialinvoicedetail,losspecialinvoiceheader,aitem
where itemid=iditemid and ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and
idratetype = 1 and ihproforma = 0 and ihTransFinished = 1
---------------------------------------------------------------
UNION ALL
---------------------------------------------------------------
----------------------Section 7 & 8 Avoided Caz there is no Actual-price concept in the tables
-------------------------------------------------------------------------------------9
select
reditemid, ItemDescription,
convert(numeric(18,2), (redUnitPrice / redquantity) * rehExchangeRate) cUnitPrice,
convert(numeric(18,2), (redUnitPrice / redquantity)  *  rehDepExRate) dUnitPrice,
convert(numeric(18,2), (redUnitPrice / redquantity))  posdUnitPrice,
convert(numeric(18,2), (redActualUnitPrice) * rehExchangeRate) cActualUnitPrice,
convert(numeric(18,2), (redActualUnitPrice)  *  rehDepExRate) dActualUnitPrice,
convert(numeric(18,2), (redActualUnitPrice))  posdActualUnitPrice,
redquantity, redRateType, rehExportDate, rehExportID, rehExportNo, rehShopid, redcostprice,
redcostprice * rehDepExRate, redcostprice * rehExchangeRate, ''S'',
((redUnitPrice / redquantity) * rehExchangeRate - redcostprice) margin,
((redUnitPrice / redquantity) - redcostprice) * rehDepExRate  dmargin,
((redUnitPrice / redquantity) - redcostprice) * rehExchangeRate cmargin,
convert(numeric(18, 2),redUnitPrice) Amount,convert(numeric(18, 2),redUnitPrice * rehExchangeRate) cAmount,
convert(numeric(18, 2),redUnitPrice * rehDepExRate) Amount
from losExportDetail, losExportHeader,aitem
where itemid=redItemID and rehExportID = redExportID and rehShopID = redShopID AND
rehCancelled = 0 and rehproforma = 0 and rehtype = ''i''
---------------------------------------------------'
GO
/****** Object:  View [dbo].[vwShopItemSalesGstSeparately]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesGstSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwShopItemSalesforSeasonalPrediction]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesforSeasonalPrediction]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By : Sebin.T.S
--Modified On : 14/05/09
CREATE VIEW [dbo].[vwShopItemSalesforSeasonalPrediction] AS
-- 1
select
posditemid,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshExchangeRate) cUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity) *  poshDepExRate) dUnitPrice,
convert(numeric(18, 2), (posdUnitPrice / posdquantity)) posdUnitPrice,
posdquantity,posdRateType, poshBilldate,poshbillID,
poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,
posdcostprice * poshExchangeRate ccostprice, ''S'' as type,
((posdUnitPrice / posdquantity) - posdcostprice) margin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,
((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,
convert(numeric(18, 2),posdUnitPrice) Amount,convert(numeric(18, 2),posdUnitPrice * poshExchangeRate) cAmount,
convert(numeric(18, 2),posdUnitPrice * poshDepExRate) dAmount
from
losposdetail, losposheader
where
poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0
union all
-- 2
select
iditemid, convert(numeric(18,2),
(idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), (idUnitPrice / idquantity))  posdUnitPrice,
idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,
idcostprice * ihDepExRate,idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) margin,
((idUnitPrice / idquantity) - idcostprice) * ihDepExRate  dmargin,
((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount,convert(numeric(18, 2),idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),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''
union all
--3
select
seditemid,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehExchangeRate) cUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) * sehDepExRate) dUnitPrice,
convert(numeric(18,2),(sedUnitPrice / sedquantity) ) UnitPrice,
sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,
sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, ''S'',
((sedUnitPrice / sedquantity)  - sedcostprice) margin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,
((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate  cmargin,
convert(numeric(18, 2),sedUnitPrice)  Amount,convert(numeric(18, 2),sedUnitPrice * sehExchangeRate) cAmount,
convert(numeric(18, 2),sedUnitPrice * sehDepExRate) dAmount
from
losposexchangeheader,losposexchangedetail
where
sedExchangeid = sehExchangeID and sedShopID = sehShopid and
SEHCANCELLED = 0 and sedbillorexchange  = ''E''
union all
-- 4
select
iditemid, convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2),(idUnitPrice / reqqty)) UnitPrice  ,reqqty,
idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''S'',
((idUnitPrice / reqqty) -idcostprice) margin,
((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate dmargin ,
((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),idUnitPrice) Amount, convert(numeric(18, 2),idUnitPrice * ihExchangeRate)  cAmount,
convert(numeric(18, 2),idUnitPrice * ihDepExRate)  Amount
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,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) UnitPrice, reqqty,
idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''R'',
-((idUnitPrice / reqqty) - idcostprice) margin,
-((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,
-((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount
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
select
seditemid, convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) cUnitPrice ,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)  *  sehDepExRate) dUnitPrice,
convert(numeric(18,2), -(sedUnitPrice / sedquantity)) UnitPrice,
-sedExchangeQty, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,
sehShopID, sedcostprice, sedcostprice * sehDepExRate, sedcostprice * sehExchangeRate, ''R'' ,
-((sedUnitPrice / sedquantity) - sedcostprice) margin,
-((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,
-((sedUnitPrice / sedquantity)  - sedcostprice) *  sehExchangeRate cmargin,
convert(numeric(18, 2),- sedUnitPrice) Amount,
convert(numeric(18, 2),- sedUnitPrice * sehexchangerate)  cAmount,
convert(numeric(18, 2),- sedUnitPrice * sehDepExRate)  dAmount
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,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) cUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihDepExRate) dUnitPrice,
convert(numeric(18,2), -(idUnitPrice / reqqty)  *  ihExchangeRate) UnitPrice, reqqty,
idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,
idcostprice * ihDepExRate, idcostprice * ihExchangeRate, ''R'',
-((idUnitPrice / reqqty) - idcostprice) margin,
-((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,
-((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,
convert(numeric(18, 2),-idUnitPrice) Amount, convert(numeric(18, 2),-idUnitPrice * ihExchangeRate) cAmount,
convert(numeric(18, 2),-idUnitPrice * ihDepExRate) dAmount
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,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhExchangeRate) cUnitPrice,
convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity)  *  grnhDepExRate) dUnitPrice,
convert(numeric(18,2),( GRNDUnitPrice / GRNDQuantity) ) UnitPrice,
-GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,
GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,
grncostprice * grnhExchangeRate, ''R'' as type,
((GRNDUnitPrice / GRNDQuantity) - grncostprice) margin,
((GRNDUnitPrice / GRNDQuantity) - grncostprice) * grnhDepExRate dmargin,
((GRNDUnitPrice / GRNDQuantity) - grncostprice) *  grnhExchangeRate cmargin,
convert(numeric(18, 2),-grndUnitPrice) Amount,convert(numeric(18, 2),-grndUnitPrice * grnhExchangeRate) cAmount,
convert(numeric(18, 2),-grndUnitPrice * grnhDepExRate) dAmount
from
losgoodsreturnnoteheader, losgoodsreturnnotedetail
where
GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and
grnhShopid =  GRNDShopid AND GrnhCancel = 0
UNION ALL
-- 8
select
repinvdpartsid, convert(numeric(18,2) , repinvdrate  *  serinvhcmpexrate) cUnitPrice,
convert(numeric(18,2) , repinvdrate  *  seinvhDepExRate) dUnitPrice,
convert(numeric(18,2) , repinvdrate ) UnitPrice, repinvdqty, 0 as ratetype, serinvhdate ,
serinvhid , serinvNo , serinvhShopid, repinvdcostprice, repinvdcostprice *  seinvhDepExRate,
repinvdcostprice * serinvhcmpexrate, ''b'',
(repinvdrate - repinvdcostprice) margin,
(repinvdrate - repinvdcostprice) *  seinvhDepExRate dmargin,
(repinvdrate  - repinvdcostprice) *  serinvhcmpexrate cmargin,
convert(numeric(18, 2),RepInvDRate * repinvpackqty) Amount,
convert(numeric(18, 2),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,
convert(numeric(18, 2),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount
from
losinvoicedpartsreplacedetails, losserviceinvheader
where
serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND
serinvhcancelled = 0
union all
-- 9
select
reditemid, convert(numeric(18,2),
(redUnitPrice / redquantity) * rehExchangeRate) cUnitPrice,
convert(numeric(18,2), (redUnitPrice / redquantity)  *  rehDepExRate) dUnitPrice,
convert(numeric(18,2), (redUnitPrice / redquantity))  posdUnitPrice,
redquantity, redRateType, rehExportDate, rehExportID, rehExportNo, rehShopid, redcostprice,
redcostprice * rehDepExRate, redcostprice * rehExchangeRate, ''S'',
((redUnitPrice / redquantity) * rehExchangeRate - redcostprice) margin,
((redUnitPrice / redquantity) - redcostprice) * rehDepExRate  dmargin,
((redUnitPrice / redquantity) - redcostprice) * rehExchangeRate cmargin,
convert(numeric(18, 2),redUnitPrice) Amount,convert(numeric(18, 2),redUnitPrice * rehExchangeRate) cAmount,
convert(numeric(18, 2),redUnitPrice * rehDepExRate) Amount
from
losExportDetail, losExportHeader
where
rehExportID = redExportID and rehShopID = redShopID AND
rehCancelled = 0 and rehproforma = 0 and rehtype = ''i''
union all
-- 10 Hire Purchase
select
hpqdItemId, convert(numeric(18,2),
(hpqdSellingPrice / 1)) cUnitPrice,
convert(numeric(18,2), (hpqdSellingPrice / 1) ) dUnitPrice,
convert(numeric(18,2), (hpqdSellingPrice / 1))  UnitPrice,
1 as Qty,null as redRateType,null as rehExportDate,0 as rehExportID,null as rehExportNo, hpqhShopid, hpqdCostPrice,
hpqdCostPrice, hpqdCostPrice , ''S'',
((hpqdSellingPrice / 1) - hpqdCostPrice) margin,
((hpqdSellingPrice / 1) - hpqdCostPrice)  dmargin,
((hpqdSellingPrice / 1) - hpqdCostPrice) cmargin,
convert(numeric(18, 2),hpqdSellingPrice) Amount,convert(numeric(18, 2),hpqdSellingPrice) cAmount,
convert(numeric(18, 2),hpqdSellingPrice) Amount
from
loshpInvoiceDetail,losHpInvoiceHeader
where
hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I'''
GO
/****** Object:  View [dbo].[vwShopItemSalesFandB]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesFandB]'))
EXEC dbo.sp_executesql @statement = N'
--select * from vwShopItemSalesFandB
-- Created On  : 22/10/2010
-- Created By  : Nidheesh P V
-- Comments    : To show details in daliy sales item report for FandB shop
CREATE view [dbo].[vwShopItemSalesFandB]
as
select v.* from
(
select distinct fb_dd_dishid[posditemid],fb_dd_dishname,''Dish''DishType,
convert(numeric(18,2),(fb_pd_Rate)*poshExchangeRate)cUnitPrice,
convert(numeric(18,2),(fb_pd_Rate)*poshdepexrate)dUnitPrice,
convert(numeric(18,2),(fb_pd_Rate))posdUnitPrice,
fb_pd_reusedqty[posdquantity],0 as posdRateType,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBilldate,poshBillID[poshbillID],poshBillNo[poshBillNo],poshShopID[poshShopID],
sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,
convert(numeric(18,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,
convert(numeric(18,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,
''S'' as type,
convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,
convert(numeric(18,2),sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))Amount,
convert(numeric(18,2),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)cAmount,
convert(numeric(18,2),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)dAmount
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 Fb_recipedetails rd on
--Fb_rd_Companyid=fb_pd_companyid and Fb_rd_dishid=fb_pd_dishid
--inner join aitem a on a.itemid=rd.Fb_rd_itemid
where fb_pd_AddedItemtype=0
union all
select distinct a.itemid,a.ItemDescription,''DishAdd''DishType,
convert(numeric(18,2),(fb_pd_Rate/fb_pd_reusedqty)*poshExchangeRate)ComUnitprice,
convert(numeric(18,2),(fb_pd_Rate/fb_pd_reusedqty)*poshdepexrate)DepUnitPrice,
convert(numeric(18,2),(fb_pd_Rate/fb_pd_reusedqty))UnitPrice,
fb_pd_reusedqty,0 as Ratetype,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshBillID,poshBillNo,poshShopID,
sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,
convert(numeric(18,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,
convert(numeric(18,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,
''S'' as Type,
convert(numeric(18,2),(fb_pd_Rate-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
convert(numeric(18,2),(fb_pd_Rate-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
convert(numeric(18,2),(fb_pd_Rate-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,
convert(numeric(18,2),sum(fb_pd_Rate)over (partition by a.itemid,poshBillID))Amount,
convert(numeric(18,2),(sum(fb_pd_Rate)over (partition by a.itemid,poshBillID))*poshExchangeRate)ComAmount,
convert(numeric(18,2),(sum(fb_pd_Rate)over (partition by a.itemid,poshBillID))*poshdepexrate)DepAmount
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
where fb_pd_AddedItemtype=2
)v'
GO
/****** Object:  StoredProcedure [dbo].[spGITDifference_GL]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGITDifference_GL]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------
/*
CREATED BY    :PRASANTH JOSEPH
CREATED ON    :14-08-2009
CREATED FOR   :TO GET COSTING BILL PAYMENT DETAILS IN SIGLE EXECUTION BETWEEN 2 PERIOD
USE           :EXEC SPGITDIFFERENCE_GL ''20080101'',''20081231''
*/
------------------------------------------------------------------------------------
CREATE  PROC [dbo].[spGITDifference_GL](@strFromDate as varchar(10),@strtodate as varchar(10)) AS
BEGIN
DECLARE @COSTINGID AS INT
DECLARE @COSTINGNO AS VARCHAR(25)
DECLARE @COSTINGDATE AS datetime
DECLARE @BILLID AS INT
dECLARE @DEPARTMENTID AS INT
DECLARE @BILLAMOUNT as NUMERIC(18,2)
DECLARE @PAYMENTAMT AS NUMERIC(18,2)
DECLARE @PAYMENTID AS INT
DECLARE @PAYMENTNO AS VARCHAR(20)
CREATE table #Detail (
DepartmentID int, CostingID int,
CostingNo nvarchar(25),
PaymentNo varchar(20),
CostingDate datetime,
CostingAmt numeric(18,2),
BillID int,
BillNo varchar(25),
BillAmount  numeric(18,2),
PaymentAmount  numeric(18,2),
Debitamt numeric(18,2) )
CREATE table #Payments
(
PaymentID int,
PaymentNo varchar(20),
PaymentAmount numeric(18,2)
)
DECLARE CURDETAIL CURSOR FOR
SELECT
chCostingID,chCOSTINGNO,chCostingDate,chBillID,chDepartmentID
FROM
LOaCostingHeader
WHERE
chCancelled=0 and
chCostingDate>= @strFromDate  and chCostingDate<=@strtodate
OPEN CURDETAIL
FETCH next FROM CURDETAIL into  @COSTINGID,@COSTINGNO,@COSTINGDATE,@BILLID,@DEPARTMENTID
WHILE @@Fetch_status = 0
BEGIN
INSERT INTO   #Payments SELECT phPaymentID,phPaymentNo,(pddAmount*phexchangerate)phPaymentAmount FROM LOaCostingHeader
left outer join LOspPurchaseBillHeader ON chBillID=pbhBillID
left outer join ahqpaymentvoucherdebitdetails ON pbhPOID=pddhqpoid
left outer join ahqpaymentvoucherheader ON pddPaymentID=phPaymentID
WHERE  phcancelled=0 and  chCostingID= @COSTINGID and  pbhBillID=@BILLID
WHILE (SELECT COUNT(PaymentID) FROM  #Payments )<> 0
BEGIN
---SET @PAYMENTID=0
SELECT @PAYMENTID=max(PaymentID) FROM #Payments
SET @PAYMENTNO=''''
SET @PAYMENTAMT=0
SELECT @PAYMENTNO= PAYMENTNO,@PAYMENTAMT=PAYMENTAMOUNT FROM #Payments WHERE PaymentID=@PAYMENTID
--print @PAYMENTNO
--print @PAYMENTAMT
--print @PAYMENTID
INSERT INTO #Detail VALUES(@DEPARTMENTID,@COSTINGID,@COSTINGNO,@PAYMENTNO,@COSTINGDATE,NULL,@BILLID,NULL,NUll,@PAYMENTAMT,null)
UPDATE #Detail SET CostingAmt= (SELECT sum(cdCostingPrice*cdItemQuantity) FROM loacostingdetail WHERE cdcostingid=@COSTINGID)
WHERE CostingID=@COSTINGID
UPDATE #Detail SET BillNo= (select pbhBillNo from LOspPurchaseBillHeader where pbhBillID=@BILLID and pbhCancelled=0 )
WHERE CostingID=@COSTINGID
set @BILLAMOUNT=(select sum(pbhBillAmount*pbhexchangerate) from LOspPurchaseBillHeader where pbhBillID=@BILLID and pbhCancelled=0)
SET @PAYMENTAMT= (SELECT isnull(sum(pddAmount*phexchangerate),0) FROM   LOaCostingHeader
left outer join LOspPurchaseBillHeader ON chBillID=pbhBillID
left outer join ahqpaymentvoucherdebitdetails ON pbhPOID=pddhqpoid
left outer join ahqpaymentvoucherheader ON pddPaymentID=phPaymentID
WHERE  phcancelled=0 and  chCostingID= @COSTINGID and  pbhBillID=@BILLID )
UPDATE  #Detail set BillAmount=@BILLAMOUNT WHERE CostingID=@COSTINGID
UPDATE #Detail SET Debitamt= @PAYMENTAMT+@BILLAMOUNT WHERE CostingID=@COSTINGID
DELETE FROM #Payments WHERE PaymentID=@PAYMENTID
end
IF (select count(CostingID) from #Detail where  CostingID=@COSTINGID )=0
INSERT INTO #Detail VALUES(@DEPARTMENTID,@COSTINGID,@COSTINGNO,Null,@COSTINGDATE,NULL,@BILLID,NULL,@BILLAMOUNT,NULL,null)
FETCH NEXT FROM  CURDETAIL INTO  @COSTINGID,@COSTINGNO,@COSTINGDATE,@BILLID, @DEPARTMENTID
END
CLOSE CURDETAIL
DEALLOCATE CURDETAIL
SELECT DepartmentName,d*t1.DepartmentID,CostingID,CostingNo,CostingDate,CostingAmt,BillID,BillNo,isnull(Debitamt,0) Debitamt,PaymentNo,PaymentAmount,BillAmount
FROM #Detail dt1,adepartmentmaster dt2 where  dt2.DepartmentID=dt1.DepartmentID order by dt1.DepartmentID
DROP TABLE #Detail
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spReverseGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReverseGodownTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created By 		: Kishore
-- Created Date  	: 25/08/2003
-- Comments		: Reverses the stock updation of ''Total Stock Verification''
-- 			  (Taken from v2)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spReverseGodownTotalStockVerification] (@VerificationID int,
				@GodownId int) AS
Begin
	declare
	@cur_verid int,
	@cur_GodownId int,
	@cur_ItemId int,
	@cur_ItemGoodQty numeric(18,3),
	@cur_itemBadQty numeric(18,3),
	@cur_AvailGoodQty numeric(18,3),
	@cur_availBadQty numeric(18,3),
	@cur_packingtypeid int,
	@cur_cost numeric(18,2),
	@cur_ShipmentID int,
	@recCount as int
	set nocount on
	Declare Cursor_Detail cursor for
	        select svdid, svdGodownId, svdItemId, svdVerifiedStock, svdVerifiedBadStock,
		svdCostPrice, svdShipmentId, svdAvailStock, svdAvailBadStock
		from loiStockVerificationDetail
		where svdid = @VerificationID and svdGodownId = @GodownId
	open cursor_Detail
	fetch next from cursor_Detail into
		@cur_verid, @cur_GodownId, @cur_ItemId,
		@cur_ItemGoodQty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
		@cur_AvailGoodQty, @cur_availBadQty
	While @@fetch_status = 0
	Begin
		-- reverse stock of items entered by user
		If @cur_AvailBadQty = 1
		Begin
			update moiGodownStock
				set gsStock = gsStock + @cur_AvailGoodQty - @cur_ItemBadQty
				where gsItemId = @cur_ItemId
				and gsGodownId = @cur_GodownId
		End		
		Else	-- Reverse stock of items entered by system
		
		Begin
			update moiGodownStock
				set gsStock = gsStock + @cur_AvailGoodQty  -- modified on 26/08/2003
				where gsItemId = @cur_ItemId
				and gsGodownId = @cur_GodownId
		End
		fetch next from cursor_Detail into
			@cur_verid, @cur_GodownId, @cur_ItemId,
			@cur_ItemGoodQty, @cur_itemBadQty, @cur_cost, @cur_ShipmentID,
			@cur_AvailGoodQty, @cur_availBadqty
	End
	Close cursor_Detail
	Deallocate cursor_Detail
	Return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGodownTotalStockVerification]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGodownTotalStockVerification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created on : 25/08/2003
-- Created by : Kishore
-- Comments   : Does the stock updattion
--              and insertion of records to loiStockVerificationDetails
--		(taken from v2)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spGodownTotalStockVerification] (@intSvdId as int, @intGodownId as int) AS
Begin
	Declare @dtUpdate as DateTime
	Declare @intItemId as int
	Declare @numSum as Numeric(18, 3)
	Declare @intCount as Int
	Set NoCount On
	Set ansi_warnings off	
	-- variables for expiry s
	Declare @intExpiryArrivalDetailId as int
	Declare @intExpiryIssueDetailId as int
	
	-- variables for location stock updation
	Declare @intArrivalDetailId as int
	Declare @intIssueDetailId as int
	
	-- initialize detail id variables
	Set @intArrivalDetailId = 1
	Set @intIssueDetailId = 1
	Set @intExpiryArrivalDetailId = 1
	Set @intExpiryIssueDetailId = 1
	-- a few records are inserted to loiLocationArrivalDeatils
	-- with cancel 0
	-- when total stock verification starts
	-- so take arrival detail id as last no + 1
	SELECT @intArrivalDetailId = ISNULL(MAX(ladDetailId), 0) + 1
		FROM loiLocationArrivalDetails
		WHERE ladGodownId = @intGodownId
		AND ladTransId = @intSvdId
		AND ladInterfaceId = 8010
		AND ladCancel = 1
	-- get the UpdateTime
	SELECT @dtUpdate = UpdateTime FROM loiStockVerificationHeader
		WHERE svhId = @intSvdId
		AND svhGodownId = @intGodownId
	
	-- open the cursor
	Declare curDetails Cursor For
		SELECT svdItemId FROM loiStockVerificationDetail
		WHERE svdId = @intSvdId
		AND svdGodownId = @intGodownId
	
	Open CurDetails
	Fetch Next From CurDetails Into @intItemId
	
	While @@Fetch_Status = 0
	Begin
		-- get sum qty transacted in sales
		-- after starting the ''total stock verification''
		SELECT @numSum = ISNULL(SUM(ddItemGoodQty), 0)
			FROM meiSpecialDespatchToShopDetail Detail,
			meiSpecialDespatchToShopHeader Header
			WHERE Detail.ddDespatchId = Header.dhDespatchId
			AND Detail.ddGodownId = Header.dhGodownId
			AND Detail.ddItemId = @intItemId
			AND Header.UpdateTime >= @dtUpdate
		Set @numSum = ISNULL(@numSum, 0)
		-- update verified stock with verified bad stock (stock entered by user)
		-- minus quantity transacted in sales
		UPDATE loiStockVerificationDetail
			SET svdVerifiedStock = svdVerifiedBadStock - @numSum
			WHERE svdId = @intSvdId
			AND svdGodownId = @intGodownId
			AND svdItemId = @intItemId
		
		print ''starting spGodownLocationTotalStockVerification...''
		print @intArrivalDetailId
		-- call sp to update location wise stock
		Execute spGodownLocationTotalStockVerification @intItemId, @intGodownId,
						@intSvdId, @dtUpdate,
						@intArrivalDetailId OUTPUT,
						@intIssueDetailId OUTPUT
	
		print ''starting spGodownExpiryTotalStockVerification...''
		-- call sp to update expiry date wise stock
		Execute spGodownExpiryTotalStockVerification @intItemID, @intGodownId,
						@intSvdId, @dtUpdate,
						@intExpiryArrivalDetailId OUTPUT,
						@intExpiryIssueDetailId OUTPUT
		
		print ''starting spSetZeroLocationStockForNonVerifiedItemsInGodown...''
		-- set the location stock of all items which are not verified to zero
		Execute spSetZeroLocationStockForNonVerifiedItemsInGodown @intSvdId,
				@intGodownId, @intIssueDetailID OUTPUT,
				@intArrivalDetailId OUTPUT
		print ''starting spSetZeroExpiryStockForNonVerifiedItemsInGodown...''
		-- set the expiry stock of all items, which are not verified, to zero
		Execute spSetZeroExpiryStockForNonVerifiedItemsInGodown @intSvdId,
				@intGodownId, @intExpiryIssueDetailID OUTPUT,
				@intExpiryArrivalDetailId OUTPUT
		Fetch Next From CurDetails Into @intItemId	
	End
	
	Close CurDetails
	Deallocate CurDetails
	-- insert to stock verified items
	UPDATE moiGodownStock
		SET gsStock = svdVerifiedStock
		FROM loiStockVerificationDetail
		WHERE svdId = @intSvdId
		AND svdGodownId = @intGodownId
		AND gsGodownId = svdGodownId
		AND gsItemId = svdItemId
	
	-- insert to stock for items
	-- which do not exist in stock
	INSERT INTO moiGodownStock
		(gsGodownID, gsLocationID, gsStockDate, gsShipmentID,
		gsItemID, gsOpeningStock, gsStock, gsOpeningBadStock,
		gsBadStock, gsItemCost)
		(SELECT svdGodownId, svdLocationId, GetDate(),
		svdShipmentId, svdItemId, 0, svdVerifiedStock,
		0, 0, ItemRate
		FROM loiStockVerificationDetail v
		LEFT OUTER JOIN moiGodownStock s
		ON v.svdGodownId = s.gsGodownId
		AND v.svdItemId = s.gsItemId, aItem
		WHERE v.svdId = @intSvdId
		AND gsGodownId IS NULL
		AND svdGodownId = @intGodownId
		AND svdItemId = aItem.ItemId)			
	-- insert to stockverification details
	-- items which are not verified by user
	INSERT INTO loiStockVerificationDetail
		(svdid, svdGodownID, svdLocationid, svdShipmentID,
		 svdItemID, svdAvailStock, svdVerifiedStock,
		 svdAvailBadStock, svdVerifiedBadStock, svdcostprice)
		(SELECT @intSvdId, @intGodownId, 1, 1,
		 gsItemId, gsStock, 0, 0, 0, ItemRate
		 FROM moiGodownStock LEFT OUTER JOIN loiStockVerificationDetail
		 ON gsItemId = svdItemId
		 AND @intSvdId = svdId
		 AND gsGodownId = svdGodownId, aItem
		 WHERE svdItemId IS NULL
		 AND gsGodownId = @intGodownId
		 AND gsItemId = ItemId)
	-- to make the item stock 0 of items
	-- which are not verified by user
	UPDATE moiGodownStock
		SET gsStock = svdVerifiedStock
		FROM loiStockVerificationDetail
		WHERE svdId = @intSvdId
		AND svdGodownId = @intGodownId
		AND gsGodownId = svdGodownId
		AND gsItemId = svdItemId
		AND svdAvailBadStock = 0
	-- Update no. of records in details to
	-- last 4 chars of svhFutureVc of Header
	SELECT @intCount = COUNT(*) FROM loiStockVerificationDetail
		WHERE svdId = @intSvdId
		AND svdGodownId = @intGodownId
	UPDATE loiStockVerificationHeader
		SET svhFutureVc = LEFT(svhFutureVc, 2) +
			REPLICATE(''0'', 5 - LEN(CAST(@intCount AS VarChar))) +
			CAST(@intCount AS VarChar)
		WHERE svhId = @intSvdId
		AND svhGodownId = @intGodownId
	Set NoCount off
	Set ansi_warnings on
End' 
END
GO
/****** Object:  View [dbo].[vwShopItemSalesDecimalQty]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopItemSalesDecimalQty]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopItemSalesDecimalQty    Script Date: 18/01/2003 9:45:40 PM ******/
/****** Object:  View dbo.vwShopItemSalesDecimalQty    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwShopItemSalesDecimalQty    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwShopItemSalesDecimalQty    Script Date: 20/11/2001 9:59:06 AM ******/
/****** Object:  View dbo.vwShopItemSalesDecimalQty    Script Date: 17/11/2001 9:21:55 PM ******/
CREATE view [dbo].[vwShopItemSalesDecimalQty] as
select vwshopitemsales.*, aitem.unitsID from vwshopitemsales, aitem
where itemid = posditemid and posdquantity <> round(posdquantity,0,1) and posdquantity>0'
GO
/****** Object:  View [dbo].[vwLocalPurchaseCosting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseCosting]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- Last modified  : Kishore
-- Last modified on     : 13/01/2003
-- Comments  : Added cancelled(lpchcancelled)on 30/09/2003
--                      : Added currency symbol (13/01/2003)
--Add selling price for kooddoo
--Abhishek on 29-07-10
CREATE VIEW [dbo].[vwLocalPurchaseCosting] AS
select s.shopname, lpch.lpchCostingid, lph.lphbilldate,
lph.lphbillno, lpch.lpchcostingno,
lpch.lpchDate, lpch.lpchremarks,
case lpch.lpchcostingdone when 1 then ''Yes'' when 0 then ''No'' end costingdone,
u.unitname, lpcd.lpcdolditemcostprice,vw.itemdescription,
lpcd.lpcdnewitemcostprice, lpcd.lpcdcostedprice, lpcd.lpcditemqty,
a.itemcode,a.itemid, lpch.lpchCancelled, Currency.Symbol CurrencySymbol ,isd.sellingprice
from loalocalpurchasecostingheader lpch, loalocalpurchasecostingdetail lpcd
left outer join losShopItemShipmentDetail isd on  lpcd.lpcditemid = isd.itemid
inner join vwitemretailpacking vwr on isd.itemid=vwr.itemid and vwr.Packingtypeid=isd.PackingTypeid,
loslocalpurchaseheader lph, ashops s, aitem a  , aunit u, vwitemdescription vw,
(select top 1 p.CompanyId, cm.Symbol -- top 1 is for extra security
from aPackageSettings p, aAccountMaster am, aCurrencyMaster cm
where p.InventoryId = am.AccountId
and p.CompanyId = am.CompanyId
and am.CurrencyId = cm.CurrencyId
and am.CompanyId = cm.CompanyId) Currency -- this derived table returns the inventory currency
where lpch.lpchcostingid = lpcd.lpcdcostingid
and lpch.lpchBillid = lph.lphbillid
and lpch.lpchshopid = lph.lphshopid
and lph.lphshopid = s.shopid
and lpcd.lpcditemid = a.itemid
and a.unitsid = u.unitid
and vw.itemid = a.itemid
and lpchCompanyid = Currency.CompanyId'
GO
/****** Object:  View [dbo].[vwLocalPurchaseBillSettlementNo]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified by    :    Kishore
-- Modified on    :    25/11/2003
-- Comments       :    Added the PaidAmount column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by    :    VinothMurugan V.
-- Modified on    :    08/11/2003
-- Comments       :    Adding Confirmation Bit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwLocalPurchaseBillSettlementNo] as
select companyid, shopid, vendorid, max(setdate) setdate,
max(refno) refno, billid, Sum(SettlementAmount) PaidAmount
from
(select vh.companyid,vd.shopid shopid, vh.vendorid,
vh.vsdate setdate, vh.vsno refno, vd.lphbillid billid, SettlementAmount
from vendorsettlementheader vh, vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid and
vd.lphbillid is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, pd.pdshopid shopid, ph.phvendorid,
ph.phpaymentdate setdate, ph.phpaymentno refno, pd.pdposlpbillid, pdPaidAmount
from AHQpaymentvoucherheader ph, AHQpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pdposlpbillid is not null and ph.phConfirmed = 1) settledaccbills
group by companyid, shopid, vendorid, billid'
GO
/****** Object:  View [dbo].[vwlocalpurchasebill]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwlocalpurchasebill]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Last Modified on  : 11/12/02
--Modified by   : leo
--Comments  : v3
--Added lphcancelled on 01/10/2003
--Modified by  : Santhosh M
--Modified By  : Hariharan
--MOdified Date  : 04/05/2004
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--Modified On:18/09/2011
--Modified By:Aadyakumar.D.V
--Comment    :Add new columns lpdItemTaxPercentage ,lpdItemTaxAmount,lpdItemTaxCategory
---------------------------------------------------------------------------------------
-- RefNo-1
-- Updated By : Aadyakumar.D.V
-- Updated On : 26-09-2011
-- Purpose    : lospurchaseorderheader table and its columns are commented,because
--            : in the case of direct Local purchase bill this view didnt give out put
---------------------------------------------------------------------------------------
-- RefNo-2
-- Updated By : Aadyakumar.D.V
-- Updated On : 17-10-2011
-- Purpose    : Need to show pack quantity in report,so view vwPurchaseBillPackQty is joined
---------------------------------------------------------------------------------------
CREATE view [dbo].[vwlocalpurchasebill] as
select lphshopid, lphbillid, lphBillNo,--pohpono,--'' RefNo-1
lphVendorBillNo, los.lpditemid,lphVendorID ,
unitname, los.lpdPOQuantity, los.lpdPOUnitPrice, los.lpdItemQuantity, los.lpdItemUnitPrice,
lphRemarks,lphBillDate,vw.itemdescription,lphBillAmount,lphCashPurchase,
vw.code, lphexchangerate, lphdepexrate,lphCancelled,--pohdiscount, --'' RefNo-1
los.lpdItemTaxPercentage ,los.lpdItemTaxAmount,los.lpdItemTaxCategory,PackQty,lphDiscount
from loslocalpurchaseheader,
loslocalpurchasedetail los
inner join vwPurchaseBillPackQty vwp
on vwp.lpdShopID=los.lpdShopID and vwp.lpdBillID=los.lpdBillID and vwp.lpdItemID = los.lpdItemID,
--lospurchaseorderheader,--'' RefNo-1
aunit u, aitem a, vwitemdescription vw
where lphBillID = los.lpdbillid and lphshopid = los.lpdshopid and
--lphpoid=pohpoid  and    --'' RefNo-1
--lphshopid = pohshopid and --'' RefNo-1
los.lpditemid=a.itemid and a.unitsid = u.unitid and a.itemid = vw.itemid'
GO
/****** Object:  View [dbo].[vwshopcreditinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopcreditinvoicereceipt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopcreditinvoicereceipt    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshopcreditinvoicereceipt] as
select rh.companyid, rd.shopid, rd.posinvoiceid, rh.customerid, 0.0 as invoiceamt,
max(rh.receiptdate) receiptdate, sum(amountreceived) settledamt from receiptvoucherheader rh,
receiptvoucherdetails rd where rh.companyid=rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled = 0 and rd.posinvoiceid is not null
group by rh.companyid, rd.shopid, posinvoiceid, rh.customerid'
GO
/****** Object:  StoredProcedure [dbo].[sp_FBCashSummary]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_FBCashSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: LAWRENCE M.
-- Create date: 29 JULY 2011
-- Description: For getting the correct Cash value and Cash drawer Value in the Cash Detail Summary Report
-- Client : Wings Service
-- =============================================
CREATE PROCEDURE [dbo].[sp_FBCashSummary] (@intOutletID AS INT,@TillNo AS INT)
AS
BEGIN
	CREATE TABLE #Temp
	(
	TempTillNo INT,
	TempOutletID INT,
	TempAccID INT,
	TempAccDesc VARCHAR(250),
	TempCurrency INT,
	TempExchangeRate DECIMAL(28,8),
	TempBillAmount DECIMAL(18,4),
	)
	CREATE TABLE #TempCash
	(
	TempCTillNo INT,
	TempCOutletID INT,
	TempCCurrencyID INT,
	TempCCashAmount DECIMAL(18,4)
	)
	INSERT INTO #Temp(TempTillNo,TempOutletID,TempAccID,TempAccDesc,TempCurrency,TempExchangeRate,TempBillAmount)
	SELECT TillHistory.till_no,TillHistory.till_outletid,AccountID,AccountDesc,poshCurrencyID,poshExchangeRate,SUM(Poshbillamount) Tot
	FROM losposfandbheader inner join aaccountmaster ON AccountID=poshCashAccID AND poshCompanyID=CompanyID INNER JOIN
		TillHistory ON LosPosFAndBHeader.poshTillHistID = TillHistory.till_hist_id AND
		LosPosFAndBHeader.poshShopID = TillHistory.till_outletid AND
		LosPosFAndBHeader.poshTillID = TillHistory.till_id inner join TillBalanceHistory ON
		TillBalanceHistory.till_hist_id=TillHistory.till_hist_id and poshCurrencyID=till_currencyid
	WHERE poshbilltype <>''NP'' AND poshcashsale=1 and TillHistory.till_no=@TillNo and LosPosFAndBHeader.poshShopID=@intOutletID
	GROUP BY TillHistory.till_no,TillHistory.till_outletid,AccountID,AccountDesc,poshCurrencyID,poshExchangeRate
	
	INSERT INTO #TempCash(TempCTillNo,TempCOutletID,TempCCurrencyID,TempCCashAmount)
	SELECT Till_no,till_outletid,dcurrencyid,SUM(damount) cashTot FROM denominationheader INNER JOIN
	denominationdetail ON denominationid=ddenominationid INNER JOIN
	tillhistory ON till_hist_id=tillHistoryid AND till_outletid=shopid INNER JOIN acurrencymaster ON CurrencyID=dcurrencyid
	WHERE cancelled=0 AND tillhistory.Till_no=@TillNo AND till_outletid=@intOutletID
	GROUP BY Till_no,till_outletid,dcurrencyid
	
	SELECT TempTillNo till_no,TempOutletID till_outletid,TempAccDesc AccountDesc,TempExchangeRate poshExchangeRate,TempBillAmount Tot,
	TempBillAmount*TempExchangeRate value,TempCCashAmount cashTot,TempCCashAmount*TempExchangeRate cashValue,
	TempCCashAmount-TempBillAmount cashTotal,(TempCCashAmount-TempBillAmount)*TempExchangeRate finalValue
	FROM #Temp LEFT OUTER JOIN #TempCash ON TempCTillNo=TempTillNo AND TempOutletID=TempCOutletID AND
	TempCCurrencyID=TempCurrency
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spFixedAssetRpt]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFixedAssetRpt]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created on 	: 26/03/04
--create by  	: venkitesh
--purpose    	: display the FixedAssetDetails
-- modified by	: Venkitesh For giving company currency
-- Modified date: 08/04/04
-- modified by	: Venkitesh For accc id correction
--MOdified Date	: 130403
-----------------------------------------
CREATE proc [dbo].[spFixedAssetRpt] (@intcompanyid as int,
					 @intDeptid as int =0 ,
					 @Todate as varchar(8),
	   		  		@intCmpCur as int )
as
begin
	set nocount on
	declare
		@intfinancialid as int,		
		@lastyearfinancialid as int
		
	Create table #Temp(
			CompanyID int,
			TransDeptid int,
			FixedAssetid int,
			AssetAccid int,
			TransAmt numeric(18,2),
			Type varchar(3),
			TransType  varchar(3))
			-- from dep id and reducing cost value
			--asset  value For open asset
			select @intfinancialid=financialid from vwfinyearperiod where
			year(sdate)=left(@todate,4)
			
			select top 1 @lastyearfinancialid= financialid from vwfinyearperiod
			where edate<=@todate order by financialid desc
-- opening Taking from openings sp
			insert into #temp
			exec spFixedAssetopeningBalance 1,@lastyearfinancialid,@intCmpCur
-- Fixed Asset Details Inserting
			insert into #Temp --Inertng asset and depreciation opending  details
			
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then costprice* exrate
			else  costprice end Costprice,''A'',''C'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			insert into #temp  --Depreciation value For purchased or gdn transfer asset	
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then initialDepreciatedValue* exrate
			else  initialDepreciatedValue end initialDepreciatedValue,''A'',''D'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			
			
--depreciation 	
			insert into #temp
			select a.companyid,DepartmentID,FixedAssetID,assetAccountID,case when @intCmpCur=1 then consexrate* DepreciationAmount
			else  DepreciationAmount end DepreciationAmount ,''A'',''D''
			from depreciationheader a,depreciationdetail b
			where  	a.DepreciationID=b.DepreciationID and a.CompanyID=b.companyid
			and Cancelled=0  and DepreciationDate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and DepreciationDate <=@Todate
			
			
			/*insert into #temp --depreciation Additionals
				
			select a.companyid,DepartmentID,FixedAssetID,assetAccountID,DepreciationAmount ,''A'',''D''from depreciationheader a,depreciationdetail b
			where  	a.DepreciationID=b.DepreciationID and a.CompanyID=b.companyid
			and Cancelled=0  and DepreciationDate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and DepreciationDate <=@Todate*/
--Asset Transfer
			
			insert into #Temp --Inertng asset transfer details
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then consexrate*-asttransvalue else  -asttransvalue*fromdepexrate end  assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* asttransvalue else asttransvalue*todepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* -astDeprValue else  -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate<=@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*todepexrate end  assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
				insert into #temp
			-- from acc dep id and redcuing cost value(accounts)
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate * -asttransvalue else -asttransvalue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- To acc dep id and depreciation reducing cost value
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccID,case when @intCmpCur=1 then  consexrate* asttransValue else  asttransValue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			
		
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate*-astDeprValue else -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is  null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate	
--disposal
			
			insert into #temp ---disposal case cost
			
			select disphcompanyid,disphdepartmentid,dispdasstid,
			case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end
			dispdaccid, case when @intCmpCur=1 then  -disphexrate * dispdamount else  -dispdamount end dispdamount ,''D'',''C'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate
			
			insert into #temp --disposal case depreciation			
			
			select disphcompanyid,disphdepartmentid, dispdasstid,
			case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end dispdaccid,case when @intCmpCur=1 then disphexrate * disdepeBalamt else disdepeBalamt end disdepeBalamt,''D'',''D'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate	
	
if @intDeptid>0
	select a.CompanyID,a.TransDeptid,a.FixedAssetid,
	b.assetname,a.AssetAccid,c.AccountDesc,
	a.TransAmt,a.Type,a.TransType  from #temp a,
	fixedasset b,aaccountmaster c where a.companyid=b.companyid and
	a.FixedAssetID=b.FixedAssetID
	and a.companyid=c.companyid and
	a.AssetAccid=c.AccountID and a.TransDeptid=@intdeptid
else
	select a.CompanyID, a.TransDeptid , a.FixedAssetid,
	b.assetname,a.AssetAccid,c.AccountDesc,
	a.TransAmt,a.Type,a.TransType  from #temp a,
	fixedasset b,aaccountmaster c where a.companyid=b.companyid and
	a.FixedAssetID=b.FixedAssetID
	and a.companyid=c.companyid and
	a.AssetAccid=c.AccountID
end' 
END
GO
/****** Object:  View [dbo].[vwadvancepaidReturnAmounts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidReturnAmounts]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwadvancepaidReturnAmounts] as
select prhCompanyID, prhReturnID,prhVendorId, sum(advanceamt) Pmtamt,
sum(settlementamt) settledamt from
(select prh.prhReturnID, prh.prhCompanyID, prh.prhVendorId, sum(prdSuppAmount) advanceamt,
0.0 as settlementamt from loPurchaseReturnheader prh
Inner Join loPurchaseReturnDetail ON prhCompanyID=prdCompanyID And prhReturnID=prdReturnID
Inner Join vwadvancepaidReturn vw ON prh.prhCompanyID = vw.prhcompanyid and prh.prhReturnID = vw.prhReturnID
where prhcancelled = 0
Group by  prh.prhReturnID, prh.prhCompanyID, prh.prhVendorId
union all
select vh.PReturnID, vh.companyid, vh.vendorid,0.0 advanceamt,
sum(vd.SettlementAmount) settlementamt from
vendorsettlementheader vh
Inner Join vendorsettlementdetail vd ON vh.companyid = vd.companyid and vh.vsid = vd.vsid
Inner Join vwadvancepaidReturn vw  ON vw.prhcompanyid = vh.companyid and vw.prhReturnID = vh.PReturnID
where vh.cancelled =0
group by vh.PReturnID, vh.companyid, vh.vendorid) temp1
group by prhcompanyid, prhReturnID, prhvendorid'
GO
/****** Object:  View [dbo].[vwGodownIssuedItems]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGodownIssuedItems]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------
/*
CREATED BY  : PRASANTH JOSEPH
CREATED ON  : 12-04-2009
CRATED FOR  : There is a view already named ''vwAlreadyIssuedItems'', but it
take values from confirmed Sp invoice too. Need to show the Confirmed Invoice Qty Seperate.
MODIFY ON   :
MODIFY BY   :
*/
---------------------------------------------
CREATE  view [dbo].[vwGodownIssuedItems] as
select totalreserve.indgodownid, totalreserve.indlocationid, totalreserve.inditemid,
sum(totalreserve.issuedgood) issuedgood,
sum(totalreserve.issuedbad) issuedbad
from
(select ind.indgodownid,ind.indlocationid, ind.inditemid,sum(ind.indqty) as issuedgood,
sum(ind.indbadqty) as issuedbad from ahqissuenotedetail ind,ahqIssueNoteHeader inh ,
ahqIssuenoteMain inm where ind.indissuenoteid=inh.inhissuenoteid and
ind.indgodownid=inh.inhgodownid and inh.inhissuenotemainid=inm.inmissuenoteid and
inm.inmCancel=0 and inh.inhused=0
group by ind.indgodownid,ind.indlocationid, ind.inditemid
)totalreserve
group by totalreserve.indgodownid, totalreserve.indlocationid, totalreserve.inditemid'
GO
/****** Object:  StoredProcedure [dbo].[SpPopulateAccountsBills]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpPopulateAccountsBills]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------------------------------------------
--exec SpPopulateAccountsBills 1,1,1
--------------------------------------------------------------------------------------------------------------------
--SPName      : SpPopulateAccountsBills
--Coded By    : Vinoth Murugan V
--Verified By : Yogesh Joe
--Date        : 10-02-2010
--Purpose   : To speed up vendor settlement.
---------------------------------------------------------------------------------------------------------------------
--Modified on : 17/03/2007
--Modified By : VINOTHMURUGAN V
---------------------------------------------------------------------------------------------------------------------
-- 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
--------------------------------------------------------------------------------
-- Modified on  :  08/07/2010
-- Modified by  :  VinothMurugan V
-- Purpose      : LC paid Two times.so i removed second time.
-- Reference    : RefNo-2
--------------------------------------------------------------------------------
-- Modified on  :  14/10/2010
-- Modified by  :  VinothMurugan V
-- Purpose      :Adding inter division bills  and set company login
-- Reference    : RefNo-3
--------------------------------------------------------------------------------
-- Modified on  :  22/11/2011
-- Modified by  :  MANUNADH.U
-- Purpose      :  Set @departmentid= companydepartment from apackagesettings when company login is enabled
-- Reference    :  RefNo-4
---- Modified on  :  05/01/2012
-- Modified by  :  jyothish S R
-- Purpose      :  shopid is added in local purchase bill
-- Reference    :  RefNo-5
--------------------------------------------------------------------------------
CREATE PROC [dbo].[SpPopulateAccountsBills](@vendorid AS INT,@companyid AS INT,@departmentid 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,@Companylogin int
BEGIN
CREATE TABLE #temp(
Location VARCHAR(100),
BillNo VARCHAR(50),
BillDate  DATETIME,
BillAmt NUMERIC(18,2),
SettleAmt NUMERIC(18,2),
BillID INT,
BillType VARCHAR(10),
ShopID INT,
LCOutstanding NUMERIC(18,2) )
CREATE TABLE #tempid(
id INT IDENTITY(1,1),
billid  int,
shopid int )
set @Companylogin = (select Companylogin from apackagesettings)--RefNo-3
if @Companylogin = 1
Begin
--set @departmentid =0   -- Previous code is commented --<<RefNo-4>>
set @departmentid =(select isnull(companydepartment,0) from apackagesettings)  --<<RefNo-4>>
End
IF @departmentid = 0
BEGIN
INSERT INTO #tempID
SELECT billsid,'''' FROM bills b WHERE b.cashpurchase = 0 AND b.cancelled=0 AND
b.companyid=@companyid AND b.vendorid=@vendorid
END
ELSE
BEGIN
INSERT INTO #tempID
SELECT billsid,'''' FROM bills b WHERE  b.cashpurchase = 0 AND b.cancelled = 0
AND b.DepartmentID= @departmentid AND  b.companyid = @companyid AND b.vendorid = @vendorid
END
SET @INDEX = 1
set @RECCOUNT =(SELECT COUNT(billid) FROM #tempid )
WHILE (@INDEX <= @RECCOUNT)
BEGIN
set @id =(select billid from #tempid where id = @INDEX)
SET @AMT =
(
select ISNULL(sum(settlementamount),0) FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vh.vsid = vd.vsid
WHERE vd.companyid = vh.companyid AND vd.companyid = @companyid
AND cancelled = 0 AND vd.billid  = @id
)
SET @AMT1 =(
select  isnull(sum(pdPaidAmount),0) from ahqpaymentvoucherdetails pd
inner join ahqPaymentvoucherheader ph on pd.pdpaymentid = ph.phpaymentid
where ph.phcompanyid = 1 and pd.pdcompanyid = ph.phcompanyid  and
ph.phcancelled = 0 and pd.pdAccBillsID =@id
)
INSERT INTO #TEMP
SELECT ''Head Quarters'' ,billsno ,BillDate ,billamount-(@AMT+@AMT1+isnull(Discount,0)),
''0.00'' , billsid ,''ABILL'' ,'''' ,''0.00''
FROM bills B where (@AMT + @AMT1 )< billamount and BILLSID = @id
set @INDEX =(@INDEX + 1 )
END
-----------------------------------------------------------------------------------------
--delete from #tempid
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempid
SELECT pbhBillID,'''' FROM losppurchasebillheader b
LEFT OUTER JOIN vwLcReferredInPayments lc ON b.pbhBillId = lc.BillId
WHERE  b.pbhCashPurchase = 0 AND b.pbhCancelled = 0 AND b.pbhCompanyID = @companyid
AND b.pbhVendorID = @vendorid
END
ELSE
BEGIN
INSERT INTO #tempid
SELECT pbhBillID,'''' From losppurchasebillheader b,vwLcReferredInPayments lc
where b.pbhBillId *= lc.BillId and b.pbhCashPurchase = 0 and b.pbhCancelled = 0 and
b.pbhDepartmentId = @departmentid and b.pbhCompanyID =@companyid and
b.pbhVendorID = @vendorid
END
SELECT @index = 1
SELECT @RECCOUNT = COUNT(id) FROM #tempid
WHILE (@index < = @RECCOUNT)
BEGIN
set @id =(select billid from #tempid where id = @INDEX)
SET @AMT = (
SELECT ISNULL(sum(settlementamount),0) FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vd.companyid = vh.companyid
AND vd.vsid = vh.vsid  WHERE vd.companyid = @companyid AND cancelled = 0
and pbhbillid =@id
)
SET @AMT1 =(
SELECT ISNULL(sum(pdPaidAmount),0) FROM ahqpaymentvoucherdetails pd
INNER JOIN ahqPaymentvoucherheader ph ON pd.pdcompanyid = ph.phcompanyid
AND pd.pdpaymentid = ph.phpaymentid
WHERE ph.phcompanyid = @companyid AND ph.phcancelled = 0 AND pd.pdBillsID = @id
)
set @dblamt =(
select case when lc.Amount is not null then pbhBillAmount --(pbhBillAmount-lc.Amount)   --RefNo-2
else pbhBillAmount end billamount
From losppurchasebillheader b,vwLcReferredInPayments lc
where b.pbhBillId *= lc.BillId and b.pbhCashPurchase = 0 and b.pbhCancelled = 0
and b.pbhDepartmentId = @departmentid and b.pbhCompanyID = @companyid and
b.pbhVendorID = @vendorid  AND b.pbhBillID = @ID
)
INSERT INTO #temp
select ''Head Quarters'',pbhBillNo,pbhBillDate, ISNULL(@dblamt -(@AMT+@AMT1),0),
''0.00'',pbhBillID,''FBILL'','''',ISNULL((lc.Amount - lc.PaidVendorEq),0)
From losppurchasebillheader b,vwLcReferredInPayments lc
where b.pbhBillId *= lc.BillId and b.pbhCashPurchase = 0 and b.pbhCancelled = 0 and
b.pbhDepartmentId = @departmentid and b.pbhCompanyID = @companyid and
b.pbhVendorID = @vendorid and (@AMT+@AMT1)< @dblamt AND b.pbhBillID = @ID
SELECT @Index =(@Index + 1)
END
-----------------------------------------------------------------------------------------------------
-- delete  from #tempid
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempid
SELECT dcniD,''''  FROM debitcreditnote WHERE dcncancelled =0 AND dcndebit = 0 AND
dcncompanyid = @companyid AND dcnvendorid = @vendorid
END
ELSE
BEGIN
INSERT INTO #tempid
SELECT dcniD,'''' FROM debitcreditnote WHERE dcncancelled =0 AND dcndebit = 0 AND
dcncompanyid = @companyid AND dcnvendorid = @vendorid AND dcnDepartmentId = @departmentid
END
SELECT @index = 1
SET @RECCOUNT = (select  COUNT(id) FROM #tempid )
while (@index < = @RECCOUNT)
BEGIN
set @ID =(select billid from #tempid where id = @INDEX)
SET @AMT = (
SELECT ISNULL(sum(settlementamount),0)
FROM vendorsettlementdetail vd INNER JOIN vendorsettlementheader vh
ON vh.companyid = vd.companyid AND vh.vsid = vd.vsid
WHERE  vh.cancelled = 0 AND vh.companyid = @companyid AND vd.dcnid = @ID
)
SET @AMT1 =(
SELECT ISNULL(sum(pdPaidAmount),0)
FROM ahqpaymentvoucherdetails pd INNER JOIN ahqPaymentvoucherheader ph
ON pd.pdcompanyid = ph.phcompanyid AND pd.pdpaymentid = ph.phpaymentid
WHERE ph.phcompanyid = @companyid AND ph.phcancelled = 0 AND pd.pddcnid =@ID
)
INSERT INTO #TEMP
SELECT ''Head Quarters'',dcnNo, dcnDate,ISNULL(dcnamount -(@AMT+@AMT1),0),''0.00'',dcniD,
''HDEBIT'','''',''0.00''
FROM debitcreditnote
WHERE dcncancelled =0 AND dcndebit = 0 AND dcncompanyid = @companyid
AND dcnvendorid = @vendorid AND dcnDepartmentId = @departmentid AND (@AMT + @AMT1)
< dcnamount and dcnid = @id
SELECT @Index = @Index + 1
END
----------------------------------------------------------------------------------------------------
--DELETE  FROM  #tempid
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempid
SELECT lphBillID,shopid FROM loslocalpurchaseheader b
INNER JOIN ashops s ON s.shopid = b.lphshopid
WHERE b.lphCashPurchase = 0 AND b.lphCancelled = 0
AND b.lphCompanyID = @companyid AND b.lphVendorID = @vendorid AND  s.accountable IS NOT NULL
END
ELSE
BEGIN
INSERT INTO #tempid
SELECT lphBillID,shopid From loslocalpurchaseheader b
INNER JOIN ashops s ON s.shopid = b.lphshopid
WHERE b.lphCashPurchase = 0 AND b.lphCancelled = 0 AND b.lphCompanyID = @companyid AND
b.lphVendorID = @vendorid AND lphdepartmentid = @departmentid AND  s.accountable IS NOT NULL
END
SELECT @index = 1
SELECT @RECCOUNT = COUNT(id) FROM #tempid
WHILE (@index < = @RECCOUNT)
BEGIN
set @ID =(select billid from #tempid where id = @INDEX)
set @shopid = ((select shopid from #tempid where id = @INDEX))
SET @AMT = (
select ISNULL(sum(settlementamount),0)FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vd.companyid = vh.companyid AND
vd.vsid = vh.vsid
WHERE vd.companyid = @companyid AND cancelled = 0 AND vd.shopid = @shopid
AND lphbillid = @ID
)
SET @AMT1 =(
select ISNULL(sum(pdPaidAmount),0) FROM ahqpaymentvoucherdetails pd
INNER JOIN ahqPaymentvoucherheader ph ON pd.pdcompanyid = ph.phcompanyid AND
pd.pdpaymentid = ph.phpaymentid
WHERE ph.phcompanyid = @companyid AND ph.phcancelled = 0 AND pd.pdshopid = @shopid
AND pd.pdposlpbillid = @ID
)
INSERT INTO #temp
SELECT s.shopname,lphBillNo,lphBillDate --,ISNULL((lphBillAmount - ISNULL(lphDiscount,0))-(@AMT+@AMT1),0)
,ISNULL(lphBillAmount-(@AMT+@AMT1),0) -- RefNo-1
,''0.00'',lphBillID,''SBILL'',shopid,''0.00''
From loslocalpurchaseheader b INNER JOIN ashops s ON s.shopid = b.lphshopid
WHERE b.lphCashPurchase = 0 AND b.lphCancelled = 0 AND b.lphCompanyID = @companyid AND
b.lphVendorID = @vendorid AND lphdepartmentid = @departmentid AND s.accountable IS NOT NULL
AND (@AMT + @AMT1) < (lphBillAmount - ISNULL(lphDiscount,0))  AND b.lphBillID = @ID  and ShopID=@shopid -- RefNo-5
SELECT @Index = @Index + 1
END
-----------------------------------------------------------------------------------------------------
--DELETE  FROM  #tempid
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempID
SELECT losdcnid,losdcnshopid FROM losdebitcreditnote b
INNER JOIN ashops s ON s.shopid = b.losdcnshopid
WHERE b.losdcndebit = 0 AND b.losdcnCancelled = 0 AND b.losdcnCompanyID = @companyid AND
b.losdcnVendorID = @vendorid AND  s.accountable IS NOT NULL
END
ELSE
BEGIN
INSERT INTO #tempID
SELECT losdcnid,losdcnshopid FROM losdebitcreditnote b
INNER JOIN ashops s ON s.shopid = b.losdcnshopid
WHERE b.losdcndebit = 0 AND b.losdcnCancelled = 0 AND b.losdcnCompanyID = @companyid
AND b.losdcnVendorID = @vendorid AND  s.accountable IS NOT NULL AND losdcndepartmentid = @departmentid
END
SELECT @index = 1
SELECT @RECCOUNT = COUNT(id) FROM #tempid
WHILE (@index < = @RECCOUNT)
BEGIN
set @ID =(select billid from #tempid where id = @INDEX)
set @SHOPID =(select billid from #tempid where id = @INDEX)
SET @AMT =(
select ISNULL(sum(settlementamount),0) FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vd.companyid = vh.companyid AND vd.vsid = vh.vsid
WHERE vd.companyid = @companyid AND cancelled = 0 and vd.shopid = @SHOPID
AND vd.losdcnid = @ID
)
SET @AMT1 =(
select ISNULL(sum(pdPaidAmount),0) FROM ahqpaymentvoucherdetails pd
INNER JOIN ahqPaymentvoucherheader ph ON pd.pdcompanyid = ph.phcompanyid
AND pd.pdpaymentid = ph.phpaymentid
WHERE ph.phcompanyid = @companyid AND ph.phcancelled = 0 AND pd.pdshopid = @SHOPID
AND pd.shopdcnid = @ID
)
INSERT INTO #temp
SELECT s.shopname ,losdcnNo, losdcnDate,ISNULL(losdcnamount-(@AMT+@AMT1),0),''0.00'',losdcnid,
''SDEBIT'',losdcnshopid,''0.00''
FROM losdebitcreditnote b INNER JOIN ashops s ON s.shopid = b.losdcnshopid
WHERE b.losdcndebit = 0 AND b.losdcnCancelled = 0 AND b.losdcnCompanyID = @companyid
AND b.losdcnVendorID = @vendorid AND  s.accountable IS NOT NULL
AND losdcndepartmentid = @departmentid AND (@AMT +@AMT1) < losdcnamount  and b.losdcnid = @id
SELECT @Index = @Index + 1
END
----------------------------------------------------------------------------------------------
--DELETE FROM  #tempid
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempid
SELECT ReceiptID,'''' FROM receiptvoucherheader
WHERE cancelled =0 AND companyid = @companyid AND vendorid = @vendorid
END
ELSE
BEGIN
INSERT INTO #tempid
SELECT ReceiptID,'''' FROM  receiptvoucherheader
WHERE cancelled =0 AND companyid = @companyid AND vendorid = @vendorid AND departmentid = @departmentid
END
SET @index = 1
SET @RECCOUNT =(SELECT COUNT(id) FROM #tempid )
WHILE (@index < = @RECCOUNT)
BEGIN
set @ID =(select billid from #tempid where id = @INDEX)
SET @AMT=(
select ISNULL(sum(settlementamount),0) FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vh.companyid = vd.companyid AND
vh.vsid = vd.vsid
WHERE vd.receiptid = @ID  AND vh.cancelled = 0 AND vh.companyid = @companyid
)
INSERT INTO #temp
SELECT ''Head Quarters'',ReceiptNo, ReceiptDate,ISNULL(customeramount- @AMT,0),''0.00'',ReceiptID,
''RECEIPT'','''',''0.00''
FROM  receiptvoucherheader
WHERE cancelled =0 AND companyid = @companyid AND vendorid = @vendorid AND
departmentid = @departmentid AND @AMT < customeramount and ReceiptID = @ID
SELECT @Index = @Index + 1
END
----------------------------------------------------------------------------------------- RefNo-3
--Inter divisional bill
TRUNCATE TABLE #tempid
IF @departmentid = 0
BEGIN
INSERT INTO #tempID
SELECT billsid,'''' FROM InterDivisionBillsHeader b
WHERE  b.cashpurchase = 0 AND b.cancelled = 0 AND b.companyid = @companyid AND
b.vendorid = @vendorid
END
ELSE
BEGIN
INSERT INTO #tempID
SELECT billsid,'''' FROM InterDivisionBillsHeader b
WHERE  b.cashpurchase = 0 AND b.cancelled = 0 AND b.DepartmentID= @departmentid AND
b.companyid = @companyid AND b.vendorid = @vendorid
END
SET @INDEX = 1
set @RECCOUNT =(SELECT COUNT(billid) FROM #tempid )
WHILE (@INDEX <= @RECCOUNT)
BEGIN
set @id =(select billid from #tempid where id = @INDEX)
SET @AMT = (
select ISNULL(sum(settlementamount),0) FROM vendorsettlementdetail vd
INNER JOIN vendorsettlementheader vh ON vh.vsid = vd.vsid
WHERE vd.companyid = vh.companyid AND vd.companyid = @companyid
AND cancelled = 0 AND vd.InterdivBillID  = @id
)
SET @AMT1 =(
select  isnull(sum(pdPaidAmount),0) from ahqpaymentvoucherdetails pd
inner join ahqPaymentvoucherheader ph on pd.pdpaymentid = ph.phpaymentid
where ph.phcompanyid = 1 and pd.pdcompanyid = ph.phcompanyid  and
ph.phcancelled = 0 and pd.pdIndevBillsID =@id
)
INSERT INTO #TEMP
SELECT ''Head Quarters'' ,billsno ,BillDate ,billamount-(@AMT+@AMT1+isnull(Discount,0)),
''0.00'' , billsid ,''INBILL'' ,'''' ,''0.00''
FROM InterDivisionBillsHeader B
where (@AMT + @AMT1 )< billamount and BILLSID = @id
set @INDEX =(@INDEX + 1 )
END
-----------------------------------------------------------------------------------------
SELECT * FROM #TEMP   where BillAmt >0
DROP TABLE #TEMP
drop table #tempid
END' 
END
GO
/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnPostedShopTransactions]'))
EXEC dbo.sp_executesql @statement = N'
-- ==================================================================
-- Created by : MANUNADH. U
-- Created on : 23/03/2012
-- Comments   : To create a report for showing unposted shop transactions
-- =================================================================
create VIEW [dbo].[vwUnPostedShopTransactions] AS
SELECT ''POS'' TransactionType,poshbillid TransactionId,poshbillno TransactionNo,poshbilldate TransactionDate,
	poshDepartmentid Departmentid,ph.poshshopid LocationId,S.ShopName LocationName
FROM losposheader ph
	LEFT OUTER JOIN Ashops S ON ph.poshshopid = S.ShopID
WHERE ph.poshcancellED = 0 and ph.poshpostED = 0
UNION ALL
SELECT ''Goods Return Note'',grnh.grnhGoodsReturnNoteID,grnhGoodsReturnNoteNo,grnhGoodsReturnNoteDate,
	grnhDepartmentId,grnh.grnhShopid,S.ShopName
FROM LOsGoodsReturnNoteHeader grnh
	LEFT OUTER JOIN Ashops S ON grnh.grnhShopid = S.ShopID
WHERE  grnhPosted = 0 and grnhCancel = 0
UNION ALL
SELECT ''Goods Exchange'',sehExchangeId,sehExchangeNo,sehExchangeDate,sehDepartmentID,sehShopID,S.ShopName
FROM losposExchangeHeader
	LEFT OUTER JOIN Ashops S ON sehShopID = S.ShopID
WHERE sehcancelled = 0 and sehposted = 0
UNION ALL
SELECT ''Invoice'',ihInvoiceId,ihinvoiceno,ihinvoicedate,ihdepartmentid,ihShopID,S.ShopName
FROM losinvoiceheader I
	LEFT OUTER JOIN Ashops S ON I.ihShopID = S.ShopID
WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 and ihcashinvoice =0 and ihtype =''i''
UNION ALL
SELECT ''Service Invoice'',aiInvoiceID,aiInvoiceNo,aiInvoiceDate,aiDepartmentID,aiShopID,S.ShopName
FROM losAccountsInvoiceHeader
	LEFT OUTER JOIN Ashops S ON aiShopID = S.ShopID
WHERE aiCancelled = 0 and aiPosted = 0 and aiProforma = 0
UNION ALL
SELECT ''Direct Invoice'', ihinvoiceId, ihinvoiceno, ihinvoicedate,ihdepartmentId,IhShopID,S.ShopName
FROM losSpecialInvoiceHeader
	LEFT OUTER JOIN Ashops S ON IhShopID = S.ShopID
WHERE ihcancelled = 0 and ihtransfinished = 1 and ihposted = 0 and ihproforma = 0
UNION ALL
SELECT ''Payments'', phPaymentID, phpaymentno, phpaymentdate,phDepartmentID,phShopID,S.ShopName
FROM LOsPaymentVoucherHeader
	LEFT OUTER JOIN Ashops S ON phShopID = S.ShopID
WHERE phpostED =0 and phcancellED =0
UNION ALL
SELECT ''Local Purchase'',lphbillid,lphbillno,lphBillDate,lphdepartmentid,lphShopID,S.ShopName
FROM losLocalPurchaseHeader
	LEFT OUTER JOIN Ashops S ON lphShopID = S.ShopID
WHERE lphcancellED = 0 and lphpostED = 0 and lphConfirmed=1
UNION ALL
SELECT ''Goods Arrival To Shop'',gahArrivalID,gahArrivalNo, gahArrivalDate, gahdepartmentid,gahShopid,S.ShopName
FROM  LosGoodsArrivaltoShopHeader ga
	LEFT OUTER JOIN Ashops S ON gahShopid = S.ShopID
WHERE  gahCancelled = 0 and gahposted = 0 and gahTransFinished = 1
UNION ALL
SELECT ''Transfer In'',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName
FROM LOSTransferinheader tinh
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = ''TI''
UNION ALL
SELECT ''Transfer Out'',ToHID, ToHNO, ToHDate,tohdepartmentid ,TOHShopid,S.ShopName
FROM mestransferoutheader tinh
	LEFT OUTER JOIN Ashops S ON TOHShopid = S.ShopID
WHERE  ToHcancelled =0 and ToHPosted =0 and ToHTransFinished = 1 and tohtype =''TO''
UNION ALL
SELECT ''Despatch To Godown'',dgHID,dgHNO,dgHDate,dghdepartmentid,dghShopID,S.ShopName
FROM mesDespatchToGodownHeader tinh
	LEFT OUTER JOIN Ashops S ON dghShopID = S.ShopID
WHERE  dgHcancelled = 0 and dgHPosted = 0 and dgHTransFinished = 1
UNION ALL
SELECT ''Reexport'',rehExportId,rehExportNo,rehExportDate,rehdepartmentid,rehShopID,S.ShopName
FROM losExportHeader
	LEFT OUTER JOIN Ashops S ON rehShopID = S.ShopID
WHERE rehcancelled =0 and rehposted =0 and rehcashinvoice =0 and rehtype =''i''
UNION ALL
SELECT ''Inhouse Consumption'',whID, whno, whdate,whdepartmentid,whShopID,S.ShopName
FROM loswriteoffheader
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID
WHERE WhCancelled =0 and whposted =0 and whtype=''I'' and whVerified=1
UNION ALL
SELECT ''Inhouse Return'',IHRHID,IHRHNo,IHRHDate,IHRHdepartmentid,IHRHShopID,S.ShopName
FROM LOs_InHouseCons_ReturnHeader
	LEFT OUTER JOIN Ashops S ON IHRHShopID = S.ShopID
WHERE IHRHCancelled =0 and IHRHposted=0 and IHRHConfirmed=1
UNION ALL
SELECT ''Stock Write Off Shop'',whId,whno,whdate,whdepartmentId,whShopID,S.ShopName
FROM loswriteoffheader
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID
WHERE whcancellED =0 AND whposted =0 and whType=''W''
UNION ALL
SELECT ''Stock Verification Shop'',svhId, svhno, svhdate,svhdepartmentId,svhShopId,S.ShopName
FROM losstockverificationheader
	LEFT OUTER JOIN Ashops S ON svhShopId = S.ShopID
WHERE svhcancelled =0 and svhposted =0
--UNION ALL
--SELECT ''Recovery Shop'',srId,srtransno,srdate,srDepartmentId,srShopID,S.ShopName
--FROM losStockRecovery r
--	LEFT OUTER JOIN Ashops S ON R.srShopID = S.ShopID
--WHERE srposted =0
UNION ALL
SELECT ''Booking Advance'',serbookhid,serbookhinspectionno,serbookhInspectionDate,serbookhdepartmentid,
	serbookhshopid,S.ShopName
FROM losservicebookingheader bk
	LEFT OUTER JOIN Ashops S ON serbookhshopid = S.ShopID
WHERE serbookhinpcancelled = 0 and serbookhposted = 0 and serbookadvanceamount > 0 and serbookhstatus <>''n''
UNION ALL
SELECT ''Booking Invoice'',li.serinvhid,li.serinvno,li.serinvhdate,li.serinvhdepartmentid,li.serinvhshopid,S.ShopName
FROM losserviceinvheader li
	LEFT OUTER JOIN Ashops S ON li.serinvhshopid = S.ShopID
WHERE li.serinvhcancelled =0 AND li.serinvhposted =0
UNION ALL
SELECT ''Booking Cancellation'',bkcancellId,bkcancellno,bkcancelldate,0,bkcancellshopid,S.ShopName
from losbookingcancellation
	LEFT OUTER JOIN Ashops S ON bkcancellshopid = S.ShopID
where bkcancellId = 0 and  bkcancellcancelled=0 AND bkcancellposted=0
UNION ALL
SELECT ''Inter Department Sales'',ToHID,ToHNO,ToHDate,tohdepartmentid,ToHShopid,S.ShopName
FROM mestransferoutheader tinh
	LEFT OUTER JOIN Ashops S ON ToHShopid = S.ShopID
WHERE  ToHcancelled =0 AND ToHPosted =0 AND ToHTransFinished = 1 AND tohType =''IS''
UNION ALL
SELECT ''Inter Department Purchase'',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName
FROM LOSTransferinheader tinh
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = ''IP''
UNION ALL
SELECT ''Shop Debit/Credit Note'',losDCNId,losDCNNo,losDCNDate,losdcndepartmentid,losDCNShopid,S.ShopName
from losDebitCreditNote
	LEFT OUTER JOIN Ashops S ON losDCNShopid = S.ShopID
where losDCNPosted = 0 and losDCNCancelled = 0
UNION ALL
SELECT '' Agreement'',mghAgreementID, mghAgreementNo,mghAgreementDate,mghDepartmentid, mghShopId,S.ShopName
FROM losApartmentAgreementHeader ah
	LEFT OUTER JOIN Ashops S ON mghShopId = S.ShopID
WHERE mghCancelled = 0 and mghPosted = 0 and mghadvdate is not null
UNION ALL
SELECT ''Utility Bill Details'',tbhBillId,tbhBillNo,tbhBillDate,tbhDepartmentID,tbhShopId,S.ShopName
from losTenantServiceBillHeader
	LEFT OUTER JOIN Ashops S ON tbhShopId = S.ShopID
where tbhPosted=0 and tbhCancelled=0
UNION ALL
SELECT ''Room Billing'',abhBillId ,abhBillNo,abhBillDate,abhDepartmentid,abhSHopID,S.ShopName
FROM losApartmentBillHeader
	LEFT OUTER JOIN Ashops S ON abhSHopID = S.ShopID
WHERE abhPosted=0 and abhCancelled=0
UNION ALL
SELECT ''Check Out Returns'',chID,chNo,chDate,ChDepartmentID,chShopID,S.ShopName
FROM losApartmentCheckOut
	LEFT OUTER JOIN Ashops S ON chShopID = S.ShopID
WHERE chCancelled = 0 and chPosted = 0 and (chDepositAmount>0 or chAvaliedAmount>0)
UNION ALL
SELECT ''HP Invoices'',hpqhQuotationID,hpqhQuotationNo,hpqhQuotationDate,0, hpqhShopId, S.ShopName
FROM loshpinvoiceheader
	LEFT OUTER JOIN Ashops S ON hpqhShopId = S.ShopID
WHERE hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and hpqhType=''I''
UNION ALL
SELECT ''HP Shop Receipts'',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType=''S''
UNION ALL
SELECT ''HP Shop Down Payment'',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType=''A''
UNION ALL
SELECT ''HP Resale'',hphResaleID,hphResaleNo,hphReSaleDate,0,hphShopID,S.ShopName
FROM  losHpReSaleHeader
	LEFT OUTER JOIN Ashops S ON hphShopID = S.ShopID
WHERE hphCancel =0 and hphposted =0
UNION ALL
SELECT ''HP Repossession'',hprhRepossessionID,hprhRepossessionNo,hprhRepossessionDate,0,hprhShopId,S.ShopName
FROM losHpRepossessionHeader
	LEFT OUTER JOIN Ashops S ON hprhShopId = S.ShopID
WHERE hprhCancel =0 and hprhposted =0
UNION ALL
SELECT ''Shop Purchase Return'',whID,whNo,whDate,whDepartmentId,whShopId,S.ShopName
FROM losPurchaseReturnHeader
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID
WHERE whCancelled = 0 And whPosted = 0 And whType =''P''
UNION ALL
SELECT ''Food and Beverages Bill'',poshBillID,poshBillNo,poshBillDate,poshDepartmentid,poshShopID,S.ShopName
FROM losPosFandBHeader h
	LEFT OUTER JOIN Ashops S ON poshShopID = S.ShopID
WHERE h.poshCancelled=0 and h.poshPosted = 0
UNION ALL
SELECT ''Goods Arrival Inventory'',ahArrivalId,ahArrivalNo,ahArrivalDate,ahdepartmentid,
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN 0
		WHEN ahShopID IS NULL THEN AHGodownID ELSE ahShopID END,
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN ''HQ''
		WHEN ahShopID IS NULL THEN G.GodownName ELSE S.ShopName END	
FROM LOiArrivalHeader ga
	LEFT OUTER JOIN Ashops S ON ahShopID = S.ShopID
	LEFT OUTER JOIN aGodown G ON G.GodownID=AHGodownID
WHERE ahCancelled = 0 and ahPosted = 0 and ahTransFinished = 1
UNION ALL
SELECT ''Goods Dispatch to Shop'',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhShopID,S.ShopName
FROM meiDespatchToShopHeader
	LEFT OUTER JOIN Ashops S ON dhShopID = S.ShopID
WHERE dhCancelled = 0 and dhPosted =0 and dhTransFinished=1
UNION ALL
SELECT ''Stock Write off Inventory'',whID, whno, whdate,whdepartmentid,whGodownID,G.GodownName
FROM loiwriteoffheader
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whcancellED = 0 and whposted = 0 and whType = ''W''
UNION ALL
SELECT ''Stock Verification Inventory'',svhid,svhno,svhdate,svhdepartmentid,svhGodownid,G.GodownName
FROM loiStockVerificationHeader
	LEFT OUTER JOIN aGodown G ON G.GodownID=svhGodownid
WHERE svhcancelled =0 and svhposted =0
UNION ALL
SELECT ''Recovery Inventory'',srID,srtransno,srDate,0,srGodownID,G.GodownName
FROM loiStockRecovery i
	LEFT OUTER JOIN aGodown G ON G.GodownID=srGodownID
WHERE srposted = 0
UNION ALL
SELECT ''Special Despatch'',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhgodownid,G.GodownName
FROM meiSpecialDespatchToShopHeader
	LEFT OUTER JOIN aGodown G ON G.GodownID=dhgodownid
WHERE dhCancelled = 0 and dhposted = 0
UNION ALL
SELECT ''Godown to Godown Transfer'',gthDespatchID,gthDespatchNo,gthDespatchDate,gthDepartmentId,gthFromGodownId,
	G.GodownName
FROM MEiGodownTransferHeader tinh
	LEFT OUTER JOIN aGodown G ON G.GodownID=gthFromGodownId
WHERE gthCancelled = 0 and gthPosted = 0 and gthTransFinished = 1
UNION ALL
SELECT ''Asset Transfer'',whID, whno, whdate,whDepartmentId,whGodownID,G.GodownName
FROM loiWriteOffHeader
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0  and whType =''A''
UNION ALL
SELECT ''Purchase Return'',whID, whNo, whDate,whDepartmentId,whGodownId,G.GodownName
FROM loiWriteOffHeader
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0 and whType =''R''
UNION ALL
SELECT ''HQ Stock Write Off'',swID,swTransCode,swDate,0,
	CASE WHEN swShopID IS NULL THEN swGodownID ELSE swShopID END ,
	CASE WHEN swShopID IS NULL THEN G.GodownName ELSE S.ShopName  END
FROM moStockWriteOffHQ
	LEFT OUTER JOIN Ashops S ON swShopID = S.ShopID
	LEFT OUTER JOIN aGodown G ON G.GodownID=swGodownID
WHERE swposted =0
UNION ALL
SELECT ''Business Promotion'',wchID,wchNo,wchDate,0,wchSHOPID,S.ShopName
FROM losWarrentyClaimHeader
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
WHERE wchType=''BP'' and wchposted=0 and wchCancelled=0 and wchConfirmed=1
UNION ALL
SELECT ''Warrenty Claim'',wchID,wchNo,wchDate,0,wchShopID,S.ShopName
FROM losWarrentyClaimHeader
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
WHERE wchType=''WC'' and wchposted=0 and wchCancelled=0 and wchConfirmed=1'
GO
/****** Object:  View [dbo].[vwUnConfirmedTransactions]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnConfirmedTransactions]'))
EXEC dbo.sp_executesql @statement = N'
-- Created by : Hariharan
-- Created on : 19/01/2004 (at Male'' From V2)
-- Comments   : For alert display of unconfirmed transactions
-- =================================================================
-- Ref.No:1
-- Upgraded By : AADYAKUMAR D V
-- Upgraded On : 13-03-2012
-- Upgrade     : Added more transactions
-- ==================================================================
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Create VIEW [dbo].[vwUnConfirmedTransactions] AS
SELECT ''Despatch Note Generation'' TransactionType, dnmDespatchNoteId TransactionId,
dnmDespatchNoteNo TransactionNo, dnmDespatchNoteDate TransactionDate,
0 LocationId, ''HQ'' LocationName, Departmentid, ''H'' LocType
FROM aHqDespatchNoteMain Main LEFT OUTER JOIN aHqDespatchNoteHeader Header
ON Main.dnmDespatchNoteId = Header.dhDespatchNoteMainID
WHERE dnmCancelled = 0 AND dhTransFinished = 0 group by
dnmDespatchNoteId, dnmDespatchNoteNo, dnmDespatchNoteDate, Departmentid
UNION ALL
SELECT ''Issue Note Generation'' TransactionType, inmIssueNoteId TransactionId,
inmIssueNoteNo TransactionNo, inmIssueDate TransactionDate,
0 LocationId, ''HQ'' LocationName, Departmentid, ''H'' LocType
FROM aHqIssueNoteMain Main LEFT OUTER JOIN aHqIssueNoteHeader Header
ON Main.inmIssueNoteId = Header.inhIssueNoteMainId
WHERE inmCancel = 0
AND inhTransFinished = 0 group by inmIssueNoteId ,
inmIssueNoteNo, inmIssueDate, Departmentid
UNION ALL
SELECT ''Costing'', chCostingId, chCostingNo, chCostingDate, 0, ''HQ'', chDepartmentId, ''H'' LocType
FROM loaCostingHeader WHERE chCancelled = 0 AND chCostingDone = 0
and chCostingId >0
UNION ALL
SELECT ''Local Purchase Costing'', lpchCostingId, lpchCostingNo, lpchDate, 0, ''HQ'',
lpchDepartmentid, ''H'' LocType FROM loaLocalPurchaseCostingHeader
WHERE lpchCancelled = 0
AND lpchCostingDone = 0
UNION ALL
SELECT ''Item Split Costing'', scfhId, scfhNo, scfhDate, 0, ''HQ'', scfhdepartmentid, ''H'' LocType
FROM loaItemSplitCostingHeader
WHERE scfhCancelled = 0
AND scfhCostFixed = 0
UNION ALL
SELECT ''Goods Arrival To Godown'', ahArrivalId, ahArrivalNo, ahArrivalDate,
ahLocalGodownId, aGodown.GodownName, ahDepartmentid, ''G'' LocType
FROM loiArrivalHeader LEFT OUTER JOIN aGodown
ON ahLocalGodownId = GodownId
WHERE ahCancelled = 0
AND ahTransFinished = 0
UNION ALL
SELECT ''Despatch To Shop'', dhDespatchId, dhDespatchNo, dhDespatchDate,
dhGodownId, GodownName, dhDepartmentId, ''g'' LocType
FROM meiDespatchToShopHeader LEFT OUTER JOIN aGodown
ON dhGodownId = GodownId
WHERE dhCancelled = 0
AND dhTransFinished = 0
UNION ALL
SELECT ''Godown To Godown Transfer'', gthDespatchId, gthDespatchNo, gthDespatchDate,
gthFromGodownId, GodownName, gthDepartmentId, ''H'' LocType
FROM meiGOdownTransferHeader LEFT OUTER JOIN aGodown
ON gthFromGodownId = GodownId
WHERE gthCancelled = 0 AND gthTransFinished = 0
UNION ALL
SELECT ''Goods Arrival To Shop'', gahArrivalId, gahArrivalNo, gahArrivalDate,
gahShopId, ShopName, gahDepartmentId, ''S'' LocType
FROM LOsGoodsArrivaltoShopHeader LEFT OUTER JOIN aShops
ON gahShopId = ShopId
WHERE gahCancelled = 0
AND gahTransFinished = 0
UNION ALL
--SELECT ''Request To Shop'', srhRequestId, srhRequestNo, srhRequestDate,
--srhShopId, ShopName, Departmentid , ''S'' LocType
--FROM mesRequestToShopHeader LEFT OUTER JOIN aShops
--ON srhShopId = aShops.ShopId
--WHERE srhCancelled = 0
--AND srhTransFinished = 0
--UNION ALL
SELECT ''Request To HQ'', grhRequestId, grhRequestNo, grhRequestDate,
grhShopId, ShopName, departmentid, ''S'' LocType
FROM mosGoodsRequestHeader LEFT OUTER JOIN aShops
ON grhShopId = aShops.ShopId
WHERE grhCancel = 0
AND grhTransFinished = 0
--UNION ALL
--SELECT ''Transfer Out'', tohId, tohNo, tohDate, tohShopId,
--ShopName, tohDepartmentid, ''S'' LocType
--FROM mesTransferOutHeader LEFT OUTER JOIN aShops
--ON tohShopId = aShops.ShopId
--WHERE tohCancelled = 0
--AND tohTransFinished = 0
UNION ALL
SELECT ''Transfer In'', tihId, tihNo, tihDate, tihShopId,
ShopName, tihDepartmentid, ''S'' LocType
FROM losTransferInHeader LEFT OUTER JOIN aShops
ON tihShopId = aShops.ShopId
WHERE tihCancel = 0
AND tihTransFinished = 0
UNION ALL
SELECT ''Shop To Godown Transfer'', dghID, dghNo, dghDate, dghShopId,
ShopName, dghDepartmentid, ''S'' LocType
FROM mesDespatchtoGodownHeader LEFT OUTER JOIN aShops
ON dghShopid = aShops.ShopId
WHERE dghCancelled = 0 AND dghTransFinished = 0
UNION ALL
SELECT ''Special Invoice'', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopId,
ShopName, ihDepartmentid, ''S'' LocType FROM losSpecialInvoiceHeader LEFT OUTER JOIN aShops
ON ihShopId = aShops.ShopId WHERE ihCancelled = 0 AND ihTransFinished = 0
--Ref.No:1------------------------------START----------------------------------------------------
UNION ALL
SELECT ''Local Purchase'', lphBillID, lphBillNo, lphBillDate, lphShopID,
ShopName, lphDepartmentID, ''S'' LocType FROM loslocalpurchaseheader LEFT OUTER JOIN aShops
ON lphShopID = aShops.ShopId WHERE lphCancelled = 0 AND lphConfirmed = 0
UNION ALL
SELECT ''Warrenty Claim'', wchID, wchNo, wchDate, wchShopID,
ShopName, DepartmentID, ''S'' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType=''WC''
UNION ALL
SELECT ''Business Promotion'', wchID, wchNo, wchDate, wchShopID,
ShopName, DepartmentID, ''S'' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType=''BP''
UNION ALL
SELECT ''Hire Purchase Invoice'', hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhShopID,
ShopName, DepartmentID, ''S'' LocType FROM losHpInvoiceHeader LEFT OUTER JOIN aShops
ON hpqhShopID = aShops.ShopId WHERE hpqhCancel = 0 AND hpqhConfirmed = 0
UNION ALL
SELECT ''InHouse Return/Exchanged'', IHRHID, IHRHNo, IHRHDate, IHRHShopID,
ShopName, DepartmentID, ''S'' LocType FROM LOs_InHouseCons_ReturnHeader LEFT OUTER JOIN aShops
ON IHRHShopID = aShops.ShopId WHERE IHRHCancelled = 0 AND IHRHConfirmed = 0
UNION ALL
SELECT ''MerGing'', lshID, lshNo, lshDate, lshShopID,
ShopName, DepartmentID, ''S'' LocType FROM losMergeHeader LEFT OUTER JOIN aShops
ON lshShopID = aShops.ShopId WHERE lshCancelled = 0 AND lshTransFinished = 0
UNION ALL
SELECT ''Purchase Return'', WhID, WhNo, WhDate, whShopID,
ShopName, DepartmentID, ''S'' LocType FROM losPurchaseReturnheader LEFT OUTER JOIN aShops
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whtransfinished = 0
UNION ALL
--Invoice confirmation is not using in program
--SELECT ''Credit Invoice'', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,
--ShopName, DepartmentID, ''S'' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops
--ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType=''I''
--UNION ALL
SELECT ''Purchase Quotation'', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,
ShopName, DepartmentID, ''S'' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType=''Q''
UNION ALL
SELECT ''Purchase Order'', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,
ShopName, DepartmentID, ''S'' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType=''P''
UNION ALL
SELECT ''Purchase Request'', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,
ShopName, DepartmentID, ''S'' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType=''R''
UNION ALL
SELECT ''Shop Consumption'', WhID, WhNo, WhDate, whShopID,
ShopName, DepartmentID, ''S'' LocType FROM LOsWriteOffHeader LEFT OUTER JOIN aShops
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whverified = 0 and whtype=''I''
UNION ALL
SELECT ''Dummy POS'', poshBillID, poshBillNo, poshBillDate, poshShopID,
ShopName, DepartmentID, ''S'' LocType FROM LOsPosdummyHeader LEFT OUTER JOIN aShops
ON poshShopID = aShops.ShopId WHERE poshCancelled = 0 AND poshconfirmed = 0
UNION ALL
SELECT ''SerialNo Verification'', svhID, svhNo, svhDate, svhShopID,
ShopName, DepartmentID, ''S'' LocType FROM losSerialNoVerificationHeader LEFT OUTER JOIN aShops
ON svhShopID = aShops.ShopId WHERE svhCancel = 0 AND cofirmed = 0
UNION ALL
SELECT ''Stand By Issue'', ishIssueID, ishIssueNo, ishDate, ishShopID,
ShopName, DepartmentID, ''S'' LocType FROM losSerStandByIssueHeader LEFT OUTER JOIN aShops
ON ishShopID = aShops.ShopId WHERE ishCancelled = 0 AND ishConfirmed = 0
UNION ALL
SELECT ''Special Invoice Quotation'', IhInvoiceID, IhInvoiceNo, IhInvoiceDate, IhShopID,
ShopName, DepartmentID, ''S'' LocType FROM losSIQuotationHeader LEFT OUTER JOIN aShops
ON IhShopID = aShops.ShopId WHERE IhCancelled = 0 AND ihTransFinished = 0
UNION ALL
SELECT ''Request To Shop'', srhRequestId, srhRequestNo, srhRequestDate,
srhShopId, ShopName, Departmentid , ''S'' LocType
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops
ON srhShopId = aShops.ShopId
WHERE srhCancelled = 0
AND srhTransFinished = 0 and srhType=''r''
UNION ALL
SELECT ''Inter Division Sales Request'', srhRequestId, srhRequestNo, srhRequestDate,
srhShopId, ShopName, Departmentid , ''S'' LocType
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops
ON srhShopId = aShops.ShopId
WHERE srhCancelled = 0
AND srhTransFinished = 0 and srhType=''s''
UNION ALL
SELECT ''Transfer Out'', tohId, tohNo, tohDate, tohShopId,
ShopName, tohDepartmentid, ''S'' LocType
FROM mesTransferOutHeader LEFT OUTER JOIN aShops
ON tohShopId = aShops.ShopId
WHERE tohCancelled = 0
AND tohTransFinished = 0  and tohType=''TO''
UNION ALL
SELECT ''Inter Division Sales'', tohId, tohNo, tohDate, tohShopId,
ShopName, tohDepartmentid, ''S'' LocType
FROM mesTransferOutHeader LEFT OUTER JOIN aShops
ON tohShopId = aShops.ShopId
WHERE tohCancelled = 0
AND tohTransFinished = 0  and tohType=''IS''
--Ref.No:1-------------------------------END-----------------------------------------------'
GO
/****** Object:  StoredProcedure [dbo].[spFastMovingItem]    Script Date: 10/06/2012 14:17: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].[spFastMovingItem]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------
--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 [dbo].[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' 
END
GO
/****** Object:  View [dbo].[vwCustomerSalesmonthwise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesmonthwise]'))
EXEC dbo.sp_executesql @statement = N'
-- Created on   : 28/11/2008
-- Created by   : Benzigar S D
-- 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.
--   : Other charges changes
--   : specialinvoice chking transfinished, transfinished checking given for special invoice which were missed earlier
--   : Other charges given in group by clause to avoid doubling in Invoice queries
CREATE VIEW [dbo].[vwCustomerSalesmonthwise] AS
--1. shop cash sales invoice
select
ihcompanyid, ihshopid,ihinvoicedate, month(ihinvoicedate) month,year(ihinvoicedate) year ,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
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 ,
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, month(ihinvoicedate),year(ihinvoicedate), ihinvoiceid, ihbankcashaccid,
ihexchangerate,ihCustomerId ,ihdepartmentid, countryname,
CustomerCardNo, Customername, ihReferenceNo, ocd.ioAmount, ihExchangeRate, ihDepExRate
union all
-- 2.shop cash sales special invoice
select
ihcompanyid, ihshopid,ihinvoicedate, month(ihinvoicedate) month,year(ihinvoicedate) year, 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
from
losspecialinvoiceheader ih, losspecialinvoicedetail invd, vwShopSplInvItemAmount 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 ihproforma = 0 and
ihcashinvoice = 1 and invd.idratetype = 0 and ihcustomerid = c.customerid and
c.countryid = cm.countryid  and ih.ihtransfinished=1
group by
ihcompanyid, ihshopid, ihinvoiceno,ihinvoicedate, month(ihinvoicedate),year(ihinvoicedate), ihinvoiceid, ihbankcashaccid,
ihexchangerate, ihCustomerID, ihdepartmentid, countryname , CustomerCardNo,
Customername, ihReferenceNo, ihDepExRate
union all
-- 3. shop cash service invoice
select
vws.sicompanyid, vws.sishopid,vws.siinvoicedate, month(vws.siinvoicedate) month,year(vws.siinvoicedate) year, 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
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, month(ah.invoicedate) month,year(ah.invoicedate) year, 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
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, month(ah.invoicedate),year(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, month(ihinvoicedate) month,year(ihinvoicedate) year, 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
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 ,
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, month(ihinvoicedate),year(ihinvoicedate), ihinvoiceid, ihbankcashaccid,
ihexchangerate,ihCustomerId ,ihdepartmentid, countryname,
CustomerCardNo, Customername, ihReferenceNo, ocd.ioAmount, ihDepExRate
union all
-- 6. shop credit special invoice
select
ihcompanyid, ihshopid,ihinvoicedate, month(ihinvoicedate) month,year(ihinvoicedate) year, 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,
convert(numeric(18, 2), sum(vw.idunitprice) - sum(idcostprice * invd.idquantity)) profit,
convert(numeric(18, 2), (sum(vw.idunitprice) * ihDepExRate) - sum(idcostprice * invd.idquantity) * ihDepExRate) DepProfit,
convert(numeric(18, 2), (sum(vw.idunitprice) * ihExchangeRate) - sum(idcostprice * invd.idquantity) * 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
from
losspecialinvoiceheader ih, losspecialinvoicedetail invd,
vwShopSplInvItemAmount 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 invd.idratetype = 0 and
ihproforma = 0 and ihcustomerid = c.customerid and  c.countryid = cm.countryid
and ihTransfinished = 1
group by
ihcompanyid, ihshopid,ihinvoicedate, month(ihinvoicedate),year(ihinvoicedate), ihinvoiceid, ihCustomerID, ihbankcashaccid,
ihexchangerate, ihcustomerid, ihdepartmentid, countryname, ihinvoiceno,
customercardno, Customername, ihReferenceNo, ihDepExRate
union all
-- 7. shop credit service invoice
select
vws.sicompanyid, vws.sishopid,vws.siinvoicedate, month(vws.siinvoicedate) month,year(vws.siinvoicedate) year, 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
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, month(ah.invoicedate) month,year(ah.invoicedate) year, 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
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, month(ah.invoicedate),year(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, month(poshbilldate) month,year(poshbilldate) year, 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, ''''
from
losposheader ih
left outer join acustomermaster c on poshcustomerid = c.customerid
left outer join acountrymaster cm on c.CountryId = cm.CountryId,
losposdetail invd
where
ih.poshshopid = invd.posdshopid and ih.poshbillid = invd.posdbillid and
poshcancelled = 0
group by
poshcompanyid, poshshopid,poshbilldate, month(poshbilldate),year(poshbilldate), poshbillid, poshcashaccid,
poshexchangerate, poshCustomerId, poshdepartmentid, countryname, poshbillno,
customercardno, Customername, poshdepexRate  ,ih.poshCustomerName
union all
--10. shop Exchange out
select
sehcompanyid, sehshopid,sehexchangedate, month(sehexchangedate) month,year(sehexchangedate) year, 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, ''''
from
losposexchangeheader ih, losposexchangedetail invd,
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, month(sehexchangedate), Year(sehexchangedate), sehexchangeid, sehcashaccid,
poshexchangerate, poshCustomerId, sehdepartmentid, countryname, sehExchangeNo,
customercardno, sehexchangerate, Customername, sehDepExRate,Sehexchangername
Union All
-- 11. shop Exchange in
select
sehcompanyid, sehshopid,sehexchangedate, month(sehexchangedate) month,year(sehexchangedate) year, 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, ''''
from
losposexchangeheader ih, losposexchangedetail invd,
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, month(sehexchangedate),year(sehexchangedate), sehexchangeid,
sehcashaccid, poshexchangerate, poshCustomerId,sehdepartmentid, countryname,
sehExchangeNo, customercardno, sehexchangerate, Customername, sehdepExRate,Sehexchangername
union all
---- 12. shop credit rexport invoices - 22/12/2002
select
rehcompanyid, rehshopid,rehexportdate, month(rehexportdate) month,year(rehexportdate) year, 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
from
losExportHeader ih, losExportDetail invd, acustomermaster c, acountrymaster cm
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''
group by
rehcompanyid, rehshopid, rehExportNo,rehexportdate, month(rehExportDate),year(rehExportDate) , rehExportID, rehCustomerID,
rehbankcashaccid, rehexchangerate, rehCustomerid ,rehdepartmentid,
countryname, rehExportNO, CustomerCardNo, Customername, rehReferenceno, rehDepExRate
union all
-- Goods return note  - Kishore 23/06/2003
select grnCompanyId, grnhShopId,grnhGoodsReturnNoteDate, month(grnhGoodsReturnNoteDate) month,year(grnhGoodsReturnNoteDate) year, 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,
convert(numeric(18, 2), sum(grndUnitPrice) * grnhdepExRate -
sum(grnCostPrice * invd.grndQuantity * grnhdepExRate)) DepProfit,
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, ''''
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,
month(GrnhGoodsreturnnoteDate),year(GrnhGoodsreturnnoteDate), c.customername ,
grnhGoodsReturnNoteId, ih.GrnhGoodsreturnnoteNO, grnReturnAccId, grnhExchangeRate,
GrnhCustomerID, grnhdepartmentid, countryname, customercardno, grnhexchangerate,
grnhDepExRate'
GO
/****** Object:  View [dbo].[vwCustomerSalesByitem]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSalesByitem]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Created  ON : 06/05/03
--modified by  : Hariharan,sebin,Yogesh 09-07-09
--MOdified Date : 10/01/2004 ,17/06/09
--Modified Special Invoice details for Return after Despatch
--09-07-09Yogesh
--Modified Shop exchange sales.Earlier sedquantity quantity were taken as quntity.Now i have replaced it with sedExchangeQty and took absolute value and added a -ve sign in front of this.
--Modified Return After Despatch.Took absolute value of invd.reqqty and put -ve sign.It ensure that the RAD quantity is always negative
--Modified Special invoice to exclude RBD invoices.
--Wrote new section to handle RBD invoices.These invoices quantity must be deducted.
CREATE view [dbo].[vwCustomerSalesByitem] as
--1. shop sales invoice
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,
convert(numeric(18,2), sum(idunitprice)) as amount, ''c'' as transtype, ihCustomerId,
ihdepartmentid, convert(numeric(18, 2), sum(idcostprice * invd.idquantity)) costamt,
convert(numeric(18, 2), sum(idunitprice * ihDepExrate)) DepAmount,
convert(numeric(18, 2), sum(idunitprice * ihExchangeRate)) CmpAmount,
countryname, ihinvoiceno, convert(numeric(18, 2), sum(idunitprice)) - convert(
numeric(18, 2), sum(idcostprice * invd.idquantity)) profit,
convert(numeric(18, 2), sum(idunitprice * ihDepExRate)) - convert(
numeric(18, 2), sum(idcostprice * invd.idquantity * ihDepExRate)) as DepProfit,
convert(numeric(18, 2), sum(idunitprice * ihExchangeRate)) - convert(
numeric(18, 2), sum(idcostprice * invd.idquantity * ihExchangeRate)) as CmpProfit,
CustomerCardNo, iditemid , sum(invd.idquantity) quantity, ihsalespersonid, sum(isnull(idcdcustcur,0.0)) customs
from losinvoiceheader ih, losinvoicedetail invd, acustomermaster c, acountrymaster cm
where ih.ihshopid = invd.idshopid and ih.ihinvoiceid = invd.idinvoiceid and ihcancelled=0
and ihproforma = 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, iditemid, ihsalespersonid
union all
-- 2.shop sales special invoice
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,
convert(numeric(18, 2), sum(vw.idunitprice) )  as amount,
''d'' as transtype, ihCustomerID, ihdepartmentid,
convert(numeric(18, 2), sum(vw.costprice * invd.idquantity)) costamt,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihdepexRate)) DepAmt, -- ********
convert(numeric(18, 2), sum(vw.idunitprice * 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 , invd.iditemid, sum(invd.idquantity) quantity, ihsalespersonid, 0.0
from losspecialinvoiceheader ih, (select  idItemID,idInvoiceId,idShopid,idRateType,sum(idquantity) idquantity,idcostprice
from  losspecialinvoicedetail group by idItemID,idInvoiceId,idShopid,idRateType,idcostprice) invd,
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 ihproforma = 0 and
invd.idratetype = 0 and ihcustomerid = c.customerid and
c.countryid = cm.countryid  and ihTransfinished = 1
and ih.ihnoofocdetails=0--09-07-09Yogesh.To exclude RBD invoices.It will handle separately in another section
group by ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate,
ihinvoiceid, ihbankcashaccid, ihexchangerate, ihCustomerID,
ihdepartmentid, countryname , CustomerCardNo, invd.iditemid, ihsalespersonid
union all
-- 3. shop cash sales
select poshcompanyid, poshshopid, poshbilldate, poshcashaccid,
convert(numeric(18,2), sum(posdunitprice)) as amount,
''c'' as transtype, poshCustomerId, poshdepartmentid,
convert(numeric(18, 2), sum(posdcostprice * invd.posdquantity)) costamt,
convert(numeric(18, 2), sum(posdunitprice * ih.poshDepExRate)) DepAmount,
convert(numeric(18, 2), sum(posdunitprice * 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 , invd.posdItemID, sum(invd.posdQuantity) quantity, poshsalespersonid, 0.0
from losposheader ih,
losposdetail invd ,acustomermaster c,
acountrymaster cm
where ih.poshshopid = invd.posdshopid and
ih.poshbillid = invd.posdbillid and poshcancelled=0
and poshcustomerid = c.customerid and c.countryid = cm.countryid group by poshcompanyid,
poshshopid, poshbilldate, poshbillid, poshcashaccid, poshexchangerate, poshCustomerId,
poshdepartmentid, countryname, poshbillno, customercardno, invd.posdItemID, poshsalespersonid
union all
--4. shop exchange sales
select sehcompanyid, sehshopid, sehexchangedate, sehCashAccID,
convert(numeric(18,2),sum(sedunitprice)) as amount,
''c'' as transtype, poshCustomerId, sehdepartmentid,
convert(numeric(18, 2), sum(sedcostprice * invd.sedquantity)) costamt,
convert(numeric(18, 2), sum(sedunitprice * sehDepExRate)) DepAmount,
convert(numeric(18, 2), sum(sedunitprice * sehExchangeRate)) CmpAmount,
countryname, poshbillno,
sum(sedunitprice) - sum(sedcostprice * invd.sedquantity) profit,
sum(sedunitprice) - sum(sedcostprice * invd.sedquantity * sehDepExRate) DepProfit,
sum(sedunitprice) - sum(sedcostprice * invd.sedquantity * sehExchangeRate) CmpProfit,
customercardno, invd.seditemid, -abs(sum(invd.sedExchangeQty))-- sum(invd.sedquantity)Yogesh 09-07-09
quantity, sehsalespersonid, 0.0
from losposexchangeheader ih,
losposexchangedetail invd ,acustomermaster c,
acountrymaster cm, losposheader  where ih.sehshopid = invd.sedshopid and
ih.sehexchangeid  = invd.sedexchangeid and sehcancelled=0
and poshcustomerid = c.customerid and c.countryid = cm.countryid and sehbillid = poshbillid
and sehshopid = poshshopid group by sehcompanyid, sehshopid, sehexchangedate, sehexchangeid,
sehcashaccid, poshexchangerate, poshCustomerId,
sehdepartmentid, countryname, poshbillno, customercardno, sehexchangerate, invd.seditemid, sehsalespersonid
union all
---- 5. shop credit rexport invoices
select rehcompanyid, rehshopid, rehexportdate, rehbankcashaccid,
convert(numeric(18,2), sum(isnull(redunitprice,0)) ) as amount,
''c'' as transtype , ih.rehCustomerid, ih.rehdepartmentid,
convert(numeric(18, 2), sum(isnull(redcostprice,0) * invd.redquantity)) costAmt,
convert(numeric(18, 2), sum(redunitprice * rehDepExRate)) DepAmount,
convert(numeric(18, 2), sum(redunitprice * 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, invd.redItemID, sum(redquantity) quantity, rehsalespersonid, 0.0
from losExportHeader ih, losExportDetail invd, acustomermaster c, acountrymaster cm 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''
group by rehcompanyid, rehshopid, rehExportNo, rehExportDate, rehExportID, rehCustomerID,
rehbankcashaccid, rehexchangerate, rehCustomerid ,rehdepartmentid,
countryname, rehExportNO, CustomerCardNo, invd.redItemID, rehsalespersonid
union all
-- 6.shop sales special invoice  for Return After Despatch
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,
convert(numeric(18, 2), sum(vw.idunitprice) )  as amount,
''d'' as transtype, ihCustomerID, ihdepartmentid,
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty))) costamt,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihdepexRate)) DepAmt, -- ********
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihExchangeRate)) CmpAmt,
countryname, ihinvoiceno,
convert(numeric(18, 2), sum(vw.idunitprice)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty))) Profit,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihDepExRate)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty) * ih.ihDepExRate)) DepProfit,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihExchangeRate)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty)* ihExchangeRate)) Cmpprofit,
--
CustomerCardNo , invd.iditemid, -abs(sum(invd.reqqty)) quantity, ihsalespersonid, 0.0  --09-07-09Yogesh.Took absolute value of invd.reqqty and put -ve sign.It ensure that the RAD quantity is always negative
from losspecialinvoiceheader ih, (select  idItemID,idInvoiceId,idShopid,idRateType,sum(reqqty) reqqty,idcostprice
from  losspecialinvoicedetail group by idItemID,idInvoiceId,idShopid,idRateType,idcostprice) invd,
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 ihproforma = 0 and
invd.idratetype = 1 and ihcustomerid = c.customerid and
c.countryid = cm.countryid  and ihTransfinished = 1
group by ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate,
ihinvoiceid, ihbankcashaccid, ihexchangerate, ihCustomerID,
ihdepartmentid, countryname , CustomerCardNo, invd.iditemid, ihsalespersonid
-- 7.shop sales special invoice  for Return Before Despatch
union all
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,
convert(numeric(18, 2), sum(vw.idunitprice) )  as amount,
''d'' as transtype, ihCustomerID, ihdepartmentid,
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty))) costamt,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihdepexRate)) DepAmt, -- ********
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihExchangeRate)) CmpAmt,
countryname, ihinvoiceno,
convert(numeric(18, 2), sum(vw.idunitprice)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty))) Profit,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihDepExRate)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty) * ih.ihDepExRate)) DepProfit,
convert(numeric(18, 2), sum(vw.idunitprice * ih.ihExchangeRate)) -
convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty)* ihExchangeRate)) Cmpprofit,
--
CustomerCardNo , invd.iditemid, -abs(sum(invd.reqqty)) quantity, ihsalespersonid, 0.0
from losspecialinvoiceheader ih, (select  idItemID,idInvoiceId,idShopid,idRateType,sum(reqqty) reqqty,idcostprice
from  losspecialinvoicedetail group by idItemID,idInvoiceId,idShopid,idRateType,idcostprice) invd,
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 ihproforma = 0 and
invd.idratetype = 0 and ihcustomerid = c.customerid and
c.countryid = cm.countryid  and ihTransfinished = 1 and ihNoofOcdetails >0
group by ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate,
ihinvoiceid, ihbankcashaccid, ihexchangerate, ihCustomerID,
ihdepartmentid, countryname , CustomerCardNo, invd.iditemid, ihsalespersonid'
GO
/****** Object:  View [dbo].[vwCustomerSales]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSales]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
/****** Object:  View [dbo].[vwCustomerSettlementHeader]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSettlementHeader]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 06/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For Customer Settlement in Header Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on     : 31-12-2008
-- Modified by     : Regin
-- Comments        : Cancelled field is added as it is needed to add Cancelled watermark
-------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCustomerSettlementHeader] AS
---For HQ receipts
SELECT  CSH.CSID SettlementId,CSH.CompanyID CompanyID,CSH.CSNO SettlementNo,CSH.CSDate SettlementDate,
CSH.DepartmentID DepartmentID,AD.DepartmentName DepartmentName ,CSH.ShopID ,
RVH.ReceiptNo ReferenceNo , ''HQ Receipts'' Type,
ac.CustomerID CustomerID,ac.CustomerName CustomerName,CSH.FinancialID FinancialID, CSH.Cancelled
FROM    CustomerSettlementHeader CSH
INNER JOIN   ReceiptVoucherHeader RVH ON CSH.ReceiptID = RVH.ReceiptID
INNER JOIN   aCustomerMaster ac ON CSH.CustomerID=ac.CustomerID
INNER JOIN   aDepartmentMaster AD ON CSH.DepartmentID=AD.DepartmentID
UNION ALL
-- For HQ Debit Credit Note
SELECT  CSH.CSID,CSH.CompanyID,CSH.CSNO,CSH.CSDate,CSH.DepartmentID,AD.DepartmentName,CSH.ShopID,
DCN.DCNNo,''HQ DCN'',ac.CustomerID,ac.CustomerName,CSH.FinancialID, CSH.Cancelled
FROM    CustomerSettlementHeader CSH
INNER JOIN   DebitCreditNote DCN ON CSH.dcnid = DCN.DCNId
INNER JOIN   aCustomerMaster ac ON CSH.CustomerID=ac.CustomerID
INNER JOIN   aDepartmentMaster AD ON CSH.DepartmentID=AD.DepartmentID
UNION ALL
-- For Shop Receips [Dummy Receipt]
SELECT  CSH.CSID,CSH.CompanyID,CSH.CSNO,CSH.CSDate,CSH.DepartmentID,AD.DepartmentName,CSH.ShopID,
LDRH.drNo,''Dummy Receipts'',ac.CustomerID,ac.CustomerName,CSH.FinancialID, CSH.Cancelled
FROM    CustomerSettlementHeader CSH
INNER JOIN   losDummyReceiptHeader LDRH ON CSH.losReceiptID = LDRH.drId AND CSH.shopid = LDRH.drShopid
INNER JOIN   aCustomerMaster ac ON CSH.CustomerID=ac.CustomerID
INNER JOIN   aDepartmentMaster AD ON CSH.DepartmentID=AD.DepartmentID
UNION ALL
-- For Shop Debit Credit Note
SELECT  CSH.CSID,CSH.CompanyID,CSH.CSNO,CSH.CSDate,CSH.DepartmentID,AD.DepartmentName,CSH.ShopID,
LDCN.losDCNNo,''Shop DCN'',ac.CustomerID,ac.CustomerName,CSH.FinancialID, CSH.Cancelled
FROM    CustomerSettlementHeader CSH
INNER JOIN   losDebitCreditNote LDCN ON CSH.shopid = LDCN.losDCNShopid AND CSH.losdcnid = LDCN.losDCNId
INNER JOIN   aCustomerMaster ac ON CSH.CustomerID=ac.CustomerID
INNER JOIN   aDepartmentMaster AD ON CSH.DepartmentID=AD.DepartmentID
UNION ALL
--For Shop Goods Return Note
SELECT  CSH.CSID,CSH.CompanyID,CSH.CSNO,CSH.CSDate,CSH.DepartmentID,AD.DepartmentName,CSH.ShopID,
LGRNH.GrnhGoodsreturnnoteNO,''Shop Goods Return'',ac.CustomerID,ac.CustomerName,CSH.FinancialID, CSH.Cancelled
FROM    CustomerSettlementHeader CSH
INNER JOIN   LosGoodsReturnNoteHeader LGRNH ON CSH.shopid = LGRNH.grnhShopid
AND CSH.losGoodsreturnnoteID = LGRNH.GrnhGoodsreturnnoteID
INNER JOIN   aCustomerMaster ac ON CSH.CustomerID=ac.CustomerID
INNER JOIN   aDepartmentMaster AD ON CSH.DepartmentID=AD.DepartmentID'
GO
/****** Object:  View [dbo].[vwdummyreceipts]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdummyreceipts]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
--Last Modified on  : 11/12/02
--Modified by  : leo
--Comments  : v3
--Modified by           : Santhosh M, Shinu
--Added drcancelled 0n 01/10/2003
--Modified by           : venkitesh
--Added special invoice finished chking
--Added drcancelled 0n 28/04/2004
--Modified by           : venkitesh
--Added remarks,symbol columsn
-- corrected currency symbol for received
-- Added Opening Invoice Condition
CREATE  view   [dbo].[vwdummyreceipts]
as
select drId,drNo,drShopid,DrDate, drcustomerid, customername, drrecadduser, drrecmodifyuser,
ih.ihinvoiceno creditinvamount, sih.ihinvoiceno splinvamount, ah.aiinvoiceno,drbankname,
drchequeno , drchequedate, drAmount, drdinvoiceamount, drdsettledamount,drcancelled ,
drremarks,acutrans.Symbol TranSymbol,acuRec.symbol RecSymbol,drrecamount
from losdummyreceiptheader left outer join acurrencymaster acuRec on
acuRec.currencyid =drreccurrencyid left outer join losdummyreceiptdetail on drId = drdid and
drshopid = drdshopid left outer join losinvoiceheader ih on drdinvoiceid= ih.ihinvoiceid and
drdshopid= ih.ihshopid left outer join losspecialinvoiceheader sih on
drdsplinvoiceid =sih.ihinvoiceid and drdshopid = sih.ihshopid
left outer join losaccountsinvoiceheader ah on drdserviceinvoiceid=ah.aiinvoiceid and
drdshopid= ah.aishopid left outer join vwshopservicesales vws on
drdserviceinvoiceid = vws.siinvoiceid and drdshopid= vws.sishopid, acustomermaster c
left outer join acurrencymaster acuTrans on c.currencyid =acuTrans.currencyid where
drcustomerid=c.customerid  and   isnull(drdaccInvoiceID,0)=0
Union All
select drId,drNo,drShopid,DrDate, drcustomerid, customername, drrecadduser, drrecmodifyuser,
ih.ReferenceNo , null, null,drbankname,
drchequeno , drchequedate, drAmount, drdinvoiceamount, drdsettledamount,drcancelled ,
drremarks,acutrans.Symbol TranSymbol,acuRec.symbol RecSymbol,drrecamount
from losdummyreceiptheader left outer join acurrencymaster acuRec on
acuRec.currencyid =drreccurrencyid left outer join losdummyreceiptdetail on drId = drdid and
drshopid = drdshopid left outer join Accountsinvoiceheader ih on drdaccinvoiceid= ih.invoiceid
, acustomermaster c
left outer join acurrencymaster acuTrans on c.currencyid =acuTrans.currencyid where
drcustomerid=c.customerid and  isnull(drdaccInvoiceID,0)<>0'
GO
/****** Object:  View [dbo].[vwdespatchestogodown]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdespatchestogodown]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwdespatchestogodown    Script Date: 18/01/2003 9:45:38 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwdespatchestogodown]
as
select dhdespatchnoteid Despid, dhdespatchnoteno Despno, dnmdespatchnotedate despdate,
dhgodownid godownid, dditemid itemid , pd.packingbarcode, ddqty quantity,
''HQ'' as type, 0 as fromgodownid, 0 fromshopid,
p.packingtypecode as pack, dd.ddqty * pk.quantity as actualqty from
ahqdespatchnoteheader dh, ahqdespatchnotedetails dd, ahqdespatchnotemain dm,
apackingtypecapacitydetail pk, aitem ai, apackingtype p, aunit u, aitempackingdetail pd where
pd.itemid = dd.dditemid and pd.packingtypeid= dd.ddpackingtypeid and
dm.dnmdespatchnoteid = dh.dhdespatchnotemainid and dh.dhgodownid = dd.ddgodownid
and dh.dhdespatchnoteid = dd.dddespatchnoteid and pk.packingtypeid = dd.ddpackingtypeid
and pk.unitsid=ai.unitsid and dd.dditemid= ai.itemid and p.packingtypeid= dd.ddpackingtypeid
and ai.unitsid= u.unitid
union all
select gthdespatchid, gthdespatchno, gthdespatchdate, gthtogodownid , gtditemid,
pd.packingbarcode, sum(gtditemgoodqty), ''G'' as type,
gthFromgodownid , 0 fromshopid, Packingtypecode  as pack,
SUM(gtditemgoodqty) from  meigodowntransferheader h,
meigodowntransferdetail d, aitem ai, apackingtype p, aunit u, aitempackingdetail pd where
h.gthfromgodownid = d.gtdgodownid and h.gthDespatchid = d.gtddespatchid  and
p.packingtypeid = 1 and d.gtditemid= ai.itemid and ai.unitsid= u.unitid
and pd.packingtypeid=1 and pd.itemid= d.gtditemid GROUP BY
gthdespatchid, gthdespatchno, gthdespatchdate, gthtogodownid , gtditemid,
pd.packingbarcode,gthFromgodownid, Packingtypecode, unitcode
union all
select dghid, dghno, dghdate, dghGodownid, dgditemid, pd.packingbarcode,
sum(dgdAvailableGoodQty), ''S'' as type,
0 fromgodownid, h.dghshopid,
Packingtypecode as pack, sum(dgdAvailableGoodQty) from
mesdespatchtogodownheader h, mesdespatchtogodowndetail d, aitem ai,
apackingtype p, aunit u, aitempackingdetail pd  where
h.dghshopid = d.dgdshopid and h.dghid = d.dgdid  and
p.packingtypeid = 1 and d.dgditemid= ai.itemid and ai.unitsid= u.unitid
and pd.packingtypeid=1 and pd.itemid= d.dgditemid group by
dghid, dghno, dghdate, dghGodownid, dgditemid, pd.packingbarcode,
h.dghshopid, Packingtypecode, unitcode'
GO
/****** Object:  StoredProcedure [dbo].[spLedgersPreview]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLedgersPreview]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Last modified on     : 22/11/2003, 25/01/2004, 08/04/2004, 09/12/2004 , 07/27/2010
-- Modified by          : Kishore, Hariharan, Hariharan , Hariharan, Hariharan
-- Comments             : Replaced strTrandId with intTransId in appropriate placed
--                      : altered the debit note posting (09/01/2003)
--     Added the adjustment (21/04/2003)
--       : FOR COSTING packingtypeqty converstion is removed from fobvalue calculation
--       : (@numshipmentoc) Shipment other charges is calculated excluding the
--                  custom duty difference
--   : Added the multicustomer option on receipts 28/07/2003
--           : altered for giving asset related transactions
--                      : Changed the Receipt Preview (23/09/2003)
--                      : Replaced strTrandId with intTransId in appropriate placed (22/11/2003)
--  : debitacc1 and debitacc2 is posted with respect to the transaction.
--  : if transaction is debit these two opted as debit.
--  : if it is credit these two opted as Credit
--  : receipt posting query corrected, spconvertequiamount is passed with last paremeter to suppress selection
--  : bill other charges summing up with header value is avoided
--  : ADJUSTment entry posting corrected
--  : given abs condition for taking the exchange gain or loss value
--  : MOdiifed depreciation query taking fixedasset accid and dep exp accid from
--  : depreciation detail table itself
--  : disposal posting modified, asset transfer dep transfer from dep exrate correctly given
---------------------------------------------------------------------------------------
-- :Modified By :Nidheesh P V
-- :Modified on :29/06/2010
-- Comments : To change the ledger preview for HP receipts(At first the transaction was saved
-- in account amount. After doing partila settlement in hp receipts the transaction amount
-- is saved as the Cust. Equi.Amount. So make proper changes in the posting also.
---------------------------------------------------------------------------------------
-- Last Modified on : 07/08/2010
-- Last Modifued by : Nidheesh P V
-- Comment   : Added the case for shop inhouse consumption
-- If Itemwise counting(for shop inhouse) is enabled this transaction should be post seperately
---------------------------------------------------------------------------------------------
-- Last Modified on : 07/27/2010
-- Last Modifued by : jyothish S R
---Inter division journal
-----------------------------------------------------------------------------------------------
--RefNo-01
-- Last Modifued by : VinothMurugan V
-- Last Modified on : 05/09/2010
---Purpose   :Inter division Bills
-- client   : Kooddoo
-----------------------------------------------------------------------------------------------
--RefNo-02
-- Last Modifued by : VinothMurugan V
-- Last Modified on : 28/02/2010
---Purpose   :Adding Post Dated Cheque
-- client   : Sonee
-----------------------------------------------------------------------------------------------
-- Last Modifued by : Aadyakumar.D.V
-- Last Modified on : 11/07/2011
---Purpose   :Modified forex Trasaction
-- client   : Ask
------------------------------------------------------------------------------------------------
-- Modified on   : 26/07/2011
-- Modified by   : Nidheesh P V
-- Comments  : Posting preview of FOREX is corrected
-- Reference : RefNo:1
--------------------------------------------------------------------
----Modified  on : 23-11-2011   11/10/2011
-- Modified by   : Jyothish.SR
-- Comments  : GST added in service invoice  ,petty cash payment priview corrected
-- Reference : Ref-10
--------------------------------------------------------------------
-- Last Modified by   : vikas.k
----LAst Modified  on : 16-02-2012
-- Comments  :add a condition for display the Cheque no along with remarks in contra
-- Reference : Ref-11
--------------------------------------------------------------------
CREATE  PrOC [dbo].[spLedgersPreview]
@intCompanyID as int,
@strTransid as varchar(250),
@strTransType as varchar(10) ,
@strshopid as varchar(250), --for inhouse cons
@intChequeDtlID as varchar(250)=NULL
as
begin
-- exec spLedgersPreview 1,4,''INDJL'',''''
--For Testing Purpose Commented by R Harikrishnan
--set @intCompanyID=1
--set @strTransid=''2''--''1895''
--set @strTransType=''PAY''
set nocount on
--------------------------------------------RefNo-02
if @intChequeDtlID <>''''
begin
DECLARE  @intTransPDCHECKId  as varchar(250)
set @intTransPDCHECKId = @strTransid
end
------------------------------------------
create table #JournalHeaderPreview
(
JournalID int,companyid int,JournalDate smalldatetime,Remarks  varchar(300),ReferenceNo varchar(50),
FinancialID int,Type  varchar(10),CurrencyId int,Cancel bit,Realised bit,chequedate smalldatetime,
updatetime smalldatetime,bankdate smalldatetime
)
create table #JournalDetailsPreview
(
JournalDetailID int,CompanyID int,JournalID int,JournalCredit bit,AccountID int,CustomerID int,
VendorID int,Amount  numeric(18, 2),ActualAmount numeric(18, 2),departmentId int,depAmount numeric(18, 2)
)
Declare @intRefJournalId  as int,-- declare Bills
@intBillsID as int,@intJournalID as int,@intJournalDetailID as int,@intFinancialID as int,
@strBillsNo as varchar(50),@dtBillsDate as datetime,@intDiscountAccID  as int,@intVendorID   as int,
@strRemarks as varchar(250),@intDepartmentID as int,@numDiscount as numeric(18,2),
@numBillAmt as numeric(18,2),@intDebitAccID as int,@numDebitAmt as numeric(18,2),@intCashBankID   as int,
@intTransCurID as int,@numAverageRate  as numeric(18,8),@numTransRate as numeric(18,8),
@numvexchangerate as numeric(18,8),@numvendoramt as numeric(18,2),@numvendorActualamt as numeric(18,2),
--Declare--ProductInvoice
@intinvoiceid as int,@intSalesAccountID as int,@intCashAccountID as int,@intAccountID as int,
@dtInvoicedate as datetime,@intCustomerID as int,@strInvoiceNo as varchar(50),@intDiscountAccountID  as int,
@strSName as varchar(100),@bitCash as bit,@bitProduct as bit,@numTotalInvValue as numeric(18,2),
@intCompanyCurID as int,@numBuyingRate as numeric(18,8),
--Declare -- Service Invoice
@intSAccountID as int,@intSQty as int,@numSAmount   as numeric(18,2),
--Declare -- Contra @intFinancialID as int,
@intContraID as int,@dtContraDate as datetime,@intFROMBankID as int,@intToBankID as int,@intChargeID as int,
@strContraNo as varchar(50),@strContraType as varchar(10),@numAmount as numeric(18,2),
@numChargeAmount as numeric(18,2),@numIMCurAmt as numeric(18,2),@ExchangeRate as numeric(18,8),
@numtoer as numeric(18,2),@numPerExRate as numeric(18,8),@numbankamt as numeric(18,2),
@intHeaderCreditAccID as int,@intMCCustID as int,@numHeaderCreditAmount  as numeric(18,2),
@intMCAmt as numeric(18,2),@intMCCustAmt as numeric(18,2),
--Declare--Debit Credit
@intdcnid as int,@dtdcnDate as datetime,@strdcnNo as varchar(50),@strdetails as varchar(1000),
@bitDebit as bit,@numdcnAmount as numeric(18,2),@bitoppdebit as bit,@numotherAmount as numeric(18,2),
@numdramt1 as numeric(18,2),@numdramt2 as numeric(18,2),@intdracc1 as int,@intdracc2  as int,
--Declare -- Journal
@intJTID as int,@intRowCount   as int,@dtJTDate   as datetime,@strJTNo   as varchar(50),@intJTDID   as int,
@bitJTC   as bit,@intJTDAccountID  as int,@numJTDAmount   as numeric(18,2),
--Declare --Payments
@intpaymentid   as int,@strPaymentNo   as varchar(50),@dtPaymentDate   as datetime,@intBankCashID   as int,
@strType   as char(2),@intExchangeAccID  as int,@intBankcashcurid  as int,@numPaymentAmt   as numeric(18,2),
@strPaymentType  varchar(5),@numvendorequiamt  as numeric(18,2),@intGoodsInTransitAccID as int,
@intdebit   as int,@numdebit   as numeric(18,4),@inthqpoid   as int,@LCtobeAccounted  as bit,
@intPaidByVendorid  as int,@intMVVendID   as int,@numMVAmt   as numeric(18,2),@numMVVendAmt   as numeric(18,2),
--Declare --Receipt
@intreceiptid   as int,@strReceiptNo   as varchar(50),@dtReceiptDate   as datetime,@numReceiptAmt   as numeric(18,2),
@intCreditAccID  as int,@numCreditAmt   as numeric(18,4),@numcustomerequiamt  as numeric(18,2),
@numcombankamt   as numeric(18,2),@numcomdebitamt  as numeric(18,2),@numcomperamt   as numeric(18,2),
@transtype   as int,@intReceiptCustomerID  as int,@numMCCustAmt   as numeric(18,2),@numMCCustID   as int,
--Ref-1
@intDiscountID as numeric(18,4),@numDisAmount as numeric(28,8),
--Declare extracting
@intPosition   as int,@intTransID   as int,
--purchase bill
@strBillNo   as varchar(25),@dtBillDate   as datetime,@bitCashPurchase  as bit,@intPurchaseAccid  as int,
@numItemAmt   as numeric(18,2),@intBillID   as int ,@numlcmarginamt  as numeric(18,2),@bitlcopened   as bit,
@bitlcmarginpaid as bit,@intpoid as int,@intlcmarginaccid as int,@intGitAccID as int,@numlcamt as numeric(18,2),
@intlcaccountid  as int,@numLCAmount   as numeric(18,2),
-- declare adjustment
@strAdjustmentNo as varchar(100),@intAdjId as int,@intAdjustmentDetailId as int,@dtAdjustmentDate as datetime,
@bitjc    as bit,@strextype   as varchar(5),@numexamount   as numeric(18,2),@intexAccountID  as int,
@numdAmount   as numeric(18,2),@numcAmount   as Numeric(18, 2),
-- declare costing
@intCostID   as int,@strcostNo   as varchar(25),@dtCostingDate   as datetime,@strCostingRemarks  as varchar(250),
@numCostingAmt   as numeric(18,2),@strCostingno   as varchar(50),@intINVAccountID  as int,
@intGITAccountid  as int,@numlcmarginamtusd  as numeric(18,2),@numfobvalue   as numeric(18,2),
@numshipmentoc   as numeric(18,2),@numdiffingain   as numeric(18,2),@intdiffaccid   as int,
-- variables for PB
@numconsRate   as numeric(18,9),@strexrates   as varchar(250),@dtutime   as datetime,@intcurrencyid   as int,
@numdepRate   as numeric(18,9), @bitposted   as bit,
-- costing variables
@intlcmarginacccurid  as int,@strbillexrates  as varchar(250),
-- bill variables
@numAccAmt   as numeric(18,2),
-- SI variables
@numseraccamt   as numeric(18,2),@dtchequedate   as datetime,
-- payment variables
@numdepcuramt   as numeric(18,2),@intMVVendorID   as int,
--PO VARIABAlES
@strPOno   as varchar(50), @dtPODate   as datetime,@numPOAmt   as numeric(18,2),@numvendorer   as numeric(18,2),
--Forex variables
@dtforexDate   as datetime,@intsalesorpurcaccID  as int,@intotheraccID   as int,@intgainorlossaccID  as int,
@strforexNo   as varchar(50),@numsalesorpurcamt  as numeric(18,2),@numgainorlossAmount  as numeric(18,2),
----RefNo:1-----
@numExchComAmount as numeric(18,2),@numExchAmount as numeric(18,2),@numExchActualAmount as numeric(18,2) ,
@numExchDepAmount as numeric(18,2) ,
-----RefNo:1-----
--Payroll Variables
@dtTransDate   as datetime,@strTransNo   as varchar(50), @numDrAmount   as numeric(18,2),
@numCrAmount   as numeric(18,2),@numCompAmount   as numeric(18,2),
--DECLARE HQ WRITEOFF
@intswoiD as int,@strswoNo as varchar(100),@dtswoDate as datetime,@numswoAmt as numeric(18,2),
@intExcessShortageDiffaccId as int,@intswoaccid as int,@intgodownid as int,@intshopid as int,
@intFailcount as int,@strzerorate as varchar(1),@numStockAddclear as numeric(18,3),@numStockDedclear as numeric(18,3),
@stockTransferAcc int,@IntTransferType as char(1),@numSrAmt as numeric(18,8),@numAaccAmt as numeric(18,8),
@intInventoryAccId as int,@numTransEr numeric(18,8),@numDepExRate numeric(18,8),@numAccExRate numeric(18,8),
@numConExRate numeric(18,8),
--FIXED ASSET
@intbillrefid as int,@intfixedassetit as int,@FixedAssetID as int,@intfixedassetaccid as int,
@intwriteoffrefid as int,@intconversiondiffaccid as int,@strrefNo as varchar(50),@dtfixedassetDate as datetime,
@numrefamount as numeric(18,2),@numAssetValue as numeric(18,2),@numDiffValue as numeric(18,2),
@intAssetConversionAccid as int,@intDepID as int,@intAstTransFromACCID as int,@intAstTransToACCID as int,
@strasttrransno as varchar(50),@intasttranstodepid as int,@inttransferaccountid as int,
@dtasttransdate as datetime,@intasttransfromdepid as int,@numasttransvalue as int ,@intasttransassetid as int,
@strasttransremarks as varchar(250),@numfromdepRate as numeric(18,8),@numtodepRate as numeric(18,8),
@numDepreciatedAmount as numeric(18,2),@intdepreciationid as int,@strDepreciationNo as varchar(50),
@dtDepreciationDate as datetime,@intDetailID as int,@intDepreciationAccountID as int,@numdepriamt as numeric(18,2),
@DepreciationAccID as int,@intdepriciationexpaccid as int,@DepreciationAmount as numeric(18,2),
@dtdisphdate as datetime,@strdisphremarks as varchar(250),@strdisphauthorisedby as varchar(250),
@intassetid as int,@intassetaccountid as int,@intassetcreditaccountid as int,@strdisphno as varchar(50),
@intdisposalid as int,@intFromACCDeprAccId as int,@intToACCDeprAccId as int,@numAccDepValue AS Numeric(18,2),
@numDispSalesValue numeric(18,2),@numUPTODepValue  as numeric(18,2),@numDisDepeBalamt as numeric(18,2),
@intDiposalAccId AS INT,@intAccumDepaccid as int,@intDepExpAccId as int,@intDepExpControlAccId as int,
---For hire Purchase Payment
@intBankID as int,@intCustomerAccID as int,@numBankrate as numeric(18,9),@numCusrate as numeric(18,9),
@numComrate as numeric(18,9),
---For Petty Cash Payment
---@intJournalID as int,intJournalDetailID as int,intRowCount as int,@intFinancialID as int,
@dtPDate as datetime,@strPNo as varchar(50),
----@strRemarks as varchar(250),
----@intDepartmentID as int,
----@numAmount as numeric(18,2),
@intPDID as int,@intPAccountID as int,@numPAmount as numeric(18,2),@intPDAccountID as int,
@numPDAmount as numeric(18,2),
----@dtutime as datetime,
@intacccurrencyid as int,
----@intcurrencyid as int,
----@numAccExRate as numeric(18,9),
----@numDepExRate as numeric(18,9),
@numComExRate as numeric(18,9),@numPDAccExRate as numeric(18,9),
----@strexrates as varchar(250),
@numresamount as numeric(18,2),@intCreditAcc as numeric(18,2),@numCreditAmount as numeric(18,2),
@numCreditExRate as numeric(18,2),
---shop inhouse cons---
@intExpenseAcid as int,
--@numTemp Numeric (18, 2),
@ItemwiseAccounting as int ,@WriteoffQty as numeric(18,2),@costprice as numeric(18,2),@InhouseAccnt as numeric(18,2),
@ItemAmount as numeric(18,2),@numToDepExRate as numeric(18,2),@intPositionShop as int,@intToDepId as int ,
--post date cheque
@intPDChequeCreditAccid as int,@intPDChequeDebitAccid AS INT,
--@intChequeDtlID AS INT,
--InterDivision Bills
@IntDetailDeptId as int, --RefNo-01
--for hire purchase reprocess after settlement---
@intProcessingID as int,@strProcessingNo as varchar(50),@intAdjustmentAccID as int,@intInterestAccId as int,
@dtDate as datetime,@CustomerId as int,@CustomerAmount as numeric(18,2),@Adjustmentamnt as numeric(18,2),
@UnearnedIncome as numeric(18,2)
set @numAccExRate = 0.0
set @numTransEr = 0.0
set @numAaccAmt = 0.0
--set @numTemp = 0.0
---shop inhouse cons---
declare
@intServiceTaxID INT, ---Ref No10
@intGSTOutPutAccountID INT, ---Ref No10
	@numGSTTaxAmount as numeric(18,9), ---Ref No10
	@numAccGSTTaxAmount as numeric(18,9) ---Ref No10
	while (@strTransID <> ''''  or  @strshopid <> '''' )
	begin
	  select @intPosition = patindex(''%,%'', @strTransID)
	  if (@intPosition>0 )
		begin
		  select @intTransID = CAST(substring(@strTransID,1,@intPosition-1) as integer)
		  select @strTransID = substring(@strTransID,@intPosition+1,len(@strTransID)-(@intPosition))
		end
	  else if (@intPosition)= 0
		begin
		  select @intTransID = CAST(@strTransID as integer)
		  set @strTransID = ''''
		end
--shop--(for shop inhouse consumption)
select @intPositionShop = patindex(''%,%'', @strshopid)
	  if (@intPositionShop>0 )
		begin
		  select @intshopID = CAST(substring(@strshopid,1,@intPositionShop-1) as integer)
		  select @strshopid = substring(@strshopid,@intPositionShop+1,len(@strshopid)-(@intPositionShop))
		end		
	  else if (@intPositionShop)= 0
		begin
		  select @intshopID = CAST(@strshopid as integer)
		  set @strshopid = ''''
		end
	  --shop--(for shop inhouse consumption)
--************section begins for Purchase Order***********************************************
	if @strTransType = ''PO''
begin
	  /* getting the maximum Journal ID FROM journal table */
	  SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
select @intGITAccid = POGITAccountid from apackagesettings where companyid = @intcompanyid
SELECT @intPOID=pohPoid, @strPOno=pohpono, @dtPODate=pohPodate, @intVendorID=pohVendorID, @numPOAmt=pohvalue,
		@strRemarks=pohremarks, @intFinancialID= pohfinancialid,@intDepartmentid=pohDepartmentid,
		@numdepRate = pohdepexrate, @numconsrate = pohcmpexrate, @dtutime=updatetime, @strexrates = pohexchangerates
from loPurchaseOrderHeader where pohcompanyid = @intCompanyID and pohPoid= @intTransID
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
select @intcurrencyid = currencyid from avendormaster where companyid = @intcompanyid and vendorid = @intvendorid
if @numPOAmt <> 0
		begin
		  insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,remarks, financialID,Type,
			CurrencyID,cancel,realised, chequedate,updatetime)
		  values (@intJournalID, @intCompanyID, @dtPODate, @strPOno,
			@strRemarks, @intFinancialID,''PO'',@intcurrencyid,0,0, @dtPODate, @dtutime)
/* crediting  the Vendor account with PO amt */
		  insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
			JournalCredit, vendorID, Amount, actualAmount, Departmentid, depamount)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intVendorID, @numPOAmt * @numconsrate, @numPOAmt,@intDepartmentid,@numpoamt * @numdeprate)
		  set @intJournalDetailID = @intJournalDetailID + 1
declare @numaccer as numeric(18,2),@numaccpoamt as numeric(18,2)
exec spReturnExrate @intcurrencyid, @strexrates, @numvendorer output
--to arrive on account currency equivalent, vendorid
		  select @intcurrencyid = currencyid from aaccountmaster where companyid = @intcompanyid and
			accountid = @intGITAccid
exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
exec spconvertcurrency @numvendorer, @numaccer, @numpoamt,@numaccpoamt output
		  --debit the goods in transit account
		  insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
			JournalCredit, accountID, Amount, actualAmount, Departmentid, depamount)
		  values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
			@intgitaccID, @numPOAmt* @numconsrate,@numaccpoamt , @intDepartmentid,@numpoamt * @numdeprate)
		end
end
--************section Ends for Purchase Order***********************************************
--**==============================Hire Purchase Reprocessing====START======================**-----
	--  if @strTransType=''HPRAS''
	--  Begin
	--    select @intcurrencyid = CurrencyId from acompanymaster where companyid = @intcompanyid
	--   /* getting the maximum Journal ID FROM journal table */
	--   SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
	--   Select @intCustomerAccID =DebtorAcc ,@intAdjustmentAccID=AdjustmentAcc ,@intInterestAccId=SuspenseAcc
	--   from ahpaccountssettings where companyid = @intcompanyid
	--     set @intJournalID = @intJournalID + 1
	--         --set @intProcessingID=@strTransid
	--     select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo,
	--        @dtDate=hphProcessingDate, @Adjustmentamnt=hphAdjustmentAmount, @UnearnedIncome=hphBalanceInterest,
	--        @strremarks=hphRemarks,@intFinancialID=hphFinancialID, @CustomerId=hphCustomerID,@dtutime=hphUpdateTime
	--    FROM ahpprocessingdetail left outer join ahpprocessingheader
	--    on hpdprocessingID=hphProcessingID and hpdCompanyID=hphCompanyID
	--    WHERE hphreprocessaftersettlement=1 and hphReferenceID is not null  and hpdProcessingID= @intTransID and hphCompanyID =@intCompanyID
	----(JournalID, CompanyID, JournalDate,
	--   --referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
	--    insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
	--    referenceno, remarks,financialID,Type, CurrencyID,updatetime) values
	--    (@intJournalID, @intCompanyID, @dtDate, @strProcessingNo,@strRemarks, @intFinancialID,''HPRAS'', @intcurrencyid,@dtutime)
	--      --''HPRPAS''---HP Reprocessing After Settlement
	-- set @intJournalDetailID = 1
	-- if @intAdjustmentAccID<>0  and  @intInterestAccId<>0
	-- begin
	-- /* Debiting Adjustment Carrying Amount in Adj. account*/
	--   --(@Adjustmentamnt-@UnearnedIncome)===Adjustment Carrying Amount
	--if (@Adjustmentamnt-@UnearnedIncome)>=0
	--begin
	--  insert into #JournalDetailsPreview (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
	--  Amount, actualAmount, departmentID, depamount)values (@intJournalId, @intJournalDetailId, @intCompanyID,0,
	--  @intAdjustmentAccID,(@Adjustmentamnt-@UnearnedIncome) , (@Adjustmentamnt-@UnearnedIncome),@intDepartmentID, (@Adjustmentamnt-@UnearnedIncome))
	--end
	--else
	--begin
	--  insert into #JournalDetailsPreview (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
	--  Amount, actualAmount, departmentID, depamount)values
	--  (@intJournalId, @intJournalDetailId, @intCompanyID,1,@intAdjustmentAccID,
	--  (@UnearnedIncome-@Adjustmentamnt) , (@UnearnedIncome-@Adjustmentamnt),@intDepartmentID, (@UnearnedIncome-@Adjustmentamnt))
	--end
	 -- set @intJournalDetailId = @intJournalDetailId +1
	-- /* Debiting  in Unearned income account */
	-- insert into #JournalDetailsPreview (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
	-- Amount, actualAmount, departmentID, depamount) values
	-- (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intInterestAccId,
	-- @UnearnedIncome,@UnearnedIncome,@intDepartmentID, @UnearnedIncome)
	-- set @intJournalDetailId = @intJournalDetailId +1
	-- set @CustomerAmount= @Adjustmentamnt
	-- /* Crediting against customer account */
	-- insert into #JournalDetailsPreview  (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerID,
	-- Amount, actualAmount, departmentID, depamount)values
	-- (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@CustomerId ,
	-- @CustomerAmount,@CustomerAmount,@intDepartmentID,@CustomerAmount)
	-- end
	-- end
	--**==============================Hire Purchase Reprocessing====END======================**-----
	--************section begins for Purchase Bill***********************************************
if (@strTransType = ''PB'')
begin
		select @LCtobeAccounted = isnull(Lctoaccount,0) from miscsettings
		/* getting the maximum Journal ID FROM journal table */
		SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
		SELECT @intBillID= pbhBillID, @strBillno= pbhBillNo, @dtBillDate = pbhBillDate,@intVendorID=pbhVendorID,
		  @numBillAmt = pbhbillamount, @strRemarks = pbhRemarks,@intFinancialID = pbhFinancialID,
		  @intDepartmentid = pbhDepartmentID, @intGITAccid =pbhPurchaseAccID, @numconsRate = pbhexchangerate,
		  @intpoid= pbhpoid, @dtutime = updatetime, @numdepRate = pbhdepexrate, @strexrates = pbhexchangerates,
		  @numLCAmount = isnull(pbhLcAmount,0)
		from losppurchasebillheader where pbhPosted =0 and pbhCompanyID =@intCompanyID and pbhCancelled =0 and
		  pbhbillid = @intTransid
		-- hari added to post whole amount credit to supplier if the lc is not to be accounted
		Select @numBillAmt  = @numBillAmt  from lospPurchaseBillOC where pboBillID = @intTransid
		if @LCtobeAccounted = 0
		  set @numBillAmt = @numBillAmt + @numLCAmount
		  set @intJournalDetailID = 1
		  set @intJournalID = @intJournalID + 1
select @intcurrencyid = currencyid from avendormaster where companyid = @intcompanyid and
vendorid = @intvendorid
		  if @numbillamt <> 0
			begin
			  insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,remarks, financialID,Type,
			    CurrencyID,cancel,realised, chequedate,updatetime)
			  values (@intJournalID, @intCompanyID, @dtBillDate, @strBillNo,@strRemarks, @intFinancialID,''PACB'',@intCurrencyID,
				0,0, @dtbilldate, @dtutime)
			  -- if the po  used in this bill is posted already then it has to be reversed
			  select @bitposted = pohposted from lopurchaseorderheader where pohcompanyid = @intcompanyid and
			    pohpoid = @intpoid
			  if (@bitposted =1)
				begin
				  select @intjournalid = journalid from  #JournalHeaderPreview where cancel =0
					and referenceno = ( select pohpono from lopurchaseorderheader where pohpoid = @intpoid)
				  insert into #JournalDetailsPreview
					select JournalDetailID, @intjournalid, abs(JournalCredit-1), AccountID,CustomerID, VendorID,
					Amount, ActualAmount,CompanyID, DepartmentID,depamount from #JournalDetailsPreview where
					vendorid is not null and  journalid = @intjournalid
				  set @intJournalDetailID = @intJournalDetailID + 1
				  insert into #JournalDetailsPreview
			      select JournalDetailID, @intjournalid, abs(JournalCredit-1), AccountID,CustomerID, VendorID, Amount,ActualAmount,
					CompanyID, DepartmentID,depamount from #JournalDetailsPreview where accountid is not null and
					journalid = @intjournalid
set @intJournalDetailID = @intJournalDetailID + 1
				end
				-- end of po posting reversal
				/* crediting  the Vendor account with bill amt - lc amount*/
			  insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, vendorID, Amount, actualAmount, Departmentid, depamount)
			  values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intVendorID, @numbillAmt * @numconsrate ,
				@numbillamt,@intDepartmentid,@numbillamt * @numdeprate)
			  set @intJournalDetailID = @intJournalDetailID + 1
			  exec spReturnExrate @intcurrencyid, @strexrates, @numvendorer output
			  --to arrive on account currency equivalent, vendorid
			  select @intcurrencyid = currencyid from aaccountmaster where companyid = @intcompanyid and
			     accountid = @intGITAccid
			  exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
			  exec spconvertcurrency @numvendorer, @numaccer, @numbillamt, @numaccpoamt output
			  --debit the goods in transit account  with bill amt + lc mar amount split posting
			  insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, accountID, Amount, actualAmount, Departmentid, depamount)
			  values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intgitaccID, @numbillAmt* @numconsRate,
				@numaccpoamt ,@intDepartmentid,@numbillamt * @numdeprate)
end -- if billamount
		  end  -- end of PB
		--************section ends for Purchase Bill***********************************************
		If (@strTransType = ''CO'')  --************section begins for Pandc Costing***********************************************
		  begin
			/* getting the maximum Journal id from journal table */
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			select @lctobeaccounted=isnull(Lctoaccount,0) from miscsettings
			SET @intJournalID = @intJournalID + 1
			select @intdiffaccid = shipmentfixedandactualvaluediff from apackagesettings where
				companyid = @intcompanyid
			SELECT @dtCostingDate = chCostingDate, @strCostingRemarks=chRemarks, @intDepartmentID=
			  chDepartmentID, @strcostingno = chcostingno, @intinvaccountid = chinventoryaccid,
			  @intgitaccountid = chgoodsintransitaccid, @dtutime = updatetime, @intbillid = chbillid
			FROM LOaCostingHeader WHERE chPosted = 0 and chCancelled = 0 and chCompanyID = @intCompanyID and
			  chcostingid = @intTransid
			select @intcurrencyid = currencyid from aaccountmaster where companyid = @intcompanyid and
			  accountid = @intinvaccountid
			set @numshipmentoc =0.0
			set @numlcmarginamt =0.0
			set @numCostingAmt = 0.0
			set @numfobvalue  =0.0
			set @numdiffingain =0.0
			select @intFinancialID = financialid from vwfinyearperiod where @dtcostingdate between sdate and edate
			select @intpoid = pbhpoid from losppurchasebillheader where pbhbillid = @intbillid
			select @bitlcopened = pohlcopened, @intlcmarginaccid = pohpurchaseaccountid,
			  @intlcaccountid = pohlcaccountid from lopurchaseorderheader where pohcompanyid = @intcompanyid and
			  pohpoid = @intpoid and pohcancel = 0
			if @bitlcopened =1 and @lctobeaccounted=1
			  begin
				declare @strpymtexrates as varchar(250),@numpymtlcmarginexrate as numeric(18,7),
				  @numpymtinvexrate as numeric(18,7),@numlcmarginamtinvequi as numeric(18,2)
				select @numlcmarginamt = isnull(pddamount,0), @strpymtexrates = phexchangerates
				from ahqpaymentvoucherdebitdetails pd, ahqpaymentvoucherheader ph
				where ph.phpaymentid = pd.pddpaymentid and ph.phcompanyid = pd.pddcompanyid and
				  ph.phcompanyid = @intcompanyid and pd.pddhqpoid = @intpoid and ph.phlcpayment=''LCM'' and
				  ph.phcancelled =0
			    -- the lcmarginamt taken above is considered to be in terms of account
				-- currency, so that amount is converted to inventory account currency terms
				select @intlcmarginacccurid = currencyid from aaccountmaster where companyid = @intcompanyid and
				  accountid = @intlcmarginaccid
				exec spReturnExrate @intlcmarginacccurid, @strpymtexrates,@numpymtlcmarginexrate output
				exec spReturnExrate @intCurrencyId, @strpymtexrates, @numpymtinvexrate output
				exec spconvertcurrency @numpymtlcmarginexrate, @numpymtinvexrate, @numlcmarginamt,@numlcmarginamtinvequi output
			  end
-- to get the total costing amount
			select @numCostingAmt = sum(pt.quantity * bd.pbditemquantity * cd.cdcostingprice),@numfobvalue =
			  sum(pbdItemUnitPrice * bd.pbditemquantity) * pbhinvaccexrate,@strbillexrates = pbhexchangerates
			from loacostingdetail cd, loacostingheader ch, losppurchasebillheader bh,losppurchasebilldetail bd,
			  apackingtypecapacitydetail pt, aitem i where ch.chcostingid = cd.cdcostingid and
			  pt.packingtypeid = bd.pbdPackingTypeID and i.itemid = bd.pbditemid and i.unitsid = pt.unitsid and
			  bh.pbhbillid = bd.pbdbillid and ch.chbillid = bh.pbhbillid and bh.pbhcancelled = 0 and cd.cditemid =
			  bd.pbditemid and cdCostingID = @intTransID group by cd.cdcostingid, pbhexchangerates, pbhinvaccexrate
set @numshipmentoc  = 0.0
			-- TO Take only the custom duty paid which will be saved in the first record
			-- of loacostingdetail table with caddetailid = 1
		    select @numshipmentoc = isnull(sum(isnull(cadamount,0)),0) from LOaCostingAccountDetails cad,
		    aPackageSettings s where cad.cadcostingid = @intTransID and cad.cadaccountid = customsaccid and
		    cad.cadCOmpanyid = s.companyid and cad.cadDetailID = 1 and cad.cadCompanyid = @intCompanyID
			--To take the shipment other charges other than custom duty
			select @numshipmentoc = @numshipmentoc + isnull(sum(isnull(cadamount,0)),0) from LOaCostingAccountDetails cad,
			  aPackageSettings s  where cad.cadcostingid = @intTransID and cad.cadaccountid <> customsaccid
			  and cad.cadCOmpanyid = s.companyid and cad.cadCompanyid = @intCompanyID
set @numdiffingain = isnull(@numcostingamt,0) - isnull(@numfobvalue,0) - isnull(@numshipmentoc,0)
INSERT into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, ReferenceNo, Remarks,FinancialID,
			  Type,CurrencyID, chequedate,updatetime) VALUES (@intJournalID,@intCompanyID, @dtCostingDate,
			  @strcostingno,@strCostingRemarks, @intFinancialID,''COST'', @intcurrencyid, @dtcostingdate, @dtutime)
set @intJournalDetailId = 1
			declare @numconsamount as numeric(18,2),@numdepamount as numeric(18,2),-- @numresamount as numeric(18,4),
			  @intconscurid as int,@intdepcurid as int,@numtemp as numeric(18,4)
select @intconscurid = currencyid from acompanymaster where companyid = @intcompanyid
			select @intdepcurid = depcurrencyid from adepartmentmaster where departmentid = @intdepartmentid
set @numtemp = isnull(@numCostingAmt,0) - isnull(@numlcmarginamtinvequi,0) - isnull(@numdiffingain,0)
			exec spConvertequiamount @intinvaccountid,''a'',@intgitaccountid,''a'',@strbillexrates,@numtemp,@numresamount output,''''
			exec spConvertequiamount @intinvaccountid,''a'',@intconscurid,''m'',@strbillexrates,@numtemp,@numconsamount output,''''
			exec spConvertequiamount @intinvaccountid,''a'', @intdepcurid,''m'',@strbillexrates,@numtemp, @numdepamount output,''''
			/* inserting the account with the cost price */
			INSERT into #JournalDetailsPreview (JournalID,JournalDetailID,CompanyID,JournalCredit,AccountID, Amount,
			  ActualAmount,departmentid,depamount) VALUES (@intJournalID,@intJournalDetailID, @intCompanyID,
			  1, @intgitaccountid, @numconsamount, @numresamount,@intDepartmentID, @numdepamount)
if @numlcmarginamt > 0.0
			begin
			  exec spConvertequiamount @intlcmarginaccid,''a'',@intconscurid,''m'',@strpymtexrates,@numlcmarginamt,@numconsamount output,''''
			  exec spConvertequiamount @intlcmarginaccid, ''a'', @intdepcurid, ''m'',@strpymtexrates, @numlcmarginamt, @numdepamount output,''''
			  set @intJournalDetailId = @intJournalDetailId+ 1
			  /* inserting the account with the cost price */
			  INSERT into #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,
				JournalCredit, AccountID, Amount, ActualAmount,departmentid, depamount)
			  VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1, @intlcmarginaccid ,
				@numconsamount, @numlcmarginamt, @intDepartmentID, @numdepamount)
			end
			if @numdiffingain <> 0.0
			  begin
				set @numtemp = abs(isnull(@numdiffingain,0))
				exec spConvertequiamount @intinvaccountid, ''a'', @intdiffaccid, ''a'',@strbillexrates, @numtemp , @numresamount output,''''
				exec spConvertequiamount @intinvaccountid, ''a'', @intconscurid, ''m'',@strbillexrates, @numtemp , @numconsamount output,''''
				exec spConvertequiamount @intinvaccountid, ''a'', @intdepcurid, ''m'',@strbillexrates, @numtemp , @numdepamount output,''''
				set @intJournalDetailId = @intJournalDetailId+ 1
				if @numdiffingain > 0.0  /* inserting the account with the cost price */
				  INSERT into #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,JournalCredit, AccountID,
				    Amount, ActualAmount,departmentid, depamount) VALUES (@intJournalID, @intJournalDetailID,
				    @intCompanyID,1,@intdiffaccid, @numconsamount, @numresamount,@intDepartmentID,@numdepamount)
				else
				  INSERT into #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,JournalCredit, AccountID,
				    Amount,ActualAmount,departmentid, depamount)VALUES (@intJournalID, @intJournalDetailID,
				    @intCompanyID, 0,@intdiffaccid, @numconsamount, @numresamount, @intDepartmentID,@numdepamount)
			  end
			set @intJournalDetailId = @intJournalDetailId+ 1
			exec spConvertequiamount @intinvaccountid, ''a'', @intconscurid, ''m'',@strbillexrates, @numCostingAmt, @numconsamount output,''''
			exec spConvertequiamount @intinvaccountid, ''a'', @intdepcurid, ''m'',@strbillexrates, @numCostingAmt, @numdepamount output,''''
		
			INSERT into #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID, JournalCredit,AccountID, Amount,
			  ActualAmount,departmentid, depamount) VALUES (@intJournalID,@intJournalDetailID,
			  @intCompanyID, 0, @intinvaccountid, @numconsamount, @numCostingAmt,@intDepartmentID, @numdepamount)
		  end   -- end of CO
		/*******************Section for creating ledger preview for Bills Transaction****************/
		if (@strTransType = ''BL'')
		  begin /* getting the maximum Journal ID FROM journal table */
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			SELECT @intBillsID = BillsID, @strBillsno = Billsno,@dtBillsDate = BillDate,@intVendorID = vendorID,
			  @intDiscountAccID = discountAccountID,@numDiscount = discount,@numBillAmt = billAmount, @strRemarks = case
			  when (chequeno is null or chequeno ='''') then remarks else chequeno + '';'' + remarks end,@intFinancialID =
			  FinancialID,@intCashBankID = bankcashaccID, @dtutime = updatetime,@intdepartmentid = departmentid,
			  @strexrates = exchangerates, @numdepRate = depexrate,@numconsrate = exchangerate
			FROM Bills WHERE posted = 0 and CompanyID = @intCompanyID and cancelled = 0 and billsid = @intTransId
		    set @intJournalDetailID = 1
			set @intJournalID = @intJournalID + 1
			-- get cash or credit
			if (@intCashBankID is null) --credit trans
			  begin
				SELECT @intcurrencyid = CurrencyID FROM aVendorMaster WHERE CompanyID = @intCompanyID and vendorID = @intvendorID
				insert into #JournalHeaderPreview (JournalID, CompanyID,JournalDate,referenceno,remarks, financialID,
				  Type,CurrencyID,chequedate, updatetime)values (@intJournalID, @intCompanyID, @dtBillsDate,
				  @strBillsNo,@strRemarks, @intFinancialID, ''B'',@intcurrencyid, @dtBillsDate, @dtutime)
				set @numvendoramt = 0
				Declare DebitBillCur cursor for
				SELECT AccountID, Amount FROM BillsDebitDetails WHERE CompanyID = @intCompanyID and BillsID=@intBillsID
				open debitbillcur
				  fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
				  while @@Fetch_status = 0
					begin	
					  exec spConvertEquiAmount @intvendorid, ''v'', @intdebitaccid, ''a'', @strexrates,@numdebitamt, @numaccamt output, ''''
					  insert into #JournalDetailsPreview(JournalID, journaldetailID,CompanyID,JournalCredit,AccountID,
					    Amount, actualAmount,departmentid, depamount)values (@intJournalID, @intjournalDetailID,
					    @intCompanyID, 0,@intDebitAccID, @numDebitAmt * @numconsrate, @numaccamt,@intDepartmentID,
					    @numDebitAmt * @numdeprate)
					  set @numvendoramt = isnull(@numvendoramt,0) + isnull(@numDebitAmt ,0)
					  set @intJournalDetailID = @intJournalDetailID + 1
					  fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
					end
				close DebitBillCur
				deallocate debitbillcur
				insert into #JournalDetailsPreview (JournalID,journaldetailID,CompanyID,JournalCredit,vendorID,Amount,
				  actualAmount,departmentid, depamount)
				values (@intJournalID,@intjournalDetailID,@intCompanyID,1,@intVendorID,@numvendoramt * @numconsrate,
				  @numvendoramt, @intDepartmentID,@numvendoramt * @numdeprate)
				set @intJournalDetailID = @intJournalDetailID + 1
			  end --for credit trans
			else
			  begin  -- cash trans
				SELECT @intcurrencyid = CurrencyID FROM aaccountmaster WHERE CompanyID = @intCompanyID and
				  AccountID = @intcashbankID
				insert into #JournalHeaderPreview(JournalID,CompanyID,JournalDate,referenceno,remarks,financialID,Type,
				  CurrencyID,chequedate, updatetime) values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsNo,
				  @strRemarks, @intFinancialID,''B'', @intcurrencyid, @dtBillsDate, @dtutime)
				set @numvendoramt =0.0
				Declare DebitBillCur cursor for
				SELECT AccountID,Amount FROM Billsdebitdetails WHERE CompanyID = @intCompanyID and BillsID = @intBillsID
				open debitbillcur
				  fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
				  while @@Fetch_status = 0
				  begin  /* inserting the Vendor account with the cost price */
					set @numvendoramt = isnull(@numvendoramt,0) + isnull(@numDebitAmt,0)
					exec spConvertequiamount @intcurrencyid,''m'',@intdebitaccid,''a'',@strexrates,@numdebitamt,@numaccamt output, ''''
					insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
					  JournalCredit, AccountID, Amount, actualAmount, departmentid, depamount)
					values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intDebitAccID,
					  @numDebitAmt * @numconsRate,@numaccamt,@intdepartmentid, @numDebitAmt * @numdepRate)
					set @intJournalDetailID = @intJournalDetailID +1
				    fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt
				  end -- end of while
				close DebitBillCur
				deallocate debitbillcur
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
					JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intcashbankID,
				  @numvendoramt * @numconsrate,@numvendoramt, @intDepartmentid,@numvendoramt * @numconsrate)
				set @intJournalDetailID = @intJournalDetailID +1
			  end --for cash trans
			end  -- end of BL
		  /*******************Section ends for creating ledger preview for Bills Transaction****************/
		  if (@strTransType=''SI'')/***********Section for creating ledger preview for Service Invoice Transaction*******************/
			begin /* getting the maximum Journal ID FROM journal table */
			  select @intServiceTaxID=isnull(TaxCategoryforServices,0) from apackagesettings
			  select @intGSTOutPutAccountID=TaxAccountId from aTaxCategoryMaster where TaxId  =@intServiceTaxID
			  SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			  set @intJournalID = @intJournalID + 1
			  --SELECT @intInvoiceID= InvoiceID,@dtInvoiceDate = InvoiceDate,@intCustomerID =CustomerID,@strInvoiceno =
			  --InvoiceNo, @strRemarks = case when (chequeno is null or -- chequeno ='''') then remarks else
			  --chequeno + '';'' + remarks end, @intDiscountAccountID = DiscountAccountID, @numDiscount = Discount,
			  --@intDepartmentID = DepartmentID,@bitProduct = Product, @intFinancialID = FinancialID,
			  --@intCashAccountID = BankCashID,@numconsRate = exchangeRate, @dtutime = updatetime,
			  --@numdeprate = depexrate,@strexrates = exchangerates FROM AccountsInvoiceHeader
			  -- WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and
			  -- Product = 0 and invoiceid = @intTransId
			  --Ref-10
			  SELECT @intInvoiceID= InvoiceID, @dtInvoiceDate = InvoiceDate, @intCustomerID = CustomerID,
				@strInvoiceno = InvoiceNo, @strRemarks = case when (chequeno is null or chequeno ='''') then remarks else
				chequeno + '';'' + remarks end, @intDiscountAccountID = DiscountAccountID, @numDiscount = Discount,
				@intDepartmentID = DepartmentID,@bitProduct = Product, @intFinancialID = FinancialID,
				@intCashAccountID = BankCashID,@numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,
				@strexrates = exchangerates, @numGSTTaxAmount=TaxAmount FROM AccountsInvoiceHeader
			  WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and
				Product = 0 and invoiceid = @intTransId
			  exec spConvertequiamount @intcustomerid, ''c'', @intGSTOutPutAccountID, ''a'',@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output,''''
			  set @numTotalInvValue =0
			  -- get cash or credit
			  if (@intCashAccountID is null) --credit trans
				begin
				  SELECT @intcurrencyid = CurrencyID FROM aCustomerMaster WHERE CompanyID = @intCompanyID and CustomerID = @intCustomerID
				  INSERT INTO #JournalHeaderPreview(JournalID, CompanyID, JournalDate,ReferenceNo,Remarks,FinancialID,
				    Type,CurrencyID, chequedate, updatetime)VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate,
				    @strInvoiceNo,@strRemarks, @intFinancialID, ''AI'', @intcurrencyid, @dtinvoicedate, @dtutime)
					set @intJournalDetailID = 1
				  Declare ServiceInv cursor for
				    SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails WHERE CompanyID = @intCompanyID
					  and InvoiceID = @intInvoiceID ORDER BY InvoiceDetailID
				  open ServiceInv
					FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
					while @@fetch_status = 0
					  begin
						exec spConvertequiamount @intcustomerid, ''c'', @intSAccountID, ''a'',
						  @strexrates, @numSAmount, @numseraccamt output, ''''
						/* inserting the sales account with the full invoice Amount */
						INSERT INTO #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,
						  JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
						VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,@intSAccountID,
						  (@numSAmount * @numconsRate),@numseraccamt, @intDepartmentID,(@numSAmount * @numdepRate) )
						set @numTotalInvValue  = isnull(@numTotalInvValue ,0) + isnull(@numSAmount,0)
						set @intJournalDetailID = @intJournalDetailID +1
						FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
					  end
				  close ServiceInv
				  deallocate ServiceInv
				  /* check if discount allowed if allowed then post discount details */
				  if @numDiscount > 0
				    begin
					  exec spConvertequiamount @intcustomerid, ''c'', @intDiscountAccountID, ''a'',
						@strexrates, @numDiscount, @numseraccamt output, ''''
					  INSERT INTO #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
						JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
					  VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intDiscountAccountID,
						(@numDiscount * @numconsRate),@numseraccamt,@intDepartmentID, (@numDiscount * @numdepRate))
					  set @intJournalDetailID = @intJournalDetailID +1
				    end
				  --INSERT INTO #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,
				  -- JournalCredit, CustomerID, Amount, ActualAmount,departmentID, depamount)
				  -- VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intCustomerID,
				  -- ((@numTotalInvValue-@numDiscount)*@numconsRate), (@numTotalInvValue - @numDiscount),@intDepartmentID,
				  -- ((@numTotalInvValue-@numDiscount)*@numdepRate))
				  INSERT INTO #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,
					JournalCredit, CustomerID, Amount, ActualAmount,departmentID, depamount)
				  VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intCustomerID,
					(((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount)*@numconsRate),
					(@numTotalInvValue - @numDiscount)+@numGSTTaxAmount,@intDepartmentID,
					((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount*@numdepRate))
				  set @intJournalDetailID = @intJournalDetailID +1
				end  -- end for credit trans
			  else
				begin -- cash trans
				  SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
				  WHERE CompanyID = @intCompanyID and AccountID = @intCashAccountID
INSERT INTO #JournalHeaderPreview(JournalID, CompanyID, JournalDate, ReferenceNo,
					Remarks, FinancialID, Type, CurrencyID, chequedate,updatetime)
				  VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate, @strInvoiceNo,
					@strRemarks, @intFinancialID, ''AI'', @intcurrencyid, @dtinvoicedate, @dtutime)
				  set @intJournalDetailID = 1
				  Declare ServiceInv cursor for
					SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails
					WHERE CompanyID = @intCompanyID and InvoiceID = @intInvoiceID ORDER BY InvoiceDetailID
				  open ServiceInv
					FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
					while @@fetch_status = 0
					begin
					  exec spConvertequiamount @intCashAccountID, ''a'', @intSAccountID, ''a'',
						@strexrates, @numSAmount, @numseraccamt output, ''''
					  /* inserting the sales account with the full invoice Amount */
					  INSERT INTO #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,
						JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
					  VALUES (@intJournalID, @intJournalDetailID, @intCompanyID,1,@intSAccountID,
						(@numSAmount * @numconsRate),@numseraccamt, @intDepartmentID, (@numSAmount * @numdepRate))
					  set @numTotalInvValue  = isnull(@numTotalInvValue ,0) + isnull(@numSAmount,0)
					  set @intJournalDetailID = @intJournalDetailID +1
					  FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID
					end
				  close ServiceInv
				  deallocate ServiceInv
				  /* check if discount allowed if allowed then post discount details */
				if @numDiscount > 0
				  begin
					exec spConvertequiamount @intCashAccountID, ''a'', @intDiscountAccountID, ''a'',
					  @strexrates, @numDiscount, @numseraccamt output, ''''
					INSERT INTO #JournalDetailsPreview(JournalID, JournalDetailID, CompanyID,
					  JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)
					VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,@intDiscountAccountID,
					  (@numDiscount * @numconsRate),@numseraccamt, @intDepartmentID, (@numDiscount * @numdepRate))
					set @intJournalDetailID = @intJournalDetailID +1
				  end
				INSERT INTO #JournalDetailsPreview (JournalID,JournalDetailID,CompanyID,JournalCredit, AccountID,
				  Amount,ActualAmount,departmentID, depamount)
				VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,@intCashAccountID,
				  ((@numTotalInvValue - @numDiscount) * @numconsRate),(@numTotalInvValue - @numDiscount),
				  @intDepartmentID,((@numTotalInvValue - @numDiscount) * @numdepRate)  )
			  end -- end for cash
			--Ref-10 start posting of GST amount
			IF (@intServiceTaxID<>0)
			  Begin
				--   exec spConvertequiamount @intcustomerid, ''c'', @intGSTOutPutAccountID, ''a'',
				--@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output
				INSERT INTO #JournalDetailsPreview (JournalID, JournalDetailID, CompanyID,JournalCredit,AccountID,
				  Amount,ActualAmount,departmentID, depamount)
				VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,@intGSTOutPutAccountID,
				  (@numGSTTaxAmount * @numconsRate),@numAccGSTTaxAmount, @intDepartmentID,
				  (@numGSTTaxAmount * @numdepRate) )
				set @intJournalDetailID = @intJournalDetailID +1
			  END
		  end  -- end of SI
		/***********************Section ends for Service Invoice  End ***************************/
		/**************************Section for Purchase Return*****************************/
		if (@strTransType =''PCRET'')
		  begin
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
			select @intPurchaseAccid = PurchaseRtnAccID from apackagesettings where companyid = @intCOmpanyid
			SELECT @strBillno= prhreturnno, @dtBillDate = prhreturndate,@intVendorID = prhvendorid,
			  @numBillAmt = sum(prdsuppamount),@strRemarks = prhremarks, @intFinancialID = prhFinancialID,
			  @intDepartmentid = prhDepartmentID, @numconsRate = prhexrate, @dtutime = prhReturnupdatetime,
			  @numdepRate = prhdepexrate, @strexrates = prhexchangerates
			from loPurchaseReturnheader,loPurchaseReturnDetail
			where  prhReturnID=prdReturnID And prhposted =0 and prhcompanyid = @intCompanyID and prhcancelled =0 and
			  prhreturnid=@intTransID
			group by prdcompanyid, prhreturnid, prhreturnno, prhreturndate, prhvendorid,prhremarks, prhFinancialID,
			  prhDepartmentID, prhexrate, prhReturnupdatetime, prhdepexrate,prhexchangerates
			set @intJournalID = @intJournalID + 1
			set @intJournalDetailID = 1
			insert into #JournalHeaderPreview (JournalID,CompanyID,JournalDate,referenceno,remarks,financialID,Type,
			  CurrencyID,chequedate, updatetime)
			values (@intJournalID, @intCompanyID, @dtPDate, @strPNo,@strRemarks,@intFinancialID, ''PCRET'',
			  @intcurrencyID, @dtPdate, @dtutime)
			select @intcurrencyid = currencyid from avendormaster where companyid = @intcompanyid and
			  vendorid = @intvendorid
			--to get Vendor Ex Rate
			exec spReturnExrate @intcurrencyid, @strexrates, @numvendorer output
			/* Debiting  the Vendor account with return amount*/
			insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, vendorID, Amount, actualAmount, Departmentid, depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intVendorID, @numbillAmt * @numconsrate ,
				@numbillamt,@intDepartmentid,@numbillamt * @numdeprate)
			set @intJournalDetailID = @intJournalDetailID + 1
			--to arrive on account currency equivalent, vendorid
			select @intcurrencyid = currencyid from aaccountmaster where companyid = @intcompanyid and
				accountid = @intPurchaseAccid
			exec spReturnExrate @intcurrencyid, @strexrates, @numaccer output
			exec spconvertcurrency @numvendorer,  @numaccer, @numbillamt, @numaccamt output
			--Crediting purchase return accid
			insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCrEDit, accountID, Amount, actualAmount, Departmentid, depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intPurchaseAccid, @numbillAmt* @numconsRate,
			@numaccamt ,@intDepartmentid,@numbillamt * @numdeprate)
		  end
/**********************Section End for Purchase Return ******************************/
/**********************Section start for Petty cash Payment ******************************/
		if (@strTransType = ''HQPCP'')
		  begin
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			SELECT @intcurrencyID = depCurrencyID FROM adepartmentmaster WHERE CompanyID =@intCompanyID
			SELECT @strPNo = phPaymentNo, @dtPDate = phPaymentDate,@strremarks = phRemarks,
			  @intFinancialID = phFinancialID, @dtutime = phupdatetime,@numAccExRate = phExRate,
			  @numComExRate = phComExRate, @numDepExRate = phDepExRate,@intdepartmentid = phdepartmentid,
			  @numPAmount=phAmount,@intPAccountID=phAccountID
			FROM aHqPettyCashPaymentHeader WHERE phcancel =0 and phpostED =0 and
			  phCompanyID = @intCompanyID and phPaymentid = @intTransID
			set @intJournalID = @intJournalID + 1
			set @intJournalDetailID = 1
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, referenceno,remarks, financialID,
Type,CurrencyID,chequedate, updatetime)
			values (@intJournalID, @intCompanyID, @dtPDate, @strPNo,  @strRemarks,
			  @intFinancialID, ''HQPCP'', @intcurrencyID, @dtPdate, @dtutime)
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,Amount,
actualAmount,departmentid, depamount) values ( @intJournalID, @intJournalDetailID, @intCompanyID, 1,
@intPAccountID,(@numPAmount/@numAccExRate)*@numComExRate, @numPAmount, @intDepartmentID,
			  (@numPAmount/@numAccExRate)*@numDepExRate)
			set @intJournalDetailID = @intJournalDetailID + 1
Declare DetailCur cursor for
			  SELECT pdDetailID, pdDebitAccountID,pdAmount,pdExRate FROM aHqPettyCashPaymentDetails d,aaccountmaster a
			  WHERE a.companyid = d.pdcompanyid and a.accountid = d.pdDebitAccountid and a.CompanyID = @intCompanyID
			    and pdPaymentID = @intTransID
open DetailCur
			  fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
			  while @@Fetch_status =0
				begin			
				  insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
					Amount,actualAmount,departmentid, depamount) values ( @intJournalID, @intJournalDetailID,
					@intCompanyID, 0, @intPDAccountID,(@numPDAmount/@numPDAccExRate)*@numComExRate, @numPDAmount,
					@intDepartmentID,(@numPDAmount/@numPDAccExRate)*@numDepExRate)
				  set @intJournalDetailID = @intJournalDetailID + 1
				  fetch next FROM DetailCur into @intPDID, @intPDAccountID, @numPDAmount,@numPDAccExRate
				end
			Close DetailCur
			Deallocate DetailCur
		  end
		/*********************End Section for petty Cash payments*********************************/
if @strTransType=''HPR''
		  /*************************Section START For Hire Purchase Receipts*************************/
		  begin
/* getting the maximum Journal ID FROM journal table */
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
SELECT  @intCustomerAccID =DebtorAcc FROM ahpaccountssettings WHERE companyid = @intcompanyid
			set @intJournalID = @intJournalID + 1
			SELECT @intReceiptID = hprhReceiptID, @strReceiptno =hprhReceiptNo, @dtReceiptDate = hprhReceiptDate,
			  @intbankID = hprhAccountID, @numAmount = hprhAmount, @strremarks = hprhremarks,@intFinancialID =
			  hprhfinancialID,@intDepartmentID = hprhdepartmentID, @dtutime = hprhupdatedtime,
			  @numbankrate = hprhBankExRate,@numdeprate = hprhDepExRate,@numcusrate = hprhCusExRate,
			  @numcomrate= hprhComExRate , @intCreditAcc=isnull(HprhCreditAccid,0),@numCreditExRate=hprhCreditExRate,
			  @numCreditAmount=hprhCreditAmount
			FROM ahpReceiptheader WHERE hprhcancel =0 and hprhpostED =0 and hprhCompanyID = @intCompanyID and
			  hprhReceiptID = @intTransId
			SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID = @intCompanyID and
			  AccountID = @intbankid
			insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,remarks,financialID,Type,
			  CurrencyID,chequedate,updatetime) values (@intJournalID, @intCompanyID, @dtReceiptDate, @strReceiptno,
			  @strRemarks, @intFinancialID,''HPR'', @intcurrencyid, @dtReceiptDate, @dtutime)
			set @intJournalDetailID = 1
			insert into #JournalDetailsPreview(JournalID,journaldetailID,CompanyID,JournalCrEDit,AccountID, Amount,
			  actualAmount,departmentID, depamount)values (@intJournalID,  @intjournalDetailID, @intCompanyID, 0,
			  @intbankID,(@numamount/@numcusrate) * @numcomrate, (@numamount/@numcusrate) * @numbankrate,
			  @intDepartmentID,(@numamount/@numcusrate)* @numdeprate)
			  --@numamount * @numcomrate, @numamount*@numbankrate, @intDepartmentID,--@numamount * @numdeprate)
			
			set @intJournalDetailID = @intJournalDetailID +1
			if @intCreditAcc<>0
			  begin
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCrEDit,
				AccountID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID,  @intjournalDetailID, @intCompanyID, 1, @intCreditAcc,
				(@numCreditAmount/@numCreditExRate) * @numcomrate , @numCreditAmount, @intDepartmentID,
				(@numCreditAmount/@numCreditExRate)* @numdeprate)
				--(@numCreditAmount/@numCreditExRate) * @numcomrate , @numCreditAmount, @intDepartmentID, --(@numCreditAmount/@numCreditExRate)* @numdeprate)
				set @numamount=((@numamount / @numcusrate)-(@numCreditAmount / @numCreditExRate))*@numbankrate
				--set @numamount=((@numamount / @numbankrate)-(@numCreditAmount / @numCreditExRate))*@numbankrate
			  end
set @intJournalDetailID = @intJournalDetailID +1
			insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCrEDit,
			  AccountID, Amount, actualAmount,departmentID, depamount)
			values (@intJournalID,  @intjournalDetailID, @intCompanyID, 0, @intCustomerAccID,
			  (@numamount/@numcusrate * @numcomrate) , @numamount, @intDepartmentID,(@numamount/@numcusrate * @numdeprate))
			--@numamount * @numcomrate , @numamount*@numcusrate, @intDepartmentID,  --@numamount * @numdeprate)
		  end
		/*************************Section START For Hire Purchase Receipts*************************/
		if @strTransType=''HPP''
		/***********************Section START for  Hire Purchae Payments Transaction*****************************/
		begin
/* getting the maximum Journal ID FROM journal table */
		  SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
SELECT  @intCustomerAccID =DebtorAcc FROM    ahpaccountssettings WHERE  companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
		  SELECT @intPaymentID = hphPaymentID, @strPaymentno =hphPaymentNo, @dtPaymentDate = hphPaymentDate,
		    @intbankID = hphAccountID, @numAmount = hphPaymentAmount, @strremarks = hphremarks,
		    @intFinancialID = hphfinancialID,@intDepartmentID = hphdepartmentID, @dtutime = hphupdatetime,
		    @numbankrate = hphBankExchangeRate,@numdeprate = hphDepExchangeRate,@numcusrate = hphCusExchangeRate,
		    @numcomrate= hphComExchangeRate
		  FROM ahppaymentheader WHERE hphcancel =0 and
		    hphpostED =0 and hphCompanyID = @intCompanyID and hphPaymentID = @intTransid
SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID
			= @intCompanyID and AccountID = @intbankid
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno, remarks,financialID,Type,
			CurrencyID,chequedate,updatetime) values (@intJournalID, @intCompanyID, @dtPaymentDate, @strPaymentno,
			@strRemarks, @intFinancialID,''HPP'', @intcurrencyid, @dtPaymentDate, @dtutime)
set @intJournalDetailID = 1
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCrEDit,AccountID, Amount,
			actualAmount,departmentID, depamount)values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
			@intbankID,@numamount * @numcomrate,@numamount*@numbankrate,@intDepartmentID,@numamount * @numdeprate)
		  set @intJournalDetailID = @intJournalDetailID +1
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCrEDit,
			AccountID, Amount, actualAmount,departmentID, depamount)
		  values (@intJournalID,  @intjournalDetailID, @intCompanyID, 0, @intCustomerAccID,@numamount * @numcomrate ,
			@numamount*@numcusrate, @intDepartmentID,@numamount * @numdeprate)
		End
/***********************Section ENDS for Hire purchase PAyment Transaction *****************************/
if @strTransType = ''CT''
		/***********************Section begins for Contra Transaction *****************************/
		  begin
			/* getting the maximum Journal ID FROM journal table */
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			set @intJournalID = @intJournalID + 1
			----add a condition for display the Cheque no along with remarks in contra
			SELECT @intContraID = ContraID, @strContrano = Contrano, @dtContraDate = ContraDate,@strContratype =
			  Contratype,@intFROMbankID = FROMAccountID, @inttobankID =toAccountID,@intchargeID = chargeAccountID,
			  @numAmount = ContraAmount, @numChargeAmount = ContrachargeAmount, @strremarks = case when
			  (chequeno is null or chequeno ='''') then remarks else chequeno + '';'' + remarks end , --Ref-11
			  @intFinancialID = financialID,@intDepartmentID = departmentID, @numconsrate = ExchangeRate, @dtutime = updatetime,
			  @numdeprate = depexrate, @strexrates = exchangerates
			FROM Contra WHERE cancelled =0 and posted =0 and CompanyID = @intCompanyID and contraid = @intTransId
			SELECT @intcurrencyid = CurrencyID FROM aAccountMaster WHERE CompanyID= @intCompanyID and AccountID = @inttobankid
			insert into #JournalHeaderPreview (JournalID,CompanyID,JournalDate,referenceno,remarks,financialID,Type,
			  CurrencyID,chequedate,updatetime) values(@intJournalID, @intCompanyID, @dtContraDate, @strContraNo,
			  @strRemarks, @intFinancialID,''C'', @intcurrencyid, @dtcontradate, @dtutime)
			set @intJournalDetailID = 1
			exec spConvertequiamount @inttobankid, ''a'', @intfrombankID,
			  ''a'', @strexrates, @numamount, @numresamount output, ''''
			insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCredit,AccountID, Amount,
			  actualAmount,departmentID, depamount)values (@intJournalID,@intjournalDetailID,@intCompanyID, 1,
			  @intFROMbankID,@numamount * @numconsrate, @numresamount, @intDepartmentID,@numamount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID, JournalCredit,AccountID,Amount,
			  actualAmount,departmentID, depamount)values (@intJournalID,@intjournalDetailID,@intCompanyID,0,
			  @inttobankID,@numamount * @numconsrate , @numamount, @intDepartmentID,@numamount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
		  end  -- end of CT
/***********************Section ends for Contra Transaction *****************************/
		if (@strTransType=''DC'')
		/***********************Section begins for Debit Credit Transaction *****************************/
		  begin
			/* getting the maximum Journal ID FROM journal table */
			SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE CompanyID = @intCompanyID
			set @intJournalID = @intJournalID + 1
			SELECT @intdcniD = DCNID, @dtdcnDate = DCNDate , @intCustomerID = DCNCustomerId,@strdcnno = DCNNo,
			  @strdetails = DCNDetails, @intAccountID = DCNotheraccid,@intvendorid = DCNVendorId , @intDepartmentID =
			  DCNDepartmentID, @bitdebit = DCNDebit,@numconsRate = DCNExchangerate, @numdcnamount = DCNAmount,
			  @dtutime = updatetime,@numdeprate = dcndepexrate, @strexrates = dcnexchangerates, @intdracc1=
			  debitaccount1, @intdracc2 = debitaccount2, @numdramt1 = debitamt1, @numdramt2 =
			  debitamt2, @numotherAmount = otheraccamt FROM debitcreditnote WHERE DCNCancelled =0
			  and DCNCompanyID = @intCompanyID and dcnid = @intTransId
			-- customer
			if (@intcustomerid is not null)
			  begin
				select @intcurrencyid = currencyid from acustomermaster where
			companyid = @intcompanyid and customerid = @intcustomerid
			
			insert into #JournalHeaderPreview (JournalID,CompanyID,JournalDate,referenceno,remarks,financialID,Type,
			  CurrencyID,chequedate,updatetime) values (@intJournalID, @intCompanyID, @dtdcnDate, @strdcnNo,
			  @strdetails,@intFinancialID,''DCN'', @intcurrencyid, @dtdcndate, @dtutime)
			if (@bitdebit =0)
				set @bitoppdebit = 1
			else
				set @bitoppdebit = 0
set @intJournalDetailID = 1
			if @numdcnamount >0
			  Begin
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				  JournalCredit, customerID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,@intcustomerid,
				  (@numdcnamount * @numconsRate), @numdcnamount,@intDepartmentID,@numdcnamount * @numdepRate)
				set @intJournalDetailID = @intJournalDetailID +1
			  End
			if (@intdracc1 is not null and @numdramt1 is not null)
			  begin
				exec spConvertequiamount @intcustomerid, ''c'', @intdracc1,''a'', @strexrates, @numdramt1, @numresamount output, ''''
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
					JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,
					@intdracc1, (@numdramt1 * @numconsRate), @numresamount, @intDepartmentID,@numdramt1 * @numdepRate)
				set @intJournalDetailID = @intJournalDetailID +1
			  end
			if (@intdracc2 is not null and @numdramt2 is not null)
			  begin
				exec spConvertequiamount @intcustomerid,''c'',@intdracc2,''a'',@strexrates,@numdramt2,@numresamount output, ''''
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
					JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,@intdracc2,
				  (@numdramt2 * @numconsRate), @numresamount, @intDepartmentID,@numdramt2 * @numdepRate)
				set @intJournalDetailID = @intJournalDetailID +1
			  end
			exec spConvertequiamount @intcustomerid,''c'',@intaccountID,''a'',@strexrates, @numotherAmount, @numresamount output, ''''
			insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount)
			values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitdebit,
				@intaccountid, (@numotherAmount * @numconsRate), @numresamount, @intDepartmentID,@numotherAmount * @numdepRate)
		  end
		-- vendor
		if (@intvendorid is not null)
		  begin
			select @intcurrencyid = currencyid from avendormaster where companyid = @intcompanyid and vendorid = @intvendorid
			insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, referenceno,remarks,financialID,Type,
			  CurrencyID,chequedate, updatetime) values(@intJournalID, @intCompanyID, @dtdcnDate, @strdcnNo, @strdetails,
			  @intFinancialID,''DCN'', @intcurrencyID,@dtdcndate, @dtutime)
			set @intJournalDetailID = 1
			if (@bitdebit =0)
				set @bitoppdebit = 1
			else
				set @bitoppdebit = 0
			if @numdcnamount >0
			  Begin
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				JournalCredit, vendorID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,@intvendorid,
				  (@numdcnamount * @numconsRate), @numdcnamount, @intDepartmentID,(@numdcnamount * @numdepRate))
				set @intJournalDetailID = @intJournalDetailID +1
			  End
			if (@intdracc1 is not null and @numdramt1 is not null)
			  begin
				exec spConvertequiamount @intvendorid, ''v'', @intdracc1,''a'', @strexrates, @numdramt1, @numresamount output, ''''
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
					JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,@intdracc1,
				  (@numdramt1 * @numconsRate), @numresamount, @intDepartmentID,@numdramt1 * @numdepRate)
				set @intJournalDetailID = @intJournalDetailID +1
			  end
			if (@intdracc2 is not null and @numdramt2 is not null)
			  begin
				exec spConvertequiamount @intvendorid, ''v'', @intdracc2,''a'', @strexrates, @numdramt2, @numresamount output, ''''
				insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
				  JournalCredit, AccountID, Amount, actualAmount,departmentID, depamount)
				values (@intJournalID, @intjournalDetailID, @intCompanyID, @bitoppdebit,@intdracc2,
				  (@numdramt2 * @numconsRate), @numresamount, @intDepartmentID,@numdramt2 * @numdepRate)
				set @intJournalDetailID = @intJournalDetailID +1
			  end
			exec spConvertequiamount @intvendorid, ''v'', @intaccountID,
			  ''a'', @strexrates, @numotherAmount, @numresamount output, ''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,JournalCredit, AccountID,Amount,
actualAmount,departmentID, depamount) values (@intJournalID, @intjournalDetailID, @intCompanyID,
@bitdebit, @intaccountid,(@numotherAmount * @numconsRate), @numresamount, @intDepartmentID,
			  (@numotherAmount * @numdepRate) )
		  end
		end  -- end of DC
/***********************Section ends for Debit Credit Transaction *****************************/
if (@strTransType = ''JL'')
/***********************Section begins for Journal Transaction *****************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM aDepartmentMaster WHERE CompanyID = @intCompanyID
SELECT @intJTID = JournalTransID, @strJTNo = JournalNo, @dtJTDate = JournalTransDate,
@strremarks = remarks, @intFinancialID = financialID, @dtutime = updatetime,
@numconsrate = exchangerate, @strexrates = exchangerates, @intdepartmentid = departmentid
FROM JournalTransHeader WHERE cancelled = 0 and posted = 0 and
CompanyID = @intCompanyID and journaltransid = @intTransId
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtJTDate, @strJTNo,  @strRemarks,
@intFinancialID, ''J'', @intcurrencyID, @dtjtdate, @dtutime)
Declare DetailCur cursor for
SELECT journaltransdetailID, journaltranscredit, d.AccountID, Amount  FROM
journaltransdetails d, aaccountmaster a WHERE a.companyid = d.companyid and
a.accountid = d.accountid and a.CompanyID = @intCompanyID and JournalTransID = @intJTID
open DetailCur
fetch next FROM DetailCur into @intJTDID, @bitJTC, @intJTDAccountID, @numJTDAmount
while @@Fetch_status = 0
begin
exec spConvertequiamount @intdepartmentid, ''d'', @intJTDAccountID,
''a'', @strexrates, @numJTDAmount, @numresamount output, ''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, @bitJTC, @intJTDAccountID,
@numJTDAmount * @numconsrate, @numresamount, @intDepartmentID, @numjtdamount)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DetailCur into @intJTDID, @bitJTC,
@intJTDAccountID, @numJTDAmount
end
Close DetailCur
Deallocate DetailCur
end -- end of JL
/***********************Section ends for Journal Transaction *****************************/
/**********************Section start for Petty cash Payment ******************************/
if (@strTransType = ''INDJL'')
/***********************Section begins for Journal Transaction *****************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
SELECT @intcurrencyID = depCurrencyID FROM aDepartmentMaster WHERE CompanyID = @intCompanyID
SELECT @intJTID = JournalTransID, @strJTNo = JournalNo, @dtJTDate = JournalTransDate,
@strremarks = remarks, @intFinancialID = financialID, @dtutime = updatetime,
@numconsrate = exchangerate, @strexrates = exchangerates
FROM InterDivisionJournalTransHeader WHERE cancelled = 0 and posted = 0 and
CompanyID = @intCompanyID and journaltransid = @intTransId
--  , @intdepartmentid = departmentid
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtJTDate, @strJTNo,  @strRemarks,
@intFinancialID, ''J'', @intcurrencyID, @dtjtdate, @dtutime)
Declare DetailCur cursor for
SELECT journaltransdetailID, journaltranscredit, d.AccountID, Amount ,departmentid FROM
InterDivisionJournalTransDetails d, aaccountmaster a WHERE a.companyid = d.companyid and
a.accountid = d.accountid and a.CompanyID = @intCompanyID and JournalTransID = @intJTID
open DetailCur
fetch next FROM DetailCur into @intJTDID, @bitJTC, @intJTDAccountID, @numJTDAmount ,@intDepartmentID
while @@Fetch_status = 0
begin
exec spConvertequiamount @intdepartmentid, ''d'', @intJTDAccountID,                           ''a'', @strexrates, @numJTDAmount, @numresamount output, ''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount) values
( @intJournalID, @intJournalDetailID, @intCompanyID, @bitJTC, @intJTDAccountID,
@numJTDAmount * @numconsrate, @numresamount, @intDepartmentID, @numjtdamount)
set @intJournalDetailID = @intJournalDetailID + 10
fetch next FROM DetailCur into @intJTDID, @bitJTC,
@intJTDAccountID, @numJTDAmount ,@intDepartmentID
end
Close DetailCur
Deallocate DetailCur
end -- end of IDJL
----------------------------------------------------
/*********************End Section for petty Cash payments*********************************/
if (@strTransType = ''PS'')
/***********************Section begins for Payments transaction *****************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
--R Harikrishnan for LCtobeAccounted checking
select @LCtobeAccounted=isnull(Lctoaccount,0) from miscsettings
set @intJournalID = @intJournalID + 1
SELECT
@intPaymentID=phPaymentID, @strPaymentno= phpaymentno, @dtPaymentDate =
phpaymentdate, @strPaymentType = phLcPayment, @strRemarks = case when
(phchequedetails is null or phchequedetails ='''') then phremarks
else phchequedetails + '';'' + phremarks end, @intBankCashID = phbankcashID, @intVendorID =
phvendorID, @intCustomerID = phcustomerID, @numPaymentAmt = phAmount, @intFinancialID =
phfinancialID, @intDepartmentID = phdepartmentID,
@numvendorequiamt = phcustomeramount, @intdebit = phDebitAccountID, @numdebit =
isnull(phDebitAmount,0), @dtchequedate = phchequedate, @intGoodsInTransitAccID =
phgoodsintransitaccid, @dtutime = updatetime, @numconsrate = phexchangerate,
@numdeprate = phdepexrate, @strexrates = phexchangerates,
@intPaidByVendorid=phpaidbyvendorid
FROM
ahqPaymentVoucherHeader
WHERE
phpostED =0 and phCompanyID = @intCompanyID and
phcancellED =0 and phpaymentid = @intTransID
select
@intcurrencyid = currencyid
from
aaccountmaster where companyid =
@intcompanyid and accountid = @intBankCashID
/* finding the type of transaction */
if @strpaymentType <> ''OP'' and @strpaymentType <> ''RP'' and @strpaymentType <> ''SCP'' and @strpaymentType <> ''SPP''
begin
SELECT @numPaymentAmt = sum(pddAmount) FROM ahqPaymentVoucherdebitdetails
WHERE pddCompanyID = @intCompanyID and pddPaymentID = @intTransID
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,              referenceno, remarks, financialID, Type, CurrencyID)
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid )
set @intJournalDetailID = 1
if (@strpaymentType=''SOC'') or (@strpaymentType=''j'') OR (@strpaymentType=''CDP'') OR (@strpaymentType=''SCDP'')
begin
select @numDebitAmt=sum(isnull(pddAmount,0)) FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intTransID
exec spConvertequiamount @intcurrencyid, ''m'', @intGoodsInTransitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output, ''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount,actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intGoodsInTransitAccID, (@numDebitAmt * @numconsRate),
@numresamount, @intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
/* inserting the bank or cash */
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt, @intDepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
else                                 begin
Declare DebitCur cursor for
SELECT pddAccountID, pddAmount, pddhqpoid FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intTransID
open debitcur
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt, @inthqpoid
while @@Fetch_status =0
begin
if (@strpaymentType=''LCO'') and @LCtobeAccounted = 1 --hari
begin
if @numDebitAmt<>0
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate), @numresamount,
@intDepartmentID,(@numDebitAmt * @numdepRate) )
set @intJournalDetailID = @intJournalDetailID +1
end
end
if (@strpaymentType=''LCM'') and @LCtobeAccounted = 1
begin
if @numDebitAmt<>0  --hari 041209
Begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output,''''
-- lc amount
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate),
@numresamount, @intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
End
set @numlcamt =0.0
select @numlcamt = isnull(pohlcamount,0.0), @intdebitaccid =
pohlcaccountid from lopurchaseorderheader where pohcompanyid =
@intcompanyid and pohpoid = @inthqpoid
exec spConvertequiamount @intDebitAccID, ''a'', @intcurrencyid,
''m'', @strexrates, @numlcamt, @numresamount output,''''
if @numlcamt > 0.0
begin
-- debiting goods in transit
exec spConvertequiamount @intDebitAccID, ''a'',
@intdepartmentid, ''d'', @strexrates, @numlcamt,
@numdepcuramt output,''''
set @numlcamt = @numresamount
set @numtemp = (@numlcAmt - @numDebitAmt)
exec spConvertequiamount @intcurrencyid, ''m'',
@intGoodsInTransitAccID, ''a'', @strexrates, @numtemp,
@numresamount output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount) values (@intJournalID,
@intjournalDetailID, @intCompanyID, 0,
@intGoodsInTransitAccID, @numtemp * @numconsRate,                                         @numresamount, @intDepartmentID,
@numtemp * @numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID,
Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intdebitaccid,@numtemp * @numconsRate,
@numtemp,@intDepartmentID, @numtemp * @numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
end
end
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt,@inthqpoid
end --for a
if not (@LCtobeAccounted=0 and (@strpaymentType=''LCO'' or @strpaymentType=''LCM''))
begin
if isnull(@numPaymentAmt,0)<>0 --hari 041209
Begin
/* inserting the bank or cash */
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt, @intDepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
End
end
close DebitCur
deallocate debitcur
end
end
/*other payments*/
if ((@strpaymentType =''OP'') or
(@strpaymentType = ''LCM'' and @LCtobeAccounted = 0) or
(@strpaymentType = ''LCO'' and @LCtobeAccounted = 0)) and
(@strpaymentType <> ''SOC'' and @strpaymentType <> ''CDP'' and
@strpaymentType <> ''SCDP'' and @strpaymentType <> ''J'')
or (@strpaymentType = ''SCP'') or (@strpaymentType = ''SPP'' )
begin
if (@intvendorID is not null) and (@intPaidByVendorid is null)
begin
SELECT @intRowCount=Count(1) FROM ahqpaymentvoucherdetails WHERE pdCompanyID = @intCompanyID and
pdPaymentID = @intTransID
if @intRowCount > 0
set @strType =''SS''
else
set @strType =''SA''
end
if (@intCustomerID is not null) and (@intPaidByVendorid is null)
set @strType =''C''
if (@intvendorID is null) and (@intCustomerID is null) and (@intPaidByVendorid is null)
set @strType = ''A''
if (@intPaidByVendorid is not null)
set @strType =''MV''
if (@strType =''SA'') or (@strtype =''SS'')  -- Advance Payment to the Vendor assumes that both bank
-- and vendor curruncy are the same
begin
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid,@dtchequedate, @dtutime )
set @intJournalDetailID = 1
exec spConvertequiamount @intVendorID, ''V'', @intCurrencyID,
''m'', @strexrates, @numdebit,  @numresamount output,''''
set @numtemp = (@numpaymentamt - @numresamount)
exec spConvertequiamount @intcurrencyid, ''m'', @intvendorid,
''v'', @strexrates, @numtemp, @numresamount output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intVendorID, @numtemp * @numconsrate,
@numresamount, @intdepartmentid, @numtemp * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebit is not null)
begin
exec spConvertequiamount @intVendorID, ''V'', @intdebit,
''a'', @strexrates, @numdebit, @numresamount output,''''
exec spConvertequiamount @intVendorID, ''V'', @intcurrencyid,
''m'', @strexrates, @numdebit, @numdebit output,''''
if @numdebit >0
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdebit,
abs(@numdebit) * @numconsrate, abs(@numresamount),@intdepartmentid,
abs(@numdebit) * @numdeprate)
else
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intdebit,
abs(@numdebit) * @numconsrate, abs(@numresamount),@intdepartmentid,
abs(@numdebit) * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
if @numPaymentAmt<>0 --hari 041209
Begin
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, @numPaymentAmt * @numconsrate, @numPaymentAmt,
@intdepartmentid, @numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
ENd
end
if @strType =''C'' -- Customer Advance
begin
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
exec spConvertequiamount @intcustomeriD, ''C'', @intCurrencyID,
''m'', @strexrates, @numdebit,  @numresamount output,''''
set @numtemp = (@numpaymentamt - @numresamount)
exec spConvertequiamount @intcurrencyid, ''m'', @intcustomerid,
''c'', @strexrates, @numtemp, @numresamount output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, customerID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcustomeriD, @numtemp * @numconsrate ,
@numresamount, @intdepartmentid, @numtemp * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebit is not null)
begin
exec spConvertequiamount @intcustomeriD, ''C'', @intdebit,
''a'', @strexrates, @numdebit, @numresamount output,''''
exec spConvertequiamount @intcustomeriD, ''C'', @intcurrencyid,
''m'', @strexrates, @numdebit, @numdebit output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdebit,
@numdebit * @numconsrate , @numresamount ,@intdepartmentid,
@numdebit * @numdeprate  )
set @intJournalDetailID = @intJournalDetailID +1
end
if isnull(@numPaymentAmt,0)<>0 --hari 041209
Begin
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (
@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt ,@intdepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
end
if @strType = ''A''
begin
SELECT @numPaymentAmt = sum(pddAmount) FROM ahqpaymentvoucherdebitdetails
WHERE pddCompanyID = @intCompanyID and pddPaymentID = @intTransID
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
/* inserting the bank or cash */
if isnull(@numPaymentAmt,0)<>0 --hari 041209
Begin
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, (@numPaymentAmt * @numconsRate),
@numPaymentAmt,@intDepartmentid, (@numPaymentAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
End
Declare DebitCur cursor for
SELECT pddAccountID, pddAmount FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intTransID
open debitcur
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output,''D''
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate), @numresamount,
@intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt
end --for a
close DebitCur
deallocate debitcur
end
if @strType = ''MV''
begin
SELECT @numPaymentAmt = sum(pvdAmount) FROM aHQPaymentVoucherVendordetails
WHERE pvdCompanyID = @intCompanyID and pvdPaymentID = @intTransID
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
/* inserting the bank or cash */
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, (@numPaymentAmt * @numconsRate),
@numPaymentAmt,@intDepartmentid, (@numPaymentAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
Declare DebitCur cursor for
SELECT pvdVendorid,pvdAmount,pvdVendorAmount FROM
aHQPaymentVoucherVendordetails WHERE
pvdCompanyID = @intCompanyID and pvdPaymentID = @intTransID
open debitcur
fetch next FROM debitcur
into @intMVVendorID,@numMVAmt,@numMVVendAmt
while @@Fetch_status =0
begin
insert into #JournalDetailsPreview (JournalID, journaldetailID,
CompanyID, JournalCrEDit, VendorID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intMVVendorID, (@numMVAmt * @numconsRate), @numMVVendAmt,
@intDepartmentID, (@numMVAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM debitcur
into @intMVVendorID,@numMVAmt,@numMVVendAmt
end --for a
close DebitCur
deallocate debitcur
end
end
end   -- end of PS
/***********************Section ends for Payments Transaction *****************************/
else if (@strTransType = ''RS'')
/***********************Section begins for Receipts Transaction *****************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
#JournalHeaderPreview
WHERE
CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
begin tran
Declare ReceiptCur cursor for
SELECT
ReceiptID, receiptno, ReceiptDate, case when
(chequedetails is null or chequedetails ='''') then remarks
else chequedetails + '';'' + remarks end as remarks, bankcashAccountID,
vendorID, customerID, Amount, financialID, departmentID,ExchangeRate,
debitaccountid, isnull(debitamount,0), customeramount, chequedate,
updatetime, CreditAccountID, CreditAmount,
Convert(numeric(18,8), substring(cancelledremarks, 1, 15)),receiptcustomerid,
depexrate,exchangerates,Discountaccountid,DiscountAmount
FROM
ReceiptVoucherHeader
WHERE
posted = 0 and CompanyID = @intCompanyID and cancellED =0 and           receiptid = @intTransID
open ReceiptCur
fetch next FROM
ReceiptCur
into
@intReceiptID, @strreceiptno, @dtReceiptDate, @strRemarks,@intBankCashID,
@intVendorID, @intCustomerID, @numreceiptAmt, @intFinancialID, @intDepartmentID,
@numconsrate ,@intdebitaccid, @numdebitamt, @numcustomerequiamt,@dtchequedate,
@dtutime, @intHeaderCreditAccID, @numHeaderCreditAmount, @numPerExRate,
@intreceiptcustomerid, @numdeprate, @strexrates ,@intDiscountID,@numDisAmount
while @@Fetch_status = 0
begin
/* finding the type of transaction */
if (@intcustomerID is not null) and (@intreceiptcustomerid is null)
begin
set @intRowCount = 0
SELECT @intRowCount =count(*) FROM receiptvoucherdetails WHERE CompanyID = @intCompanyID and        ReceiptID = @intReceiptID
if @intRowCount > 0
set @strType =''CS''
else
set @strType =''CA''
end
if (@intvendorID is not null)
set @strType =''V''
if (@intvendorID is null and @intCustomerID is null and @intreceiptcustomerid is null)
set @strType = ''A''
if (@intreceiptcustomerid is not null)
set @strType = ''MC''
if (@strType =''CA'') or (@strtype =''CS'')
begin -- customer advance payment
-- getting the customer currency
SELECT @intTransCurID = CurrencyID
FROM aCustomerMaster
WHERE CompanyID = @intCompanyID
and customerID = @intCustomerID
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID,Type, CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
set @numbankamt = 0.0
set @numbankamt = (@numreceiptamt - @numdebitamt)
set @numbankamt =@numbankamt-@numDisAmount--ref-1
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intBankCashID,
@numbankamt * @numconsrate, @numbankamt, @intDepartmentID, @numbankamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
-----------------------------ref-1--------------------------------------
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID
and accountID = @intDiscountID
if (@intDiscountID is not null and @numDisAmount<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDiscountID,
''a'', @strexrates, @numDisAmount, @numresamount output ,''''
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDiscountID, @numDisAmount * @numconsrate, @numresamount,
@intDepartmentid, @numDisAmount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
------------------------------------------------------------------
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID
and accountID = @intBankCashID
if (@intdebitaccID is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output, ''''
--debiting the debit account with debit amt
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentid, @numdebitamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
exec spConvertequiamount @intcustomerid, ''c'', @intcurrencyid, ''m'',
@strexrates, @numcustomerequiamt, @numresamount output, ''''
-- crediting the customer with the whole receipt amount
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
customerID, Amount, actualAmount,departmentid,depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcustomerID, @numresamount * @numconsrate, @numcustomerequiamt,
@intDepartmentid,@numresamount * @numdeprate)
if (@intHeaderCreditAccid is not null and @numHeaderCreditAmounT <>0)
Begin
exec spConvertequiamount @intcustomerid, ''c'', @intHeaderCreditAccid, ''a'',
@strexrates, @numHeaderCreditAmount, @numresamount output, ''''
exec spConvertequiamount @intcustomerid, ''c'', @intcurrencyid, ''m'',
@strexrates, @numHeaderCreditAmount, @numCrEDitAmt output, ''''
set @intJournalDetailID = @intJournalDetailID + 1
IF @numHeaderCreditAmounT >0 --hari 040125
Begin
-- crediting the customer with the whole receipt amount
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intHeaderCreditAccid, @numCrEDitAmt * @numconsrate,
@numresamount, @intDepartmentid, @numCrEDitAmt * @numdeprate)
End
IF @numHeaderCreditAmounT <0
Begin
-- crediting the customer with the whole receipt amount
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intHeaderCreditAccid, abs(@numCrEDitAmt) * @numconsrate,
abs(@numresamount), @intDepartmentid, abs(@numCrEDitAmt) * @numdeprate)
End
End
end  -- for customer advance payment
if @strType =''V''
begin -- vendor receipt
SELECT @intTransCurID = CurrencyID
FROM avendormaster
WHERE CompanyID = @intCompanyID
AND vendorID = @intvendorID
insert into #JournalHeaderPreview
(JournalID, CompanyID, JournalDate, referenceno, remarks,
financialID,Type, CurrencyID,chequedate, updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate,
@dtutime)
set @intJournalDetailID = 1
set @numbankamt = (@numreceiptamt - @numdebitamt )
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, @numbankamt* @numconsrate, @numbankamt,
@intDepartmentID, @numbankamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
SELECT
@intcurrencyid = CurrencyID
FROM
aaccountmaster
WHERE
CompanyID = @intCompanyID and accountID = @intBankCashID
if (@intdebitaccid is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output, ''''
-- debiting the debit account
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentid, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
exec spConvertequiamount @intvendorid, ''v'', @intcurrencyid, ''m'',
@strexrates, @numcustomerequiamt, @numresamount output, ''''
-- crediting the customer with the whole receipt amount
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, vendorID,
Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intvendorID, @numresamount * @numconsrate, @numcustomerequiamt,
@intDepartmentid, @numresamount * @numdeprate)
if @intHeaderCreditAccid is not null and @numHeaderCreditAmounT <>0
Begin
exec spConvertequiamount @intvendorid, ''v'', @intHeaderCreditAccid, ''a'',
@strexrates, @numHeaderCreditAmount, @numresamount output, ''''
exec spConvertequiamount @intvendorid, ''v'', @intcurrencyid, ''m'',
@strexrates, @numHeaderCreditAmount, @numCrEDitAmt output, ''''
set @intJournalDetailID = @intJournalDetailID + 1
-- crediting the customer with the whole receipt amount
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intHeaderCreditAccid, @numCrEDitAmt * @numconsrate,
@numresamount, @intDepartmentid, @numCrEDitAmt * @numdeprate)       End
end  -- for vendor receipt
if @strType =''A''
begin -- for account heads
SELECT
@intcurrencyid = CurrencyID
FROM
aaccountmaster
WHERE
CompanyID = @intCompanyID and AccountID = @intBankcashID
insert into #JournalHeaderPreview
(JournalID, CompanyID, JournalDate, referenceno,remarks,
financialID,Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
SELECT
@numreceiptAmt = sum(Amount)
FROM
receiptvouchercrEDitdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
/* debiting either cash or bank */
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, ((@numReceiptAmt - @numdebitamt) * @numconsRate),
(@numReceiptAmt - @numdebitamt) , @intDepartmentID,
((@numReceiptAmt - @numdebitamt) * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebitaccid is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output, ''''
-- debiting the debit account
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentID, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
Declare CrEDitCur cursor for
SELECT
AccountID, Amount
FROM
receiptVouchercrEDitdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
open CrEDitCur
fetch next FROM CrEDitCur  into
@intCrEDitAccID, @numCrEDitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intcreditaccID,
''a'', @strexrates, @numcreditamt, @numresamount output, ''''
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intCrEDitAccID, (@numCrEDitAmt * @numconsRate),
@numresamount, @intDepartmentID,
(@numCrEDitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM CrEDitCur into @intCrEDitAccID, @numCrEDitAmt
end
close CrEDitCur
deallocate CrEDitCur
end -- for account heads
if @strType =''MC''
begin -- for multiple customers
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID and AccountID = @intBankcashID
insert into #JournalHeaderPreview
(JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
/* debiting either cash or bank */
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, ((@numReceiptAmt - @numdebitamt) * @numconsRate),
(@numReceiptAmt - @numdebitamt) , @intDepartmentID,
((@numReceiptAmt - @numdebitamt) * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebitaccid is not null )
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output, ''''
-- debiting the debit account
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentID, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
Declare
CrEDitCur
cursor for
SELECT
CustomerId, Amount, CustomerAmount
FROM
receiptVoucherCustomerdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
open CrEDitCur
fetch next FROM
CrEDitCur        into
@intMCCustID, @intMCAmt, @intMCCustAmt
while @@Fetch_status =0
begin
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID,
JournalCrEDit, CustomerID, Amount, actualAmount,
departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intMCCustID, (@intMCAmt  * @numconsRate),
@intMCCustAmt, @intDepartmentID, (@intMCAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM
CrEDitCur
into
@intMCCustID, @intMCAmt, @intMCCustAmt
end
close CrEDitCur
deallocate CrEDitCur
end -- for multiple customers
set @intJournalID = @intJournalID + 1
fetch next FROM
ReceiptCur
into
@intReceiptID, @strreceiptno, @dtReceiptDate, @strRemarks,
@intBankCashID, @intVendorID, @intCustomerID, @numreceiptAmt,
@intFinancialID, @intDepartmentID, @numconsrate ,@intdebitaccid,
@numdebitamt, @numcustomerequiamt, @dtchequedate, @dtutime,
@intHeaderCreditAccID, @numHeaderCreditAmount, @numPerExRate,
@intreceiptcustomerid, @numdeprate, @strexrates,@intDiscountID,@numDisAmount
end
Close ReceiptCur
Deallocate ReceiptCur
commit tran
end
--=============================*Section ends for Receipts Transaction **================
if @strTransType = ''AE''                                                           Begin  --========
/* getting the maximum Journal ID FROM journal table */
SELECT @intjournalId = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
SELECT @intCompanycurID = CurrencyID FROM acompanymaster
WHERE CompanyID =@intCompanyID
Declare JTcur cursor for
SELECT AdjustmentId, AdjustmentNo, AdjustmentDate, remarks, amount, exchangegain,
accountid, financialid, departmentid, ExchangeRates, DepExchangerate,
exchangeRate, AdjustmentType
FROM AdjustmentHeader WHERE cancelled =0 and posted =0 and
CompanyID = @intCompanyID and adjustmentid = @intTransid
open JTCur
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid,
@strbillexrates, @numDepExRate, @numConExRate, @strtype
while @@Fetch_status = 0
begin
set @intjournalId = @intjournalId + 1
set @intAdjustmentDetailId = 1
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate)
values (@intjournalid, @intCompanyID, @dtAdjustmentDate, @strAdjustmentNo,  @strRemarks,
@intFinancialID,''A'',@intCompanycurID,@dtAdjustmentDate)
set @bitjc =0
-- accounting the net
if @strextype <> '''' and @numexamount <> 0.0
begin
if upper(@strextype) = ''I''
set @bitjc = 1
else
set @bitjc = 0
SET @numresamount = 0.0
select @intCurrencyId = currencyid from
aCompanymaster where companyid = @intCOmpanyId
if right(@strtype, 1) =''D''
exec spConvertequiamount @intDepartmentid, ''d'',
@intexAccountID, ''a'', @strbillexrates,
@numexAmount, @numresamount output,''''
else
exec spConvertequiamount @intCurrencyId, ''m'',
@intexAccountID, ''a'', @strbillexrates,
@numexAmount, @numresamount output,''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intexAccountID, @numexAmount * @numConExRate, @numresamount,
@intDepartmentID, @numexAmount * @numDepExRate)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
end
Declare DetailCur cursor for
SELECT journalcredit, AccountID,customerid,vendorid, Amount, consamount FROM
adjustmentdetails WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID
open DetailCur
fetch next FROM DetailCur into @bitJC, @intAccountID,
@intcustomerid, @intvendorid, @numdAmount, @numcAmount
while @@Fetch_status = 0
begin
if isnull(@intaccountid,0) <> 0
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intAccountID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intcustomerid,0) <> 0
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, customerID, Amount, depamount, actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intcustomerID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
if isnull(@intvendorid,0) <> 0
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, vendorID, Amount,depamount,  actualAmount,departmentid) values
( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,
@intvendorID, @numcAmount, @numdAmount,0.0,@intDepartmentID)
set @intAdjustmentDetailId = @intAdjustmentDetailId + 1
fetch next FROM DetailCur into @bitJC,
@intAccountID,  @intcustomerid, @intvendorid, @numdAmount, @numcAmount
end
Close DetailCur
Deallocate DetailCur
fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,
@numexamount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid,
@strbillexrates, @numDepExRate, @numConExRate, @strtype
end
Close JTCur
Deallocate JTCur
End  --========
if @strTransType = ''Fo''
begin -- Forex preview begin
SELECT @intjournalId = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
select
@strforexno =forexno, @dtforexdate = forexdate, @strtype = type,
@intsalesorpurcaccID = salesorpurchaseaccid, @intotheraccid = otheraccid,
@intgainorlossaccid = isnull(forexgainlossaccid,0), @numsalesorpurcamt = salesorpurchaseamt,
@numotheramount = otheramount, @numgainorlossAmount = forexgainlossamt,
@strremarks = case when (chequeno is null or chequeno ='''') then remarks else
chequeno + '';'' + remarks end, @intfinancialid = financialid, @intdepartmentid =
departmentid, @numconsrate = exchangerate, @numdeprate = depexrate,
@strexrates = exchangerates
from
forex
WHERE                                                           cancellED =0 and postED =0 and CompanyID = @intCompanyID and
forexid = @intTransid
SELECT
@intcurrencyid = CurrencyID
FROM
aAccountMaster
WHERE
CompanyID = @intCompanyID and AccountID = @intsalesorpurcaccid
----RefNo:1--------
SELECT
@intconscurid = CurrencyID
FROM
aCompanyMaster
WHERE
CompanyID = @intCompanyID
---RefNo:1------
set @intjournalId = @intjournalId + 1
insert into #JournalHeaderPreview
(JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate)
values
(@intjournalid, @intCompanyID,  @dtforexDate, @strforexNo,  @strRemarks,
@intFinancialID,''For'', @intcurrencyid, @dtforexdate)
set @intJournalDetailID = 1
if @strtype =''s''
begin -- sales
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intsalesorpurcaccid, @numsalesorpurcamt * @numconsrate,
@numsalesorpurcamt, @intDepartmentID, @numsalesorpurcamt  * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
----RefNo:1---------
--exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
--''m'', @strexrates, @numotheramount, @numconsamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intconscurid,
''m'', @strexrates, @numotheramount, @numconsamount output,''''
---exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
---''d'', @strexrates, @numotheramount, @numdepamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intdepartmentid,
''d'', @strexrates, @numotheramount, @numdepamount output,''''
------RefNo:1---------
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intotheraccid,
@numconsamount, @numotheramount, @intDepartmentID, @numdepamount)
set @intJournalDetailID = @intJournalDetailID +1
-----RefNo:1-------
--To post exchange difference amount it is better to post the amount difference.
--If we post by exchnage conversion it will show some decimal difference due to rounding so it will affect TB.
--So used new approach.
exec spConvertequiamount @intsalesorpurcaccid, ''a'', @intotheraccid,
''a'', @strexrates, @numsalesorpurcamt, @numExchAmount output,''''
set @numExchComAmount=abs((@numsalesorpurcamt * @numconsrate)-@numconsamount)
set @numExchActualAmount=abs((@numExchAmount-@numotheramount))
set @numExchDepAmount=abs((@numsalesorpurcamt * @numdeprate)-@numdepamount)
-----RefNo:1------
---select @numgainorlossAmount,@numsalesorpurcamt,@numExchAmount
if @intgainorlossaccid > 0
begin -- there is a gain or loss
if @numgainorlossAmount > 0 -- gain
begin
-----RefNo:1---------
--exec spConvertequiamount @intcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--  insert into #JournalDetailsPreview
--(JournalID, journaldetailID, CompanyID, JournalCrEDit,
--    AccountID, Amount, actualAmount, departmentID, depamount)
--   values
--    (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
--    @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
--    @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intgainorlossaccid, @numExchComAmount,
@numresamount, @intDepartmentID, @numExchDepAmount)
--------RefNo:1----------
set @intJournalDetailID = @intJournalDetailID +1
end
else -- loss
begin
set @numgainorlossAmount = abs(@numgainorlossAmount)
------RefNo:1-----------
--exec spConvertequiamount @intcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into #JournalDetailsPreview
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intgainorlossaccid, @numExchComAmount,
@numresamount, @intDepartmentID, @numExchDepAmount)
-------RefNo:1-----------
set @intJournalDetailID = @intJournalDetailID +1
end
end
end
else --purchase
begin
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intsalesorpurcaccid, @numsalesorpurcamt * @numconsrate,
@numsalesorpurcamt, @intDepartmentID, @numsalesorpurcamt  * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
------RefNo:1--------
--exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
--''m'', @strexrates, @numotheramount, @numconsamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intconscurid,
''m'', @strexrates, @numotheramount, @numconsamount output,''''
--exec spConvertequiamount @intotheraccid, ''a'', @intcurrencyid,
--''m'', @strexrates, @numotheramount, @numdepamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intdepartmentid,
''d'', @strexrates, @numotheramount, @numdepamount output,''''
--insert into #JournalDetailsPreview
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
-- Amount, actualAmount,departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intotheraccid,
-- @numconsamount * @numconsrate, @numotheramount, @intDepartmentID,
-- @numdepamount * @numdeprate)
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intotheraccid,
@numconsamount , @numotheramount, @intDepartmentID,
@numdepamount )
--------RefNo:1-----------
--------RefNo:1---------
--To post exchange difference amount it is better to post the amount difference.
--If we post by exchnage conversion it will show some decimal difference due to rounding so it will affect TB.
--So used new approach.
exec spConvertequiamount @intsalesorpurcaccid, ''a'', @intotheraccid,
''a'', @strexrates, @numsalesorpurcamt, @numExchAmount output,''''
set @numExchComAmount=abs((@numsalesorpurcamt * @numconsrate)-@numconsamount)
set @numExchActualAmount=abs((@numExchAmount-@numotheramount))
set @numExchDepAmount=abs((@numsalesorpurcamt * @numdeprate)-@numdepamount)
------------RefNo:1-------------
set @intJournalDetailID = @intJournalDetailID +1
---select @numgainorlossAmount,@numsalesorpurcamt,@numExchActualAmount
if @intgainorlossaccid > 0
begin -- there is a gain or loss
if @numgainorlossAmount > 0 -- gain
begin
-------RefNo:1------
--exec spConvertequiamount @intcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into #JournalDetailsPreview
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intgainorlossaccid, @numExchComAmount,
abs(@numresamount), @intDepartmentID, @numExchDepAmount)
-------RefNo:1------
set @intJournalDetailID = @intJournalDetailID +1
end
else -- loss
begin
set @numgainorlossAmount = abs(@numgainorlossAmount)
--------RefNo:1-------
--exec spConvertequiamount @intcurrencyid, ''m'', @intgainorlossaccid,
--''a'', @strexrates, @numgainorlossAmount, @numresamount output,''''
exec spConvertequiamount @intotheraccid, ''a'', @intgainorlossaccid,
''a'', @strexrates, @numExchActualAmount, @numresamount output,''''
--insert into #JournalDetailsPreview
-- (JournalID, journaldetailID, CompanyID, JournalCrEDit,
-- AccountID, Amount, actualAmount, departmentID, depamount)
--values
-- (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
-- @intgainorlossaccid, @numgainorlossAmount * @numconsrate,
-- @numresamount, @intDepartmentID, @numgainorlossAmount * @numdeprate)
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intgainorlossaccid, @numExchComAmount,
abs(@numresamount), @intDepartmentID, @numExchDepAmount)
----------RefNo:1-----------
set @intJournalDetailID = @intJournalDetailID + 1
end
end
end
end -- Forex preview begin
--For Fixed Asset
---------------------------------------------------------------
if @strTransType = ''DPREC''
begin
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE
CompanyID = @intCompanyID
SELECT @strDepreciationNo = DepreciationNo, @dtDepreciationDate = DepreciationDate,
@strRemarks = Remarks,@intFinancialID=FinancialID, @dtutime=updatetime,@numdepRate = depexrate,@numconsRate = consexrate,
@strexrates = exChangeRates FROM depreciationheader  WHERE CompanyID = @intcompanyid and
Cancelled=0 and DepreciationID = @intTransId
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
begin
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID,Type, CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtDepreciationDate, @strDepreciationNo,
@strRemarks, @intFinancialID,''ASDP'', @intcurrencyid, @dtDepreciationDate, @dtutime)
set @numdepriamt =0
Declare DepreciationdetailCur cursor for
SELECT dd.DepreciationAccountID,dd.DepreciationAmount,fa.FixedAssetID,
dd.assetAccountID, dd.Depexpaccid  FROM depreciationdetail dd,fixedasset fa
where dd.companyid = fa.companyid and fa.FixedAssetID = dd.fixedassetid
and dd.CompanyID = @intCompanyID and dd.DepreciationID = @intTransID
open DepreciationdetailCur
fetch next FROM DepreciationdetailCur into @DepreciationAccID, @DepreciationAmount,
@FixedAssetID,@intfixedassetaccid,@intdepriciationexpaccid
while @@Fetch_status =0
begin
exec spConvertequiamount @intDepartmentID , ''d'', @DepreciationAccID, ''a'', @strexrates,
@DepreciationAmount, @numaccamt output, ''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@DepreciationAccID, @DepreciationAmount * @numconsrate, @numaccamt,
@intDepartmentID, @DepreciationAmount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
exec spConvertequiamount @intDepartmentID , ''d'', @intdepriciationexpaccid, ''a'', @strexrates,
@DepreciationAmount, @numaccamt output, ''''
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdepriciationexpaccid,
@DepreciationAmount * @numconsrate, @numaccamt, @intDepartmentid,
@DepreciationAmount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM DepreciationdetailCur into @DepreciationAccID, @DepreciationAmount,
@FixedAssetID,@intfixedassetaccid, @intdepriciationexpaccid
end
close DepreciationdetailCur
deallocate DepreciationdetailCur
end
end
-----------------------------------------------------------------------------
if (@strTransType = ''FA'')
Begin
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE
CompanyID = @intCompanyID
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
begin
SELECT @intbillrefid=fa.billsrefid,@intwriteoffrefid=fa.writeoffrefid ,
@FixedAssetID=fa.FixedAssetID ,@strrefNo = FixedAssetNo,
@intfixedassetaccid=fa.FixedAssetAccID, @dtfixedassetDate = FixedAssetDate,
@strRemarks =fa.Remarks, @intFinancialID = fa.FinancialID,
@intdepid = fa.departmentid, @numconsrate =fa.exrate, @numdepRate = fa.depexrate,
@strexrates = fa.exchangerates , @numrefamount=fa.actrefamount,
@intconversiondiffaccid=fa.conversiondiffaccid, @numAssetValue = fa.costprice,
@numDiffValue = fa.conversiondiff FROM fixedasset fa  WHERE postED =0 and
fa.CompanyID =  @intCompanyID and FixedAssetID = @intTransId
--Get vendor currency id
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID and accountid = @intfixedassetaccid
set @numvendoramt =0
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtfixedassetDate,@strrefNo,
@strRemarks, @intFinancialID, ''AST'', @intcurrencyid,@dtfixedassetDate, @dtutime)
if (@intbillrefid is not null)
begin
if @numDiffValue>0
begin
exec spConvertequiamount @intfixedassetaccid, ''a'',
@intconversiondiffaccid, ''a'', @strexrates,
@numDiffValue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intconversiondiffaccid, @numDiffValue * @numconsrate, @numaccamt,
@intDepID, @numDiffValue * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intfixedassetaccid, @numDiffValue * @numconsrate, @numDiffValue,
@intDepID, @numDiffValue * @numdeprate)
end
end
else
begin
select @intAssetConversionAccid= AssetConversionAccid  from
apackagesettings where companyid=@intCompanyID
set @numvendoramt = (@numAssetValue+@numDiffValue)
--add asset diff amount and asset amount
exec spConvertequiamount @intfixedassetaccid, ''a'',
@intAssetConversionAccid, ''a'', @strexrates,
@numvendoramt, @numaccamt output, ''''
set @intJournalDetailID = @intJournalDetailID + 1
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intAssetConversionAccid, @numvendoramt * @numconsrate,
@numaccamt, @intDepID, @numvendoramt * @numdeprate)
if @numDiffValue>0
begin
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intfixedassetaccid, ''a'',
@intconversiondiffaccid,  ''a'', @strexrates,
@numDiffValue, @numaccamt output,''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit,AccountID, vendorID, Amount, actualAmount,departmentid,
depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intconversiondiffaccid, NULL,
@numDiffValue * @numconsrate, @numaccamt, @intDepID,
@numDiffValue * @numdeprate)
end
set @intJournalDetailID = @intJournalDetailID + 1
--to debit asset account with the net value
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit,AccountID, vendorID, Amount, actualAmount,departmentid,
depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intfixedassetaccid, NULL,
@numassetvalue  * @numconsrate, @numassetvalue, @intDepID,
@numassetvalue * @numdeprate)
end
end
end
---------------------------------------------------------------
if (@strTransType = ''AT'')
BEGIN
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview WHERE
CompanyID = @intCompanyID
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
begin
SELECT @strasttrransno=asttrransno ,
@dtasttransdate=ast.asttransdate ,@intasttransassetid = ast.asttransassetid,
@intasttransfromdepid = ast.asttransfromdepid,
@intasttranstodepid = ast.asttranstodepid,
@numasttransvalue =ast.asttransvalue, @intfixedassetaccid=fa.fixedassetaccid ,
@numAccDepValue = AST.astDeprValue, @strexrates=ast.exchangerates ,
@intFinancialID = ast.financialid, @strasttrransno = ast.asttrransno,
@strasttransremarks = ast.asttransremarks, @numfromdepRate = fromdepexrate,
@numtodepRate = todepexrate, @numconsRate = consexrate,
@intAstTransFromACCID = FromAssetAccId,
@intAstTransToACCID = ToAssetAccID,
@intFromACCDeprAccId = FromACCDeprAccId,
@intToACCDeprAccId = ToACCDeprAccId
FROM fixedasset fa, assettransfer  ast  WHERE fa.FixedAssetID = ast.asttransid
and ast.asttranscompanyid = fa.CompanyID and ast.asttransposted =0 and
ast.asttranscompanyid =  @intCompanyID and ast.asttransid = @intTransId
--check whether asset departmenttransfer or account transfer
if @intasttranstodepid is not null
begin
select @inttransferaccountid = transferaccount from asettings
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,
remarks, financialID,Type,chequedate)
values (@intJournalID, @intCompanyID, @dtasttransdate,@strasttrransno,
@strasttransremarks, @intFinancialID, ''ASTR'', @dtasttransdate)
exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'',
@strexrates, @numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numasttransvalue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
@strexrates, @numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@inttransferaccountid, @numasttransvalue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numasttransvalue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'',
@strexrates, @numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
@intasttranstodepid, @numasttransvalue * @numtodepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
@strexrates, @numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@inttransferaccountid, @numasttransvalue * @numconsrate, @numaccamt,
@intasttranstodepid, @numasttransvalue * @numtodepRate)
-- Depritiation
if @numAccDepValue <> 0
Begin
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @intFromACCDeprAccId, ''a'',
@strexrates, @numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numAccDepValue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
@strexrates, @numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@inttransferaccountid, @numAccDepValue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numAccDepValue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @intFromACCDeprAccId, ''a'',
@strexrates, @numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
@intasttranstodepid, @numAccDepValue * @numtodepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @inttransferaccountid, ''a'',
@strexrates, @numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@inttransferaccountid, @numAccDepValue * @numconsrate, @numaccamt,
@intasttranstodepid, @numAccDepValue * @numtodepRate)
End
end
else
begin
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,referenceno,
remarks, financialID,Type,chequedate)
values (@intJournalID, @intCompanyID, @dtasttransdate,@strasttrransno,
@strasttransremarks, @intFinancialID, ''ASTR'', @dtasttransdate)
exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransFromACCID, ''a'', @strexrates,
@numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intAstTransFromACCID, @numasttransvalue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numasttransvalue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intasttransfromdepid, ''d'', @intAstTransToACCID, ''a'', @strexrates,
@numasttransvalue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intAstTransToACCID, @numasttransvalue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numasttransvalue * @numfromdepRate)
if @numAccDepValue <> 0
Begin
set @intJournalDetailID = @intJournalDetailID + 1
-- ACCUM DEP ACC TRANSFER DEBITED IN FROM ACCOUNT
exec spConvertequiamount @intasttransfromdepid, ''d'',
@intFromACCDeprAccId, ''a'', @strexrates,
@numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intFromACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numAccDepValue * @numfromdepRate)
set @intJournalDetailID = @intJournalDetailID + 1
-- ACCUM DEP ACC TRANSFER CREDITED IN TO ACCOUNT
exec spConvertequiamount @intasttransfromdepid, ''d'', @intToACCDeprAccId, ''a'', @strexrates,
@numAccDepValue, @numaccamt output, ''''
insert into #JournaldetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intToACCDeprAccId, @numAccDepValue * @numconsrate, @numaccamt,
@intasttransfromdepid, @numAccDepValue * @numfromdepRate)
End
end
end
end
--------------------------------------------------------------------------
if (@strTransType = ''AD'')
Begin
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview 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 = @intTransId
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
begin
insert into #JournalHeaderPreview (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 = @intTransId
and dispdasstid = fa.FixedAssetID and dispdcompanyid = fa.CompanyID
select @intDepExpControlAccId = depriciationexpaccid from aSettings
where CompanyId = @intCompanyId
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 #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intassetaccountid, @numDebitAmt  * @numconsrate, @numaccamt,
@intDepID, @numDebitAmt  * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepid, ''d'',
@intDiposalAccId, ''a'', @strexrates,
@numDebitAmt , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDiposalAccId, @numDebitAmt  * @numconsrate, @numaccamt,
@intDepID, @numDebitAmt  * @numdeprate)
if @numDisDepeBalamt <> 0
Begin
set @intJournalDetailID = @intJournalDetailID + 1
--FOR POSTING REMAINING DEPRECIATION -------------------------------->
exec spConvertequiamount @intdepid, ''d'',
@intAccumDepaccid, ''a'', @strexrates,
@numDisDepeBalamt , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intAccumDepaccid, @numDisDepeBalamt  * @numconsrate, @numaccamt,
@intDepID, @numDisDepeBalamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepid, ''d'',
@intDepExpAccId, ''a'', @strexrates,
@numDisDepeBalamt , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid,
depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDepExpAccId, @numDisDepeBalamt * @numconsrate, @numaccamt,
@intDepID, @numDisDepeBalamt * @numdeprate)
End
--FOR POSTING REMAINING DEPRECIATION -------------------------------->
--<POSTING ACC DEP REVERSING VALUE FOR THE ASSET ---------------------
set @numUPTODepValue = isnull(@numDisDepeBalamt,0) + isnull(@numUPTODepValue,0)
if @numUPTODepValue <> 0
Begin
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepid, ''d'',
@intDiposalAccId, ''a'', @strexrates,
@numUPTODepValue , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intDiposalAccId, @numUPTODepValue * @numconsrate, @numaccamt,
@intDepID, @numUPTODepValue * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepid, ''d'',
@intAccumDepaccid, ''a'', @strexrates,
@numUPTODepValue , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID,0 ,
@intAccumDepaccid, @numUPTODepValue * @numconsrate, @numaccamt,
@intDepID, @numUPTODepValue * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
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 #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intDiposalAccId,  @numDispSalesValue * @numconsrate, @numaccamt,
@intDepID,  @numDispSalesValue * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepid, ''d'',
@intDepExpControlAccId, ''a'', @strexrates,
@numDispSalesValue , @numaccamt output,''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0 ,
@intDepExpControlAccId,  @numDispSalesValue * @numconsrate, @numaccamt,
@intDepID,  @numDispSalesValue * @numdeprate)
End
--<POSTING OF SALES WHILE DISPOSING -----------------------------------
set @intJournalDetailID = @intJournalDetailID + 1
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
close DebitassetdisposalCur
deallocate DebitassetdisposalCur
-- select * from #JournalHeaderPreview
-- select * from #JournalDetailsPreview
end
--------------------------------------------------------------------------
if (@strTransType = ''PAY'')
begin
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
#JournalHeaderPreview
WHERE
CompanyID = @intCompanyID
SELECT
@strTransNo =TransNo, @dtTransDate = TransDate,
@strremarks = remarks, @dtutime = updatetime,
@intdepartmentid = departmentid
FROM                 paPayAccLinkHeader
WHERE
cancellED =0 and postED =0 and CompanyID = @intCompanyID and
TransID = @intTransid
SELECT
@intcurrencyID = depCurrencyID
FROM
adepartmentmaster
WHERE
CompanyID =@intCompanyID and
departmentid = @intdepartmentid
select
@intFinancialID = financialID
from
vwfinyearperiod
where
@dtTransDate between sdate and edate
set @intJournalID = @intJournalID + 1
set @intJournalDetailID = 1
insert into #JournalHeaderPreview
(JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values
(@intJournalID, @intCompanyID, @dtTransDate, @strTransNo,  @strRemarks,
@intFinancialID, ''PAY'', @intcurrencyID, @dtTransDate, @dtutime)
Declare DetailCur cursor for
SELECT
AccountID, AccCurrID, sum(abs(DebitAmount)),
sum(abs(CreditAmount)), sum(abs(DeptAmount)), sum(abs(CompAmount) )
FROM
paPayAccLinkPostingDetails
WHERE            CompanyID = @intCompanyID and TransID = @intTransID
group by
AccountID, AccCurrID
open DetailCur
fetch next FROM
DetailCur
into
@intAccountID, @intcurrencyid, @numDrAmount,@numCrAmount, @numDepAmount,
@numCompAmount
while @@Fetch_status =0
begin
if (@numDrAmount > @numCrAmount)
Begin
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intJournalDetailID, @intCompanyID, 0,
@intAccountID, @numCompAmount, @numDrAmount - @numCrAmount,
@intDepartmentID, @numDepAmount)
set @intJournalDetailID = @intJournalDetailID + 1
End
else if (@numDrAmount < @numCrAmount)
begin
insert into #JournalDetailsPreview
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intJournalDetailID, @intCompanyID, 1,
@intAccountID, abs(@numCompAmount), abs(@numCrAmount - @numDrAmount),
@intDepartmentID, abs(@numDepAmount))
set @intJournalDetailID = @intJournalDetailID + 1
end
fetch next FROM
DetailCur
into
@intAccountID, @intcurrencyid, @numDrAmount,@numCrAmount, @numDepAmount,
@numCompAmount
end
Close DetailCur
Deallocate DetailCur
end
--------------------------------------------------------------------------
/***********************Section begins for HQ Writeoff Transaction *****************************/
if (@strTransType = ''HW'')
Begin
--get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster WHERE CompanyID = @intCompanyID
select @intExcessShortageDiffaccId = HQPurchaseAccId,
@strzerorate = substring(isnull(futurevc,''''),1,1),
@stockTransferAcc = stocktransfercontrolacc,
@intInventoryAccId = InventoryID from apackagesettings
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare swocur cursor for
SELECT swID, swTransCode + rtrim(convert(varchar(50),swID)),
swdate, ''system'', isnull(swShopID,0) s, isnull(swGodownID,0) g, updatetime,
swWriteOffType, swdepExRate, swdConExRate, swExchangeRates
FROM  moStockWriteOffHQ WHERE swposted =0 and swID = @intTransId
open swocur
fetch next FROM  swocur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
@intshopid, @intgodownid, @dtutime, @IntTransferType, @numDepExRate, @numConExRate,
@strExRates
while @@Fetch_status = 0
begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster a
where a.AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
--to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
--and the item master table. If so we cannot do any thing in the posting with out item rate.
--so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
if @intshopid<>0 and @intshopid is not null
begin
select @intFailcount = count(*) from moStockWriteOffHQ, aitem where
swID = @intswoiD and swShopID = @intshopid and swItemID = itemid
and (swCostPrice=null or swCostPrice=0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
set @intfailcount=0
end
if @intgodownid <> 0 and @intgodownid is not null
begin
select @intFailcount = count(*) from moStockWriteOffHQ, aitem where
swID = @intswoiD and swgodownid = @intgodownid and swItemID = itemid
and (swCostPrice=null or swCostPrice=0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
set @intfailcount=0
end
set @intfailcount = 0 -- to allow posting even the itemrate is 0
if @intfailcount = 0 -- for item rate=0 check
begin
if @intgodownid <> 0
begin
-- to update the item rate to the gadcostprice
update moStockWriteOffHQ set swCostPrice = itemrate from
aitem where ( swCostPrice =null or swCostPrice =0) and swID = @intswoiD
and swgodownid = @intgodownid and switemid = itemid
end
else
begin
-- to update the item rate to the gadcostprice
update moStockWriteOffHQ set swCostPrice = itemrate from
aitem where ( swCostPrice =null or swCostPrice =0) and swID = @intswoiD
and swshopid = @intshopid and switemid = itemid
end
if (@intgodownid > 0)
select @intDepartmentID = departmentid, @intswoaccid = stockwriteoffaccid
from agodown where godownid = @intgodownid
else                                  select @intDepartmentID = departmentid, @intswoaccid = stockwriteoffaccid
from ashops where shopid = @intshopid
set @numStockAddclear = 0.0
set @numStockDedclear = 0.0
-- getting the total amount with qty and item cost price
select @numswoAmt = isnull(sum((isnull(swAddStock,0) + isnull(swDedStock,0))
* swCostPrice),0), @numStockAddclear = SUM(isnull(swAddStock,0)),
@numStockDedclear = sum(isnull(swDedStock,0)) from moStockWriteOffHQ where swid = @intswoiD
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,                                     @strRemarks, @intFinancialID, ''hqswo'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
if @numStockAddclear >0
Begin
if @intTransferType = 0
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intswoaccid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt,
@numAaccAmt output
--debiting hte inventory accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intswoaccid,
@numswoamt * @numConExRate, @numAaccAmt, @intdepartmentid,
@numswoamt * @numDepExRate)
End
ELSE
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExcessShortageDiffaccId
and companyId = @IntCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intExcessShortageDiffaccId,                       @numswoamt * @numConExRate, @numAaccAmt , @intdepartmentid, @numswoamt * @numDepExRate )
eND
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @stockTransferAcc
and companyId = @IntCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
set @intJournalDetailID = @intJournalDetailID + 1
-- Credit transfer account
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@stockTransferAcc, @numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate)
End
if @numStockDEDclear >0
Begin
if @intTransferType = 0
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intswoaccid
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, Depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intswoaccid,
@numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
eND
eLSE
Begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExcessShortageDiffaccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
--debiting hte inventory accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intExcessShortageDiffaccId,
@numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
eND
set @intJournalDetailID = @intJournalDetailID +1
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @stockTransferAcc
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numswoamt, @numAaccAmt output
-- Credit transfer account
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount, actualamount,departmentid, DepAmount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@stockTransferAcc, @numswoamt * @numConExRate, @numAaccAmt,
@intdepartmentid, @numswoamt * @numDepExRate )
End
set @intJournalID = @intJournalID + 1
end -- for item rate=0 check
fetch next FROM  swocur into @intswoiD, @strswono, @dtswoDate, @strRemarks,
@intshopid, @intgodownid, @dtutime, @IntTransferType, @numDepExRate,
@numConExRate, @strExRates
end -- CUR END
Close swocur
Deallocate swocur
End
/***********************Section ENDS for HQ Writeoff Transaction *****************************/
--**=========================Shop Inhouse Consumption=====start===================**---
if @strTransType=''SIHC''
Begin
-- get the companyCurrencyID
SELECT @intCompanyCurID = CurrencyID
FROM acompanymaster WHERE CompanyID = @intCompanyID
select @intinventoryaccid = InventoryID, @strzerorate = substring(isnull(futurevc, ''''), 1, 1) from apackagesettings
select @ItemwiseAccounting=isnull(ItemwiseAccountinginInHousecon,0) from apackagesettings --to check wheather Itemwise accounting is enabled or not
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
Declare scoCur cursor for
SELECT whID, whno, whdate,  whremarks, updatetime, whdepartmentid,
isnull(whExpenseAccId,0)  whExpenseAccId,
whConExRate,
whDepExRate, whExchangeRates,whotherdepid,whtodepexrate
FROM loswriteoffheader WHERE
whcancellED =0 and whshopid = @intshopID and whposted =0 and whID=@intTransID
and whtype=''I'' and whVerified=1
open ScoCur
fetch next FROM  ScoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
while @@Fetch_status = 0
begin -- cur begin
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate
-- to check the no of records with item rate =0 or null in both the detail table
-- and the item master table. If so we cannot do any thing in the posting with out item rate.
-- so that transaction will be avoided from posting
-- hariharan 011211
set @intFailcount = 0
select @intFailcount = count(*) from loswriteoffdetail, aitem where
WdID = @intswoiD and wdShopID = @intshopID and WdItemID = itemid
and ( wdcostprice =null or wdcostprice = 0) and (itemrate=0 or itemrate is null)
-- to allow to proceed if allow zero rate condition given - hari 020905
if @strzerorate = ''z''
begin
set @intfailcount=0
end
if @intfailcount = 0 -- for item rate=0 check hari 011213
begin
-- to update the item rate to the gadcostprice
update loswriteoffdetail set wdcostprice = itemrate from
aitem where ( wdcostprice =null or wdcostprice = 0) and wdid = @intswoiD
and wdShopID = @intshopID and WdItemID = itemid
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtswoDate, @strswono,
@strRemarks, @intFinancialID, ''scon'', @intcompanycurID, @dtswoDate, @dtutime )
set @intJournalDetailID = 1
-- getting the total amount with qty and item cost price
select @numSwoAmt = isnull(sum(wdwriteoffqty * wdcostprice),0) from
loswriteoffdetail swod
where wdshopid = @intshopID and wdid = @intswoid
if @ItemwiseAccounting<> 0 --if itemwise accounting is enabled item amount is posted to corresponding account
begin
declare acntcurs cursor for select WdWriteoffQty,wdcostprice,WdInhouseConsAccnt
FROM loswriteoffdetail where wdshopid = @intshopID and wdid = @intswoid
open acntcurs
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt
if @InhouseAccnt is not null --to check wheather there is unposted transaction done bofore setting the itemwise accounting
begin
while @@fetch_status=0
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @InhouseAccnt
set @ItemAmount=isnull(sum(@WriteoffQty * @costprice),0)
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@ItemAmount,
@numAaccAmt output
-- debiting the stock consumption accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@InhouseAccnt ,
@ItemAmount * @numConExRate, @numAaccAmt,
@ItemAmount * @numDepExRate, @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next from acntcurs into @WriteoffQty,@costprice,@InhouseAccnt
end
if @intDepartmentID<> @intToDepId --to post to control acc in the case of Itemwise is enabled and different departmnts
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- crediting the control accid  for the current department
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 1,
@intExpenseAcId ,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intDepartmentID)
set @intJournalDetailID = @intJournalDetailID + 1
-- debiting the stock consumption accid for todept
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intToDepId)
set @intJournalDetailID = @intJournalDetailID + 1
end
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- debiting the stock consumption accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intDepartmentId)
set @intJournalDetailID = @intJournalDetailID + 1
end
close acntcurs
deallocate acntcurs
end
else
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intExpenseAcId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSwoAmt,
@numAaccAmt output
-- debiting the stock consumption accid
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,
DepAmount, departmentID)
values
(@intJournalID, @intJournalDetailId, @intCompanyID, 0,
@intExpenseAcId ,
@numSwoAmt * @numConExRate, @numAaccAmt,
@numSwoAmt * @numDepExRate, @intDepartmentId)
set @intJournalDetailID = @intJournalDetailID + 1
end
-- credit the inventory acc id
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountid, Amount,
actualamount, DepAmount,
departmentid) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intinventoryaccid, @numSwoAmt * @numConExRate, @numSwoAmt,
@numSwoAmt * @numDepExRate, @intdepartmentid )
set @intJournalID = @intJournalID + 1
end -- for item rate=0 check hari 011213
fetch next FROM  scoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks, @dtutime,
@intDepartmentID, @intExpenseAcid,@numConExRate, @numDepExRate, @strExRates,@intToDepId,@numToDepExRate
end -- CUR END
Close scoCur
Deallocate scoCur
end
--**=========================Shop Inhouse Consumption=====end===================**------=============================================
------------------------------------------------RefNo-01----------------------------------------
/*******************Section for creating ledger preview for InterDivision Bills Transaction****************/
if (@strTransType = ''IDBL'')
/**************************************************************************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0)
FROM #JournalHeaderPreview WHERE
CompanyID = @intCompanyID
SELECT @intBillsID = BillsID, @strBillsno = Billsno,
@dtBillsDate = BillDate,
@intVendorID = vendorID,
@intDiscountAccID = discountAccountID,
@numDiscount = discount,
@numBillAmt = billAmount, @strRemarks = case
when (chequeno is null or chequeno ='''')
then remarks else chequeno + '';'' + remarks end ,
@intFinancialID = FinancialID,
@intCashBankID = bankcashaccID, @dtutime = updatetime,
@intdepartmentid = departmentid,
@strexrates = exchangerates, @numdepRate = depexrate,
@numconsrate = exchangerate
FROM interdivisionbillsheader WHERE posted = 0 and CompanyID = @intCompanyID
and cancelled = 0 and billsid = @intTransId
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
-- -- get cash or credit
-- if (@intCashBankID is null) --credit trans
--  begin
SELECT @intcurrencyid = CurrencyID FROM aVendorMaster
WHERE CompanyID = @intCompanyID and vendorID = @intvendorID
insert into #JournalHeaderPreview (JournalID, CompanyID,
JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsNo,
@strRemarks, @intFinancialID, ''IDB'', @intcurrencyid, @dtBillsDate, @dtutime)
set @numvendoramt = 0
Declare DebitBillCur cursor for
SELECT AccountID, Amount,Departmentid FROM interdivisionbillsdetails
WHERE CompanyID = @intCompanyID and BillsID = @intBillsID
open debitbillcur
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt,@IntDetailDeptId
while @@Fetch_status = 0
begin
exec spConvertEquiAmount @intvendorid, ''v'', @intdebitaccid, ''a'', @strexrates,
@numdebitamt, @numaccamt output, ''''
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, @numDebitAmt * @numconsrate, @numaccamt,
@IntDetailDeptId, @numDebitAmt * @numdeprate)
set @numvendoramt = isnull(@numvendoramt,0) + isnull(@numDebitAmt ,0)
set @intJournalDetailID = @intJournalDetailID + 1
fetch next FROM debitbillcur into @intDebitAccID, @numDebitAmt,@IntDetailDeptId
end
close DebitBillCur
deallocate debitbillcur
insert into #JournalDetailsPreview (JournalID, journaldetailID, CompanyID,
JournalCredit, vendorID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intVendorID,
@numvendoramt * @numconsrate, @numvendoramt, @intDepartmentID,
@numvendoramt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID + 1
--end --for credit trans
end  -- end of IDBL
/*******************Section ends for creating ledger preview for Inter Division Bills Transaction****************/
------------------------------------------------RefNo-01----------------------------------------
------------------------------------------------RefNo-02 ----------------------------------------
/*******************Section for creating ledger preview for InterDivision Bills Transaction****************/
if (@strTransType = ''PDCHECK'')
/**************************************************************************************/
begin
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0)
FROM #JournalHeaderPreview WHERE
CompanyID = @intCompanyID
SELECT @intBillsID = PDTransId, @strBillsno = PDChequeDtlPrefix,@dtBillsDate = PDChequeEntryDate,
@intcustomerID = CustomerID,--,@intDiscountAccID = discountAccountID,@numDiscount = discount,
@numBillAmt = Amount, @strRemarks = remarks, --case  when (chequeno is null or chequeno ='''')
--then remarks else chequeno + '';'' + remarks end ,
@intFinancialID = FinancialID,  @dtutime = updatetime,--@intCashBankID = bankcashaccID,
@intdepartmentid = departmentid, @strexrates = exchangerates, @numdepRate = depexchangerates,
@numconsrate = exchangerate
FROM ahqPostDatedChequeDetails  inner join ahqPDChequeprocessing
on ahqPostDatedChequeDetails.TransID  = ahqPDChequeprocessing.PDTransId
WHERE Cancel =0 and ahqPDChequeprocessing.PDChequePosted =0 and
CompanyID = 1 and TransID = @intTransPDCHECKId     and PDChequeid = @intChequeDtlID  --
set @intJournalDetailID = 1
set @intJournalID = @intJournalID + 1
SELECT  @intcurrencyid = CurrencyID FROM acustomermaster
WHERE CompanyID = @intCompanyID and customerid = @intcustomerID
insert into #JournalHeaderPreview (JournalID, CompanyID,
JournalDate,referenceno,
remarks, financialID,Type,CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtBillsDate, @strBillsno,
@strRemarks, @intFinancialID, ''PDCHECK'', @intcurrencyid, @dtBillsDate, @dtutime)
set @numvendoramt = 0
Declare DebitBillCur cursor for
SELECT d.PDChequeid,p.DepartmentID,d.PDChequeDebitAccid,d.PDChequeCreditAccid,p.Amount,exchangerates FROM
ahqPostDatedChequeDetails p inner join ahqPDChequeprocessing d
on p.TransID  = d.PDTransId , aaccountmaster a WHERE a.companyid = p.companyid and
a.accountid = d.PDChequeDebitAccid    and a.CompanyID = @intCompanyID and transid = @intTransPDCHECKId    -- @intTransPDCHECKId
and  PDChequeid = @intChequeDtlID
open debitbillcur
fetch next FROM DebitBillCur into @intChequeDtlID,@intDepartmentID,@intPDChequeDebitAccid,
@intPDChequeCreditAccid,@numBillAmt ,@strexrates
while @@Fetch_status = 0
begin
--     exec spConvertEquiAmount @intvendorid, ''v'', @intdebitaccid, ''a'', @strexrates,
--@numdebitamt, @numaccamt output, ''''
exec spConvertequiamount @intdepartmentid, ''d'', @intPDChequeDebitAccid,
''a'', @strexrates, @numAmount, @numresamount output ,''''
--debit
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount)  values
( @intJournalID, @intJournalDetailID, @intCompanyID, 0, @intPDChequeDebitAccid,
@numBillAmt * @numconsrate,@numBillAmt , @intDepartmentID, @numresamount)-- @numresamount)
set @intJournalDetailID = @intJournalDetailID + 1
exec spConvertequiamount @intdepartmentid, ''d'', @intPDChequeCreditAccid,
''a'', @strexrates, @numAmount, @numresamount output ,''''
--credit
insert into #JournalDetailsPreview(JournalID, journaldetailID, CompanyID,
JournalCredit, AccountID, Amount, actualAmount,departmentid, depamount)  values
( @intJournalID, @intJournalDetailID, @intCompanyID, 1, @intPDChequeCreditAccid,
@numBillAmt * @numconsrate, @numBillAmt, @intDepartmentID,@numresamount)--,  @numresamount)
--update ahqPDChequeprocessing  set PDChequePosted =1 WHERE
--PDTransId = @intTransid  and   pdchequeid = @intChequeDtlID
fetch next FROM debitbillcur into  @intChequeDtlID,@intDepartmentID,@intPDChequeDebitAccid,
@intPDChequeCreditAccid,@numBillAmt ,@strexrates
end
close DebitBillCur
deallocate debitbillcur
--set @intJournalDetailID = @intJournalDetailID + 1
end
/*******************Section ends for creating ledger preview for Inter Division Bills Transaction****************/
------------------------------------------------RefNo-02   ----------------------------------------
--**==============================Hire Purchase Reprocessing====START======================**-----
if @strTransType=''HPRPAS''
Begin
select
@intcurrencyid = CurrencyId
from
acompanymaster
where
companyid = @intcompanyid
/* getting the maximum Journal ID FROM journal table */
SELECT @intJournalID = isnull(max(JournalID),0) FROM #JournalHeaderPreview
WHERE CompanyID = @intCompanyID
Select
@intCustomerAccID =DebtorAcc ,@intAdjustmentAccID=AdjustmentAcc ,@intInterestAccId=SuspenseAcc
from
ahpaccountssettings
where
companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
set @intProcessingID=@strTransid
select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo,
@dtDate=hphProcessingDate, @Adjustmentamnt=hphAdjustmentAmount, @UnearnedIncome=hphBalanceInterest,
@strremarks=hphRemarks,@intFinancialID=hphFinancialID, @CustomerId=hphCustomerID,@dtutime=hphUpdateTime
FROM ahpprocessingdetail left outer join ahpprocessingheader
on hpdprocessingID=hphProcessingID and hpdCompanyID=hphCompanyID
WHERE hphreprocessaftersettlement=1 and hphReferenceID is not null  and hpdProcessingID= @strTransid and hphCompanyID =@intCompanyID
insert into #JournalHeaderPreview (JournalID, CompanyID, JournalDate,
referenceno, remarks,financialID,Type, CurrencyID,updatetime) values
(@intJournalID, @intCompanyID, @dtDate, @strProcessingNo,
@strRemarks, @intFinancialID,''HPRPAS'', @intcurrencyid,@dtutime)
--''HPRPAS''---HP Reprocessing After Settlement
set @intJournalDetailID = 1
if @intAdjustmentAccID<>0  and  @intInterestAccId<>0
begin
/* Debiting Adjustment Carrying Amount in Adj. account*/
--(@Adjustmentamnt-@UnearnedIncome)===Adjustment Carrying Amount
insert into #JournalDetailsPreview
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID,0,@intAdjustmentAccID,
(@Adjustmentamnt-@UnearnedIncome) , (@Adjustmentamnt-@UnearnedIncome),@intDepartmentID, (@Adjustmentamnt-@UnearnedIncome), 1)
set @intJournalDetailId = @intJournalDetailId +1
/* Debiting  in Unearned income account */
insert into #JournalDetailsPreview
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intInterestAccId,
@UnearnedIncome,@UnearnedIncome,@intDepartmentID, @UnearnedIncome, 1)
set @intJournalDetailId = @intJournalDetailId +1
set @CustomerAmount= @Adjustmentamnt
/* Crediting against customer account */
insert into #JournalDetailsPreview
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerID,
Amount, actualAmount, departmentID, depamount, PostGroup)
values
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@CustomerId ,
@CustomerAmount,@CustomerAmount,@intDepartmentID,@CustomerAmount, 1)
end
end
--**==============================Hire Purchase Reprocessing====END======================**-----
end -- end of While loop(should be the second last end (before procedure end))
-- select the records from temporary tables
SELECT
h.JournalID, h.CompanyID, h.JournalDate, h.remarks,
d.departmentID, dept.DepartmentName,
h.referenceno, h.financialID,
h.type, d.Amount,d.Actualamount, depAmount,
case when d.accountid is not null then accountdesc
when d.customerid  is not null then customername
when d.vendorid is not null then vendorname end as particulars,
d.journalcredit
FROM
#JournalHeaderPreview h, #JournalDetailsPreview d
left outer join aaccountmaster am on d.companyid = am.companyid
and d.accountid = am.accountid
left outer join acustomermaster cm on d.companyid = cm.companyid
and d.customerid = cm.customerid
left outer join aVendorMaster vm on d.companyid = vm.companyid
and d.vendorid = vm.vendorid
left outer join aDepartmentMaster Dept on
d.DepartmentID = Dept.DepartmentID AND D.COMPANYID=DEPT.COMPANYID
WHERE
h.JournalID = d.JournalID and h.CompanyID = d.CompanyID
drop table #JournalHeaderPreview -- #JournalHeaderPreview #JournalDetailsPreview
drop table #JournalDetailsPreview
set nocount off
end -- end of proc' 
END
GO
/****** Object:  View [dbo].[vwCAshSalesGSTSeparately]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
-- 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 [dbo].[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
/****** Object:  View [dbo].[vwCAshSalesDetGSTSeprately]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDetGSTSeprately]'))
EXEC dbo.sp_executesql @statement = N'
--  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
/****** Object:  View [dbo].[vwCAshSalesDetAsOn15062011]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDetAsOn15062011]'))
EXEC dbo.sp_executesql @statement = N'
/*
	IF EXISTS(SELECT *  FROM sys.views WHERE name =''vwCAshSalesDet'')
	   DROP view dbo.vwCAshSalesDet
	GO
*/
	create View [dbo].[vwCAshSalesDetAsOn15062011] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
From  losposheader ph,losposdetail pd   Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate
UniOn All
Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,
COnvert(numeric(18,2),Sum(amount)) As amount,
COnvert(numeric(18,2),Sum(damount)) As damount,
COnvert(numeric(18,2),Sum(camount)) As camount,
1,''E''  As transtype, departmentid departmentid
From  vwPosExchangeDetails
Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid ,
sehcAshaccid,departmentid
Having Sum(amount)<0
UniOn All
Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,
COnvert(numeric(18,2),Sum(amount)) As amount,
COnvert(numeric(18,2),Sum(damount)) As damount,
COnvert(numeric(18,2),Sum(camount)) As camount,
1,''c''  As transtype, departmentid departmentid
From  vwPosExchangeDetails
Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid,
sehcAshaccid,departmentid
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(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
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
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid
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
UniOn All
--direct invoice
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice, ''s'' As transtype, lah.aidepartmentid  departmentid
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''GRD'' As transtype, Grnhdepartmentid  departmentid
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid 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
/****** Object:  View [dbo].[vwCAshSalesDet]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesDet]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------
--RefNo        : RefNo-1
--Modified by  : Bijesh.B
--Date         : 30/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
--BackUp       : [vwCAshSalesDetAsOn15062011]
-----------------------------------------------------------------------------------------
-- Modified by : Bijesh.B
-- Date        : 03/07/2011
-- RefNo       : RefNo-2
-- Comments    : Removed the link from ahqPostDatedChequeDetails
--               Need to show ''pd cheque amount'' even if it is not registered
------------------------------------------------------------------------------------------
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 29/07/2011
--Comments     : Bugsheet - Special invoice cash and credit is wrong
----------------------------------------------------------------------------------------------
CREATE View [dbo].[vwCAshSalesDet] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
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
--CASH + PD CHEQUE -> Taking only cash amount
Select poshcompanyid As companyid, ph.poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid,
convert(numeric(18,2),sum(posdunitprice)-pdCheque.PosBankAmount)AS amount,
convert(numeric(18,2),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount)AS damount,
convert(numeric(18,2),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount)AS camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
From  losposheader ph,losposdetail pd,losPosChequeDetails PDCheque
Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
and PDCheque.PoshBillID = ph.poshbillid  and isnull(ph.PosPostDate,0)=1
Group By poshcompanyid , ph.poshshopid , poshbilldate ,ph.poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,PDCheque.PosBankAmount
union all
--CASH + PD CHEQUE -> Taking only cheque amount
SELECT
poshCompanyID As companyid,PH.poshshopid As shopid, poshbilldate As billdate,
ISNULL(poshChequeAccID,0) As accountid,
Convert(numeric(18,2), CHQ.PosBankAmount)  As amount,
Convert(numeric(18,2), CHQ.PosBankAmount * poshdepexrate)  As damount,
Convert(numeric(18,2), CHQ.PosBankAmount * poshexchangerate) As camount,
0 as cAsh,''PD CHEQUE'' As transtype, poshdepartmentid departmentid
FROM
losPosChequeDetails CHQ,LOsPosHeader PH
--, ahqPostDatedChequeDetails PdChqDet  --RefNo-2
WHERE
PH.poshBillID = CHQ.PoshBillID  AND isnull(PH.PosPostDate,0)=1
AND PH.poshShopID = CHQ.PoshShopID AND PH.poshcancelled <> 1
--and PdChqDet.PoshBillID = ph.poshBillID AND isnull(PdChqDet.Cancel,0)=0  --RefNo-2
Group By poshcompanyid , PH.poshshopid , poshbilldate ,PH.poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,poshChequeAccID,
CHQ.PosBankAmount
--RefNo-1 ends ---------------------------
UniOn All
Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,
COnvert(numeric(18,2),Sum(amount)) As amount,
COnvert(numeric(18,2),Sum(damount)) As damount,
COnvert(numeric(18,2),Sum(camount)) As camount,
1,''E'' As transtype, departmentid departmentid
From  vwPosExchangeDetails
Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid ,
sehcAshaccid,departmentid
Having Sum(amount)<0
UniOn All
Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,
COnvert(numeric(18,2),Sum(amount)) As amount,
COnvert(numeric(18,2),Sum(damount)) As damount,
COnvert(numeric(18,2),Sum(camount)) As camount,
1,''c''  As transtype, departmentid departmentid
From  vwPosExchangeDetails
Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid,
sehcAshaccid,departmentid
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(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
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,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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, 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
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, 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
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, 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
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, 2),sum(idUnitPrice)) amount,
convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) damount,
convert(numeric(18, 2),sum(idUnitPrice * ihExchangeRate)) camount,
0 ihcAshinvoice, ''d'' As transtype, ihdepartmentid departmentid
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, 2),-sum(idUnitPrice)) amount,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,
0 ihcAshinvoice, ''d'' As transtype, ihdepartmentid departmentid
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, 2),-sum(idUnitPrice)) amount,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,
0 ihcAshinvoice, ''d'' As transtype, ihdepartmentid departmentid
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,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid
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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice, ''s'' As transtype, lah.aidepartmentid  departmentid
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''GRD'' As transtype, Grnhdepartmentid  departmentid
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid 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
/****** Object:  View [dbo].[vwCAshSalesAsOn07062011]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSalesAsOn07062011]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwCAshSalesAsOn07062011] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
From  losposheader ph,losposdetail pd   Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate
UniOn All
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
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 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
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
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,
1,''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 = 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
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid
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
UniOn All
--direct invoice
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice, ''s'' As transtype, lah.aidepartmentid  departmentid
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid 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
/****** Object:  View [dbo].[vwCAshSales_woutsplinvoicecreditsale]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_woutsplinvoicecreditsale]'))
EXEC dbo.sp_executesql @statement = N'
--select sum(amount) from vwCAshSales where shopid=5
-- 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          :Benzigar
-- Comments             : Direcrt invoice is splited to handle invoice and return before despatch
--Modified By : Nidheesh P V
--Modified on : 18/11/2010
--Comments : Added F&B
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwCAshSales_woutsplinvoicecreditsale] As
--This view not considering specialinvoice for credit sale
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
From  losposheader ph,losposdetail pd   Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate
UniOn All
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
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 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
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
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,
1,''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 = 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
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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 and ihNoofOCDetails=0
Group By
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,
ihdepexrate, ihexchangerate
UniOn All
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
-COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
-COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
-COnvert(numeric(18,2),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 and ihNoofOCDetails<>0
Group By
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,
ihdepexrate, ihexchangerate
UniOn All
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid
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
--UniOn All
--direct invoice
--Select
--ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
-- COnvert(numeric(18,2),Sum(idunitprice) ) As amount,
-- COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
-- COnvert(numeric(18,2),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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice, ''s'' As transtype, lah.aidepartmentid  departmentid
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid 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
union all
-- Food and Beverages Bill -
select poshcompanyid,h.poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,poshCashAccID,
case when poshBillType=''CA'' then COnvert(numeric(18,2),(poshbillamount))
when poshBillType=''VCA'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt))end Amount,
case when poshBillType=''CA'' then COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)
when poshBillType=''VCA'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt)*poshdepexrate)end Depamount,
case when poshBillType=''CA'' then COnvert(numeric(18,2),(poshbillamount)*poshExchangeRate)
when poshBillType=''VCA'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt)*poshExchangeRate)end Comamount,
1, ''F&B'' As type,poshDepartmentid
from  losposfandbheader h
where poshCancelled=0 and poshBillType in(''CA'',''VCA'')'
GO
/****** Object:  View [dbo].[vwCAshSales_Sonee]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_Sonee]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified by      : Bijesh.B as on 22/03/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
CREATE View [dbo].[vwCAshSales_Sonee] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled
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
UNION ALL
--RefNo-1
--After PD Cheque deduction
Select poshcompanyid As companyid, ph.poshshopid As shopid, poshbilldate As billdate,
	poshcAshaccid As accountid,
	Convert(numeric(18,2),(ph.poshBillAmount - PDCheque.PosBankAmount)) as amount,
	Convert(numeric(18,2),(ph.poshBillAmount - PDCheque.PosBankAmount) * poshdepexrate)  As damount,
	Convert(numeric(18,2), (ph.poshBillAmount - PDCheque.PosBankAmount) * poshexchangerate) As camount,
	1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid, 0 as PdChqCancelled
	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
	
UniOn All
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
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 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
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
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,
1,''c'' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled
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
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid ,0 as PdChqCancelled
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid  ,0 as PdChqCancelled
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 ,0 as PdChqCancelled
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
UniOn All
--direct invoice
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice,
''s'' As transtype, lah.aidepartmentid  departmentid ,0 as PdChqCancelled
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid   ,0 as PdChqCancelled
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid ,0 as PdChqCancelled
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid  ,0 as PdChqCancelled
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid  ,0 as PdChqCancelled
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid  ,0 as PdChqCancelled
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid ,0 as PdChqCancelled
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid  ,0 as PdChqCancelled
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid,0 as PdChqCancelled
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid  ,0 as PdChqCancelled
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid ,0 as PdChqCancelled
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
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,2), Sum(CHQ.PosBankAmount))  As amount,
Convert(numeric(18,2), Sum(CHQ.PosBankAmount) * poshdepexrate)  As damount,
Convert(numeric(18,2), Sum(CHQ.PosBankAmount) * poshexchangerate) As camount,
0,''PD CHEQUE'' As transtype, poshdepartmentid departmentid,0 as PdChqCancelled
FROM
	losPosChequeDetails CHQ,LOsPosHeader PH, ahqPostDatedChequeDetails PdChqDet
WHERE
	PH.poshBillID = CHQ.PoshBillID 	AND isnull(PH.PosPostDate,0)=1
	AND PH.poshShopID = CHQ.PoshShopID
	and PdChqDet.PoshBillID = ph.poshBillID
	AND isnull(PdChqDet.Cancel,0)=0
Group By poshcompanyid , PH.poshshopid , poshbilldate ,PH.poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,poshChequeAccID'
GO
/****** Object:  View [dbo].[vwCAshSales_BackUp_22032011]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales_BackUp_22032011]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwCAshSales_BackUp_22032011] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid
From  losposheader ph,losposdetail pd   Where
ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0
Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,
poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate
UniOn All
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
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 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
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
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,
1,''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 = 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
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid
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
UniOn All
--direct invoice
Select
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
COnvert(numeric(18,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice, ''s'' As transtype, lah.aidepartmentid  departmentid
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
0, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,
1, ''RBI'' type , abh.abhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid 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
/****** Object:  View [dbo].[vwCAshSales]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCAshSales]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
------------------------------------------------------------------------------------------
CREATE View [dbo].[vwCAshSales] As
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled
,ISNULL(poshUserId,0) as UserID
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
--After PD Cheque deduction
Select poshcompanyid As companyid, ph.poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid,
--Convert(numeric(18,2),(ph.poshBillAmount - PDCheque.PosBankAmount)) as amount,
--Convert(numeric(18,2),(ph.poshBillAmount - PDCheque.PosBankAmount) * poshdepexrate)  As damount,
--Convert(numeric(18,2), (ph.poshBillAmount - PDCheque.PosBankAmount) * poshexchangerate) As camount,
convert(numeric(18,2),sum(posdunitprice)-pdCheque.PosBankAmount) amount,
convert(numeric(18,2),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) damount,
convert(numeric(18,2),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) camount,
1 As cAsh, ''p'' As transtype, poshdepartmentid departmentid, 0 as PdChqCancelled
,ISNULL(poshUserId,0) as UserID
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,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
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,2),Sum( vw.idunitprice ))  As amount,
COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
COnvert(numeric(18,2),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,2),Sum(idunitprice) ) As amount,
COnvert(numeric(18,2),Sum(idunitprice) * ihdepexrate) As damount,
COnvert(numeric(18,2),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, 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
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, 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
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, 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
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, 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
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, 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
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, 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
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,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
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,
1,''c'' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled
,ISNULL(ihuserid,0) as UserID
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,2),(vws.siamount )) As amount,
COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,
lah.aicAshinvoice , ''s'' As transtype, aidepartmentid departmentid ,0 as PdChqCancelled
,ISNULL(vws.UserID,0) as UserID
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
UniOn All
--hq serivce invoice dOne for shop
Select
ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,
COnvert(numeric(18,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) *depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) *exchangerate),
1 ,''hs'', ai.departmentid  departmentid  ,0 as PdChqCancelled
,ISNULL(ser.UserID,0) as UserID
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
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 ,0 as PdChqCancelled
,ISNULL(ihuserid,0) as UserID
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)
UniOn All
--serviceinvoice
Select
vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,
COnvert(numeric(18,2),vws.siamount) As amount,
COnvert(numeric(18,2),vws.siamount * aidepexrate) As damount,
COnvert(numeric(18,2),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice,
''s'' As transtype, lah.aidepartmentid  departmentid ,0 as PdChqCancelled
,ISNULL(vws.UserID,0) as UserID
From
vwshopservicesales 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,2),Sum(serviceqty * amount) ),
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate),
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate),
0 ,''hs'',ai.departmentid  departmentid   ,0 as PdChqCancelled
,ISNULL(ser.UserID,0) as UserID
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,2), serbookadvanceamount) ,
COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
serbookhdepartmentid ,0 as PdChqCancelled
,ISNULL(serbookhUserid,0) as UserID
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,2), serinvhamount) ,
COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
serinvhdepartmentid  ,0 as PdChqCancelled
,ISNULL(serinvhuserid,0) as UserID
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,2), serinvhamount), COnvert(numeric(18,2),
serinvhamount*seinvhdepexrate),
COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate), 0 , ''sbi'',
serinvhdepartmentid  ,0 as PdChqCancelled
,ISNULL(serinvhuserid,0) as UserID
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,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), 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
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,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,
COnvert(numeric(18,2), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,
COnvert(numeric(18,2), 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
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
0, ''UTB'' type , tbh.tbhdepartmentid departmentid  ,0 as PdChqCancelled
,ISNULL(tbhUserID,0) as UserID
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,2), Isnull(tbh.tbhAmount,0)) Amount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,
COnvert(numeric(18,2), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,
1, ''UTB'' type , tbh.tbhdepartmentid departmentid,0 as PdChqCancelled
,ISNULL(tbhUserID,0) as UserID
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,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid  ,0 as PdChqCancelled
,ISNULL(grnUserID,0) as UserID
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,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid ,0 as PdChqCancelled
,ISNULL(losDCNUserID,0) as UserID
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,2), CHQ.PosBankAmount)  As amount,
Convert(numeric(18,2), CHQ.PosBankAmount * poshdepexrate)  As damount,
Convert(numeric(18,2), 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,2), Sum( fb_pd_reusedqty*fb_pd_Rate  ))  As amount,
COnvert(numeric(18,2), Sum( fb_pd_reusedqty*fb_pd_Rate ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), 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
/****** Object:  View [dbo].[vwcashreceipt]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashreceipt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcashreceipt    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwcashreceipt    Script Date: 14/09/2002 12:48:08 AM ******/
/****** Object:  View dbo.vwcashreceipt    Script Date: 31/07/2002 2:00:29 PM ******/
/****** Object:  View dbo.vwcashreceipt    Script Date: 20/11/2001 9:58:59 AM ******/
/****** Object:  View dbo.vwcashreceipt    Script Date: 17/11/2001 9:21:28 PM ******/
CREATE view [dbo].[vwcashreceipt] as
select rh.companyid, rh.receiptid,rh.receiptno, rh.receiptdate, rh.ReceivedFrom, acc.accountdesc,
cur.symbol, rh.ChequeDetails, rh.cbreferenceno, rh.remarks, rh.receipttype,
case when (rd.receiptid is not null) then sum(rd.amountreceived)
when (rcd.receiptid is not null) then sum(rcd.amount)
else rh.amount end as amt
from
receiptvoucherheader rh
left outer join receiptvoucherdetails rd on rh.companyid = rd.companyid and
rh.receiptid = rd.receiptid
left outer join receiptvouchercreditdetails rcd on rh.companyid = rcd.companyid and rh.receiptid =
rcd.receiptid ,aaccountmaster acc, acurrencymaster cur
where rh.companyid = acc.companyid and rh.bankcashaccountid = acc.accountid
and acc.companyid = cur.companyid and acc.currencyid = cur.currencyid
group by rh.companyid, rh.receiptid,rh.receiptno, rh.receiptdate, rh.ReceivedFrom, acc.accountdesc,
cur.symbol, rh.ChequeDetails, rh.cbreferenceno, rh.remarks, rh.receipttype,rcd.receiptid,
rd.receiptid, rh.amount'
GO
/****** Object:  View [dbo].[vwCollectionCategoryWise]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectionCategoryWise]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by  : Hariharan
-- Modified on  : 08/05/2004
-- Comments     : Added SalesQty column
--  : Avoided unitprice * qty and given amount columns from vwshopitemshipmentdetail
--------------------------------------------------------------------------------
CREATE view [dbo].[vwCollectionCategoryWise]  AS
select ShopName, poshShopId, poshBillDate,ic.CategoryNameDescription ,
sum(Amount) SalesValue, sum(cAmount) cSalesValue, sum(dAmount) dSalesValue,
sum(posdquantity) SalesQty ,ic.itemcategoryid  from vwshopitemsales vs, aitem a, aitemcategory ic,
ashops s where vs.posditemid=a.itemid and a.itemcategoryid= ic.itemcategoryid
and poshshopid = s.shopid group by poshbilldate, poshshopid, shopname,
ic.categorynamedescription ,ic.itemcategoryid'
GO
/****** Object:  View [dbo].[vwcollectionbrandwisegraph]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcollectionbrandwisegraph]'))
EXEC dbo.sp_executesql @statement = N'
--created by :- hariharan
--created date :- 08/05/2004
--Modified by : - VinothMurugan V.
--Modified date : - 15/5/2010
CREATE view [dbo].[vwcollectionbrandwisegraph]  as
select shopname, poshshopid, poshbilldate, brand ,
sum(Amount) salesvalue,a.ItemCategoryID,at.CategoryNameDescription from vwshopitemsales vs,
(select case brand when '''' then ''Others'' else brand end brand, itemid,ItemCategoryID from aitem)  a,
aItemCategory at,
ashops s where vs.posditemid=a.itemid and poshshopid = s.shopid  and a.ItemCategoryID = at.ItemCategoryID group by poshbilldate,
poshshopid, shopname, a.brand,a.ItemCategoryID, at.CategoryNameDescription'
GO
/****** Object:  View [dbo].[vwCollectionBrandWise]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectionBrandWise]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on		: 08/05/2004
-- Modified by		: Hariharan
-- Comments		: Added SalesQty column
---------------------------------------------------
CREATE VIEW [dbo].[vwCollectionBrandWise]  AS
select ShopName, poshShopId, poshBillDate, Brand ,
sum(Amount) SalesValue, sum(dAmount) dSalesValue,sum(cAmount) cSalesValue,
sum(posdquantity) SalesQty from vwshopitemsales vs,
(select case brand when '''' then ''Others'' else brand end brand, itemid from aitem)  a,
ashops s where vs.posditemid=a.itemid and poshshopid = s.shopid
group by poshbilldate, poshshopid, shopname, a.brand'
GO
/****** Object:  View [dbo].[vwCollectedSalesTax]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCollectedSalesTax]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------
-- 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
/****** Object:  View [dbo].[vwcashtallied]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashtallied]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED BY	: HARIHARAN
--MODIIFED DATE : 10/01/2004
--COMMENTS	: Special invoice data taken if confirmed only
CREATE view [dbo].[vwcashtallied] as
select poshcompanyid as companyid, poshshopid as shopid, poshbilldate as billdate,
poshcashaccid as accountid, poshbillamount as Addamount, 0 as DedAmount, 1 as cash from
losposheader where poshcancelled=0
union all
select sehcompanyid, sehshopid, sehexchangedate, sehcashaccid, sehexchangebillamount
- sehbillamount, 0 as DedAmount, 1  from losposexchangeheader where sehcancelled=0
union all
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid, ihinvoiceamount, 0 as DedAmount,
ihCashInvoice from losinvoiceheader where ihcancelled=0 and ihproforma=0
union all
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid, ihinvoiceamount, 0 as DedAmount,
IhCashInvoice from losspecialinvoiceheader where ihcancelled=0 and ihproforma=0
and ihTransfinished = 1
union all
select vws.sicompanyid, vws.sishopid, vws.siinvoicedate, lah.aibankcashid, vws.siamount,
0 as DedAmount, lah.aicashinvoice from vwshopservicesales vws , LOsAccountsInvoiceHeader lah
where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and aishopid = sishopid
union all
select phCompanyid as companyid ,phshopid as shopid , phpaymentdate as billdate,
phbankcashid as accountid, 0 as AddQty, phamount as DedAmount, 1 as cash from
lospaymentvoucherheader where phcancelled=0
union all
select rhCompanyid as companyid ,rhshopid as shopid , rhreceiptdate as billdate,
rhbankcashaccountid as accountid, rhamount as amount, 0 as DedAmount, 1 as cash from
losreceiptvoucherheader where rhcancelled=0'
GO
/****** Object:  StoredProcedure [dbo].[spAssetDetails]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAssetDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----disphexrate * dispdamount else
-- created by  : venki 040403
-- modified by Venkitesh on 080403 For giving company currency
-- modified by Venkitesh on 130403 For accc id correction
CREATE  proc [dbo].[spAssetDetails] (@intcompanyid as int,
	 			 @intDeptid as int,
				 @Todate as varchar(8),
				 @intCmpCur as int )
as
begin
	set nocount on
	declare
		@intfinancialid as int,
		@lastyearfinancialid as int		
	
	   Create table #Temp(
			CompanyID int,
			TransDeptid int,
			FixedAssetid int,
			AssetAccid int,
			TransAmt numeric(18,2),
			Type varchar(3),
			TransType  varchar(3))
		
Begin
			-- from dep id and reducing cost value
			--asset  value For open asset
			select @intfinancialid=financialid from vwfinyearperiod where
			year(sdate)=left(@todate,4)
			
			select top 1 @lastyearfinancialid= financialid from vwfinyearperiod
			where edate<@todate order by financialid desc
-- opening Taking from openings sp
			insert into #temp
			exec spFixedAssetopeningBalance 1,@lastyearfinancialid,@intCmpCur
-- Fixed Asset Details Inserting
			insert into #Temp --Inertng asset and depreciation opending  details
			
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then costprice* exrate
			else  costprice end Costprice ,''A'',''C'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			insert into #temp  --Depreciation value For purchased or gdn transfer asset	
			select CompanyID,DEPARTMENTID, fixedassetid,FixedAssetAccID,case when @intCmpCur=1 then initialDepreciatedValue* exrate
			else  initialDepreciatedValue end initialDepreciatedValue,''A'',''D'' from fixedasset
			where (billsrefid is not null or godownrefid is not null) and fixedassetdate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and fixedassetdate< =@Todate
			and Cancelled=0
			
--depreciation 	
			insert into #temp
			select a.companyid,DepartmentID,FixedAssetID,assetAccountID,
			case when @intCmpCur=1 then consexrate* DepreciationAmount
			else  DepreciationAmount end DepreciationAmount ,''A'',''D''
			from depreciationheader a,depreciationdetail b
			where  	a.DepreciationID=b.DepreciationID and a.CompanyID=b.companyid
			and Cancelled=0  and DepreciationDate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and DepreciationDate <=@Todate
			
			/*insert into #temp --depreciation Additionals
				
			select a.companyid,DepartmentID,FixedAssetID,assetAccountID,-DepreciationAmount ,''A'',''D''from depreciationheader a,depreciationdetail b
			where  	a.DepreciationID=b.DepreciationID and a.CompanyID=b.companyid
			and Cancelled=0  and DepreciationDate >=
			(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and DepreciationDate =@Todate*/
--Asset Transfer
			-- Department transfer
			insert into #Temp --Inertng asset transfer details
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then consexrate*-asttransvalue else  -asttransvalue*fromdepexrate end  assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* asttransvalue else asttransvalue*todepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* -astDeprValue else  -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate<=@Todate
			insert into #temp
			-- to dep id and addinng cost value
			Select asttranscompanyid,asttranstodepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*todepexrate end  assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is not null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
				insert into #temp
			-- from acc dep id and redcuing cost value(accounts)
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate * -asttransvalue else -asttransvalue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			-- To acc dep id and depreciation reducing cost value
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccID,case when @intCmpCur=1 then  consexrate* asttransValue else  asttransValue*fromdepexrate end assetvalue,''T'',''C''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0 and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			
		
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,FromAssetAccId,case when @intCmpCur=1 then  consexrate*-astDeprValue else -astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate
			insert into #temp
			Select asttranscompanyid,asttransfromdepid,asttransassetid,ToAssetAccId,case when @intCmpCur=1 then  consexrate* astDeprValue else astDeprValue*fromdepexrate end assetvalue,''T'',''D''
			from assettransfer where asttranstodepid is  null and
			asttranscancelled =0  and asttransdate>= (select sdate from  vwfinyearperiod where financialid=@intfinancialid)
			and asttransdate< =@Todate	
--disposal
			
			insert into #temp ---disposal case cost
			
			select disphcompanyid,disphdepartmentid,dispdasstid,
			case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end
			dispdaccid, case when @intCmpCur=1 then  -disphexrate * dispdamount else  -dispdamount end dispdamount ,''D'',''C'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate
			
			insert into #temp --disposal case depreciation			
			
			select disphcompanyid,disphdepartmentid, dispdasstid,
			case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end dispdaccid,case when @intCmpCur=1 then disphexrate * disdepeBalamt else disdepeBalamt end disdepeBalamt,''D'',''D'' from
			assetdisposalheader a,assetdisposaldetail b,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and a.disphid=b.dispid and fixedassetid= dispdasstid and companyid= disphcompanyid and
			disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate	
			
			insert into #temp --disposal case depreciation			
			select disphcompanyid,disphdepartmentid,dispdasstid,
			case when c.lasttoaccid  is null then c.FixedAssetAccID
			else c.lasttoaccid end dispdaccid,case when @intCmpCur=1 then  disphexrate * DisAstSaleValue else DisAstSaleValue end DisAstSaleValue,''D'',''S'' from
			assetdisposalheader a,assetdisposaldetail,fixedasset c
			where disphcompanyid=dispdcompanyid and disphcancelled=0
			and fixedassetid= dispdasstid and companyid= disphcompanyid
			and a.disphid=dispid
			and disphdate>=(select sdate from  vwfinyearperiod where financialid=@intfinancialid	)and disphdate <=@Todate
	
if @intDeptid>0
	select max(a.CompanyID)companyid,max(b.FixedAssetDate)AssetDate,max(b.PurchaseDate)PurchaseDate,max(b.Location)Location,
	max(b.assetcode)Assetcode,a.TransDeptid,
	a.FixedAssetid,max(b.assetname)Assetname,max(a.AssetAccid)Accountid,max(c.AccountDesc)AccountDesc,
	case when type=''O'' and transtype =''C'' then   sum(a.TransAmt)
	else 0 end  opening,
	case when type = ''A'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end AssetAddition,
	case when type = ''T'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end AssetTransfer,
	case when type = ''D'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end Assetdisposal,
	case when type=''O'' and transtype =''D'' then   sum(a.TransAmt)
	else 0 end  Depropening,
	case when type = ''A'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end DeprAddition,
	case when type = ''T'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end deprTransfer,
	case when type = ''D'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end Deprdisposal,max(a.Type)type,max(a.TransType)TransType,
	case when type = ''D'' and  transtype =''S'' then sum(a.TransAmt)
	else 0 end salevalue,max(a.Type)type,max(a.TransType)TransType,
	case when (billsrefid = null and writeoffrefid = Null )  then ''''
	     when billsrefid = null then max(loi.whno)
	     else max(BillsNo) end RefNo
	  from #temp a,
	aaccountmaster c,fixedasset b
	left outer join
		bills  bil on b.billsrefid=bil.BillsID and
		b.DepartmentID = bil.departmentid
		and b.CompanyID =bil.CompanyID
	left outer join loiwriteoffheader loi
		on loi.whGodownID = b.godownrefid and
		   loi.whID =b.writeoffrefid
	left outer join assetdisposaldetail disp
		on disp.dispdasstid = b.fixedassetid
		   and disp.dispdcompanyid=b.companyid
		
	where a.companyid=b.companyid and a.FixedAssetID=b.FixedAssetID
	and a.companyid=c.companyid and a.AssetAccid=c.AccountID
	and a.TransDeptid=@intdeptid
	group by a.FixedAssetid,a.TransDeptid,a.Type,a.TransType,billsrefid, writeoffrefid
else
	select max(a.CompanyID)companyid,max(b.FixedAssetDate)AssetDate,max(b.PurchaseDate)PurchaseDate,max(b.Location)Location,
	max(b.assetcode)Assetcode,a.TransDeptid,
	a.FixedAssetid,max(b.assetname)Assetname,max(a.AssetAccid)Accountid,max(c.AccountDesc)AccountDesc,
	case when type=''O'' and transtype =''C'' then   sum(a.TransAmt)
	else 0 end  opening,
	case when type = ''A'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end AssetAddition,
	case when type = ''T'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end AssetTransfer,
	case when type = ''D'' and  transtype =''C'' then sum(a.TransAmt)
	else 0 end Assetdisposal,
	case when type=''O'' and transtype =''D'' then   sum(a.TransAmt)
	else 0 end  Depropening,
	case when type = ''A'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end DeprAddition,
	case when type = ''T'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end deprTransfer,
	case when type = ''D'' and  transtype =''D'' then sum(a.TransAmt)
	else 0 end Deprdisposal ,max(a.Type)type,max(a.TransType)TransType,
	case when type = ''D'' and  transtype =''S'' then sum(a.TransAmt)
	else 0 end salevalue,
	case when (billsrefid = null and writeoffrefid = Null )  then ''''
	     when billsrefid = null then max(loi.whno)
else max(BillsNo) end RefNo
	  from #temp a,
	aaccountmaster c,fixedasset b
	left outer join
		bills  bil on b.billsrefid=bil.BillsID and
		b.DepartmentID = bil.departmentid
		and b.CompanyID =bil.CompanyID
	left outer join loiwriteoffheader loi
		on loi.whGodownID = b.godownrefid and
		   loi.whID =b.writeoffrefid
	where a.companyid=b.companyid and a.FixedAssetID=b.FixedAssetID
	and a.companyid=c.companyid and a.AssetAccid=c.AccountID
	
group by a.FixedAssetid,a.TransDeptid,a.Type,a.TransType,billsrefid, writeoffrefid
--select FixedAssetid,Type,Transtype,sum(transamt) from #temp group by FixedAssetid,Type,Transtype
end
			
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAdvancePaymentsNotSettled]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAdvancePaymentsNotSettled]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on : 16/06/2007
--Created by  : Shinu
--Purpose : For Getting Unsettled Paymnets
--Modified by  :
--modified Date :
--Comments :
--spAdvancePaymentsNotSettled  1,21,0,''20061231''
CREATE proc [dbo].[spAdvancePaymentsNotSettled] @intcompanyid as int, @intdepartmentid as int,
@intVendorid as int, @strasondate as varchar(8) as
begin
set nocount on
create table #temp1  (
Paymentid  int   null,
Paymentno  varchar(100)  null,
Paymentdate datetime null,
Vendorid  int   null,
VendorName varchar(100) null,
Paymentamt  numeric(18,2)  null,
settledamt numeric(18,2) null
)
if @intdepartmentid<>0
Begin
if @intVendorid = 0
begin
insert into #temp1
select h.phPaymentid, h.phPaymentno, h.phPaymentdate, h.phVendorid,cm.Vendorname, h.phcustomeramount, 0.0  from ahqpaymentvoucherheader h
left outer join ahqpaymentvoucherDetails d on
h.phcompanyid = d.pdcompanyid and h.phPaymentid = d.pdPaymentid
left outer join aVendormaster cm on
h.phvendorid=cm.Vendorid
left outer join ahqpaymentvoucherDebitDetails d1 on
h.phcompanyid = d1.pddcompanyid and
h.phPaymentid = d1.pddPaymentid
where h.phcompanyid =@intcompanyid and h.phdepartmentid = @intdepartmentid and
isnull(h.phvendorid,0) <> 0 and h.phcancelled =0 and d1.pddpaymentid is null
and h.phpaymentDate <= @strasondate
group by h.phPaymentid, h.phPaymentno, h.phPaymentdate,
h.phvendorid,cm.vendorname, h.phcustomeramount  having
count(d.pdPaymentid) =0
union all
select h.phPaymentid, h.phpaymentno, h.phpaymentdate, d.pvdvendorid,cm.vendorname,d.pvdVendorAmount, 0.0  from ahqpaymentvoucherheader h ,
ahqpaymentvouchervendorDetails d
left outer join aVendormaster cm on
d.pvdVendorid=cm.Vendorid
where h.phcompanyid = d.pvdcompanyid and
h.phPaymentid = d.pvdPaymentid and  h.phcompanyid=@intcompanyid
and h.phdepartmentid =@intdepartmentid and h.phcancelled =0
and h.phPaymentDate <= @strasondate
end
else
begin
insert into #temp1
select h.phPaymentid, h.phPaymentno, h.phPaymentdate, h.phVendorid,cm.Vendorname, h.phcustomeramount, 0.0  from ahqpaymentvoucherheader h
left outer join ahqpaymentvoucherDetails d on
h.phcompanyid = d.pdcompanyid and h.phPaymentid = d.pdPaymentid
left outer join aVendormaster cm on
h.phvendorid=cm.Vendorid
left outer join ahqpaymentvoucherDebitDetails d1 on
h.phcompanyid = d1.pddcompanyid and
h.phPaymentid = d1.pddPaymentid
where h.phcompanyid =@intcompanyid and h.phdepartmentid = @intdepartmentid and
isnull(h.phvendorid,0) <> 0 and h.phcancelled =0 and d1.pddpaymentid is null
and h.phpaymentDate <= @strasondate and  h.phvendorid = @intVendorid
group by h.phPaymentid, h.phPaymentno, h.phPaymentdate,
h.phvendorid,cm.vendorname, h.phcustomeramount  having
count(d.pdPaymentid) =0
union all
select h.phPaymentid, h.phpaymentno, h.phpaymentdate, d.pvdvendorid,cm.vendorname,d.pvdvendorAmount, 0.0  from ahqpaymentvoucherheader h ,
ahqpaymentvouchervendorDetails d
left outer join aVendormaster cm on
d.pvdVendorid=cm.Vendorid
where h.phcompanyid = d.pvdcompanyid and
h.phPaymentid = d.pvdPaymentid and  h.phcompanyid=@intcompanyid
and h.phdepartmentid =@intdepartmentid and h.phcancelled =0
and h.phPaymentDate <= @strasondate  and  h.phvendorid = @intVendorid
end
update #temp1 set settledamt = settled from (
select vsh.Paymentid rid, vsh.Vendorid cid, cm.Vendorname,
sum(isnull(SettlementAmount,0.0)) settled from
VendorsettlementDetail vsd,Vendorsettlementheader vsh
left outer join aVendorMaster cm on
vsh.Vendorid=cm.Vendorid
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid
and vsh.cancelled =0 and vsh.companyid = @intcompanyid and vsh.departmentid =
@intdepartmentid and isnull(vsh.Paymentid,0) <> 0
group by vsh.companyid, vsh.Paymentid, vsh.vendorid,cm.Vendorname ) a where
#temp1.Paymentid = a.rid and #temp1.Vendorid = a.cid
End
else
Begin
if @intVendorid = 0
begin
insert into #temp1
select h.phPaymentid, h.phPaymentno, h.phPaymentdate, h.phVendorid,cm.Vendorname, h.phcustomeramount, 0.0  from ahqpaymentvoucherheader h
left outer join ahqpaymentvoucherDetails d on
h.phcompanyid = d.pdcompanyid and h.phPaymentid = d.pdPaymentid
left outer join aVendormaster cm on
h.phvendorid=cm.Vendorid
left outer join ahqpaymentvoucherDebitDetails d1 on
h.phcompanyid = d1.pddcompanyid and
h.phPaymentid = d1.pddPaymentid
where h.phcompanyid =@intcompanyid  and
isnull(h.phvendorid,0) <> 0 and h.phcancelled =0 and d1.pddpaymentid is null
and h.phpaymentDate <= @strasondate
group by h.phPaymentid, h.phPaymentno, h.phPaymentdate,
h.phvendorid,cm.vendorname, h.phcustomeramount  having
count(d.pdPaymentid) =0
union all
select h.phPaymentid, h.phpaymentno, h.phpaymentdate, d.pvdvendorid,cm.vendorname,d.pvdVendorAmount, 0.0  from ahqpaymentvoucherheader h ,
ahqpaymentvouchervendorDetails d
left outer join aVendormaster cm on
d.pvdVendorid=cm.Vendorid
where h.phcompanyid = d.pvdcompanyid and
h.phPaymentid = d.pvdPaymentid and  h.phcompanyid=@intcompanyid
and h.phcancelled =0
and h.phPaymentDate <= @strasondate
end
else
begin
insert into #temp1
select h.phPaymentid, h.phPaymentno, h.phPaymentdate, h.phVendorid,cm.Vendorname, h.phcustomeramount, 0.0  from ahqpaymentvoucherheader h
left outer join ahqpaymentvoucherDetails d on
h.phcompanyid = d.pdcompanyid and h.phPaymentid = d.pdPaymentid
left outer join aVendormaster cm on
h.phvendorid=cm.Vendorid
left outer join ahqpaymentvoucherDebitDetails d1 on
h.phcompanyid = d1.pddcompanyid and
h.phPaymentid = d1.pddPaymentid
where h.phcompanyid =@intcompanyid and
isnull(h.phvendorid,0) <> 0 and h.phcancelled =0 and d1.pddpaymentid is null
and h.phpaymentDate <= @strasondate and  h.phvendorid = @intVendorid
group by h.phPaymentid, h.phPaymentno, h.phPaymentdate,
h.phvendorid,cm.vendorname, h.phcustomeramount  having
count(d.pdPaymentid) =0
union all
select h.phPaymentid, h.phpaymentno, h.phpaymentdate, d.pvdvendorid,cm.vendorname,d.pvdvendorAmount, 0.0  from ahqpaymentvoucherheader h ,
ahqpaymentvouchervendorDetails d
left outer join aVendormaster cm on
d.pvdVendorid=cm.Vendorid
where h.phcompanyid = d.pvdcompanyid and
h.phPaymentid = d.pvdPaymentid and  h.phcompanyid=@intcompanyid
and h.phcancelled =0
and h.phPaymentDate <= @strasondate  and  h.phvendorid = @intVendorid
end
update #temp1 set settledamt = settled from (
select vsh.Paymentid rid, vsh.Vendorid cid, cm.Vendorname,
sum(isnull(SettlementAmount,0.0)) settled from
VendorsettlementDetail vsd,Vendorsettlementheader vsh
left outer join aVendorMaster cm on
vsh.Vendorid=cm.Vendorid
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid
and vsh.cancelled =0 and vsh.companyid = @intcompanyid and isnull(vsh.Paymentid,0) <> 0
group by vsh.companyid, vsh.Paymentid, vsh.vendorid,cm.Vendorname ) a where
#temp1.Paymentid = a.rid and #temp1.Vendorid = a.cid
End
select * from #temp1 where paymentamt <> settledamt   order by paymentid
drop table #temp1
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAnalysisofItemSalesByWeekGSTSeparately]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAnalysisofItemSalesByWeekGSTSeparately]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spAnalysisofItemSalesByWeek]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spAnalysisofItemSalesByWeek]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- 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
-------------------------------------
create proc [dbo].[spAnalysisofItemSalesByWeek]
@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
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.vwShopItemSales 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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spGetPurchaseRequestStatus]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetPurchaseRequestStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
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 [dbo].[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' 
END
GO
/****** Object:  View [dbo].[vwSalesAnalysisByItem]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByItem]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on 		: 12/12/02
-- Modified by		: leo
-- Comments		: v3
-----------------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 11/06/2003
-- Comments		: Given cost of sales with out taking average
--                        Removed the condition of having sum(vs.posdquantity) > 0
--                        to show return items also (On comparison with v2)
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-- Modified by          : venki
-- Modified on          : 11/07/2003
-- Comments		: Given the amount and camount and dmount from the view
--			  vwshopitemsales	
--                        to show return items also (On comparison with v2)
CREATE VIEW [dbo].[vwSalesAnalysisByItem]  AS
select posdItemId, i.ItemCode, avg(posdunitprice) UnitPrice, avg(dunitprice) dUnitPrice,
avg(cunitprice) cUnitPrice, sum(posdquantity) Quantity , poshBillDate,  poshShopId,
avg(vs.costprice) AvgCost, avg(vs.dcostprice) AvgDCost,  avg(vs.cCostprice) AvgCCost,
sum(posdquantity * vs.costprice) as CostOfSales,
sum(posdquantity * vs.dcostprice) as dCostOfSales,
sum(posdquantity * vs.ccostprice) as cCostOfSales,
--sum(posdquantity * posdunitprice) SalesValue,
--sum(posdquantity * dunitprice) dSalesValue,
--sum(posdquantity * cunitprice) cSalesValue,
sum(amount) salesvalue,
sum(damount) dsalesvalue,
sum(damount) csalesvalue,
vi.ItemDescription,
ic.ItemCategoryId, CategoryNameDescription,
isnull(colorname,'''') ColorName,
isnull(sizename,'''') SizeName, i.ItemDescription ItemDesc
from vwshopitemsales vs,
aitemcategory ic, vwitemdescription vi,
aitem i left outer join acolor c
on i.colorid= c.colorid left outer join asize z on i.sizeid=z.sizeid
where vs.posditemid = i.itemid
and vs.posditemid = vi.itemid
and i.itemcategoryid = ic.itemcategoryid
group by poshshopid, poshbilldate, posditemid, vi.itemdescription, ic.itemcategoryid,
categorynamedescription, colorname, sizename ,i.itemcode,i.itemdescription, Type'
GO
/****** Object:  View [dbo].[vwRequestremark]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestremark]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[vwRequestremark]
AS
SELECT     dbo.MEiDespatchToShopHeader.dhShopReqid, dbo.vwGoodsRequestToHq.GRHremarks, dbo.MEiDespatchToShopHeader.dhshopreqno,
dbo.vwGoodsRequestToHq.GRHrequestNO
FROM         dbo.vwGoodsRequestToHq INNER JOIN
dbo.MEiDespatchToShopHeader ON dbo.vwGoodsRequestToHq.GRHrequestNO = dbo.MEiDespatchToShopHeader.dhshopreqno'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'vwRequestremark', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties =
Begin PaneConfigurations =
Begin PaneConfiguration = 0
NumPanes = 4
Configuration = "(H (1[46] 4[12] 2[25] 3) )"
End
Begin PaneConfiguration = 1
NumPanes = 3
Configuration = "(H (1 [50] 4 [25] 3))"
End
Begin PaneConfiguration = 2
NumPanes = 3
Configuration = "(H (1 [50] 2 [25] 3))"
End
Begin PaneConfiguration = 3
NumPanes = 3
Configuration = "(H (4 [30] 2 [40] 3))"
End
Begin PaneConfiguration = 4
NumPanes = 2
Configuration = "(H (1 [56] 3))"
End
Begin PaneConfiguration = 5
NumPanes = 2
Configuration = "(H (2 [66] 3))"
End
Begin PaneConfiguration = 6
NumPanes = 2
Configuration = "(H (4 [50] 3))"
End
Begin PaneConfiguration = 7
NumPanes = 1
Configuration = "(V (3))"
End
Begin PaneConfiguration = 8
NumPanes = 3
Configuration = "(H (1[56] 4[18] 2) )"
End
Begin PaneConfiguration = 9
NumPanes = 2
Configuration = "(H (1 [75] 4))"
End
Begin PaneConfiguration = 10
NumPanes = 2
Configuration = "(H (1[66] 2) )"
End
Begin PaneConfiguration = 11
NumPanes = 2
Configuration = "(H (4 [60] 2))"
End
Begin PaneConfiguration = 12
NumPanes = 1
Configuration = "(H (1) )"
End
Begin PaneConfiguration = 13
NumPanes = 1
Configuration = "(V (4))"
End
Begin PaneConfiguration = 14
NumPanes = 1
Configuration = "(V (2))"
End
ActivePaneConfig = 0
End
Begin DiagramPane =
Begin Origin =
Top = 0
Left = 0
End
Begin Tables =
Begin Table = "vwGoodsRequestToHq"
Begin Extent =
Top = 6
Left = 38
Bottom = 253
Right = 209
End
DisplayFlags = 280
TopColumn = 0
End
Begin Table = "MEiDespatchToShopHeader"
Begin Extent =
Top = 0
Left = 299
Bottom = 246
Right = 775
End
DisplayFlags = 280
TopColumn = 15
End
End
End
Begin SQLPane =
End
Begin DataPane =
Begin ParameterDefaults = ""
End
Begin ColumnWidths = 9
Width = 284
Width = 1500
Width = 1500
Width = 1500
Width = 1500
Width = 1500
Width = 1500
Width = 1500
Width = 1500
End
End
Begin CriteriaPane =
Begin ColumnWidths = 11
Column = 1440
Alias = 900
Table = 1170
Output = 720
Append = 1400
NewValue = 1170
SortType = 1350
SortOrder = 1410
GroupBy = 1350
Filter = 1350
Or = 1350
Or = 1350
Or = 1350
End
End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vwRequestremark'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'vwRequestremark', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vwRequestremark'
GO
/****** Object:  View [dbo].[vwServiceInvoice]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceInvoice]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------
----Created By         : Shinu
----Created On         : 05-02-2008
----Created For        : To get All Shop Service Invoices
------------------------------------------------------------------------------------------------------------------
----Modified By        :
----Modified On        :
----Purpose            :
------------------------------------------------------------------------------------------------------------------
CREATE VIEW  [dbo].[vwServiceInvoice] as
select
vws.sicompanyid ihcompanyid , vws.sishopid ihshopid, lah.aicustomerid ihcustomerid,
vws.siinvoicedate ihinvoicedate, vws.aiinvoiceno ihinvoiceno,
lah.aibankcashid , convert(numeric(18,2),vws.siamount )Amount,
convert(numeric(18,2),vws.siamount * aidepexrate)DAmount,
convert(numeric(18,2),vws.siamount * aiexchangerate)cAmount,  lah.aicashinvoice ihcashinvoice  ,
convert(numeric(18,2),vws.Settledamount) Settledamount, aidepartmentid departmentid
from
vwshopservicesales vws , LOsAccountsInvoiceHeader lah
where
aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and
aishopid = sishopid and aicashinvoice = 0'
GO
/****** Object:  View [dbo].[vwshopvendordebitnotes]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopvendordebitnotes]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopvendordebitnotes    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
--created on  : 30/07/2002
--created by  : leo
----------------------------------------------------------------------------------------------------------
--Ref.No:1
-- Modified By : AADYAKUMAR D V
-- Modified On : 16/02/2012
-- Comment     : Added losDCNDate
----------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwshopvendordebitnotes] as
select dcn.losdcncompanyid, dcn.losdcnshopid, dcn.losdcnid, dcn.losdcnno, dcn.losdcnvendorid, dcn.losdcnamount,
isnull(sum(setamount),0) settled ,
dcn.losDCNDate --Ref.No:1
from losdebitcreditnote dcn
left outer join (select cs.companyid, cs.vsid, cs.shopid, cs.losshopdcnid, sum(cd.SettlementAmount) setamount  from
vendorsettlementheader cs, vendorsettlementdetail cd where cs.vsid = cd.vsid and cs.cancelled =0
group by cs.companyid, cs.vsid, cs.shopid, cs.losshopdcnid) csh  on dcn.losdcncompanyid = csh.companyid and
dcn.losdcnshopid = csh.shopid and dcn.losdcnid = csh.losshopdcnid
where losdcncancelled = 0 and losdcndebit =1 and losdcnvendorid is not null
group by dcn.losdcncompanyid, dcn.losdcnshopid, dcn.losdcnid, dcn.losdcnno,dcn.losdcnvendorid, dcn.losdcnamount,
dcn.losDCNDate   --Ref.No:1'
GO
/****** Object:  View [dbo].[vwpaymentvoucher]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentvoucher]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwpaymentvoucher    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwpaymentvoucher    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwpaymentvoucher    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwpaymentvoucher    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwpaymentvoucher    Script Date: 17/11/2001 9:21:48 PM ******/
CREATE view [dbo].[vwpaymentvoucher] as
select ph.phcompanyid companyid, ph.phpaymentid paymentid,  phpaymentdate paymentdate,
phpaymentno paymentno, phpayee payee, acc.accountdesc,
phchequedetails chequedetails, ph.phcbreferenceno cbreferenceno,
ph.phremarks remarks,  ph.phamount amount, cur.symbol
from ahqpaymentvoucherheader ph
left outer join ahqpaymentvoucherdetails pd on ph.phcompanyid = pd.pdcompanyid and ph.phpaymentid = pd.pdpaymentid
left outer join ahqpaymentvoucherdebitdetails pcd on ph.phcompanyid = pcd.pddcompanyid and ph.phpaymentid = pcd.pddpaymentid
,aaccountmaster acc, acurrencymaster cur
where ph.phbankcashid = acc.accountid and ph.phcompanyid = acc.companyid
and acc.companyid = cur.companyid and acc.currencyid = cur.currencyid
group by ph.phcompanyid,ph.phpaymentid,  pd.pdpaymentid, pcd.pddpaymentid, phpaymentdate,
phpaymentno, phpayee, acc.accountdesc,  phchequedetails, ph.phcbreferenceno,
ph.phremarks, ph.phamount, cur.symbol'
GO
/****** Object:  View [dbo].[vwReceiptVoucherDetails]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptVoucherDetails]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 10/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For  Settlement in ReceiptVoucherDetail Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on      :
-- Modified by      :
-- Comments         :
-------------------------------------------------------------------------------------------------------------------------
create VIEW [dbo].[vwReceiptVoucherDetails] AS
-- 1: For Opening Invoice and Service Invoices in HQ
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	AIH.InvoiceNo SettlementNo,''HQ Invoices'' Type,RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   AccountsInvoiceHeader AIH ON RVD.HQAccountsInvoiceID = AIH.InvoiceID
UNION ALL
-- 2: For HQ Debit Credit Notes
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	DCN.DCNNo,''HQ DCN'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   DebitCreditNote DCN ON RVD.dcnid = DCN.DCNId
UNION ALL
-- 3: For Shop Accounts Invoice
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LAIH.aiInvoiceNo,''Shop Acc Inv'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   LOsAccountsInvoiceHeader LAIH ON RVD.shopid = LAIH.aiShopID AND RVD.PosAccountsInvoiceID = LAIH.aiInvoiceID
UNION ALL
-- 4: For Shop Special Invoice
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LSIP.IhInvoiceNo,''Shop Spl Inv'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   losSpecialInvoiceHeader LSIP ON RVD.shopid = LSIP.IhShopID AND RVD.PosSpInvoiceID = LSIP.IhInvoiceID
UNION ALL
-- 5: For Shop Credit Invoices
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LIH.ihInvoiceNo,''Shop Inv'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   LOsInvoiceHeader LIH ON RVD.shopid = LIH.ihShopID AND RVD.posinvoiceid = LIH.ihInvoiceID
UNION ALL
-- 6: For Shop debut credit Notes
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LDCN.losDCNNo,''Shop DCN'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   losDebitCreditNote LDCN ON RVD.shopid = LDCN.losDCNShopid AND RVD.losdcnid = LDCN.losDCNId
UNION ALL
--7: For Shop Service Invoice Header
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LSIH.serinvNo,''Shop Ser Inv'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   LosServiceInvHeader LSIH ON RVD.shopid = LSIH.serinvhshopid AND RVD.posserviceinvoiceid = LSIH.serinvhid
UNION ALL
--8: For Hq Payments
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	PV.phPaymentNo,''HQ Payments'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   aHQPaymentVoucherHeader PV ON RVD.phpaymentid = PV.phPaymentID
UNION ALL
--9: For Export
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LEH.rehExportNo,''Export'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   losExportHeader LEH ON RVD.shopid = LEH.rehShopID AND RVD.posexportid = LEH.rehExportID
UNION ALL
--10: For Apartment Billing
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LABH.abhBillNo,''Apartment'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   losApartmentBillHeader LABH ON RVD.RoomBillID = LABH.abhBillId AND RVD.shopid = LABH.abhSHopID
UNION ALL
--11: For Utility Billing
SELECT 	RVD.ReceiptID,RVD.ReceiptDetailID,RVD.CompanyID,RVD.ShopId,RVD.AmountReceived ,
	LTSBH.tbhBillNo,''Utility'',RVD.dueperiod
FROM ReceiptVoucherDetails RVD
INNER JOIN   losTenantServiceBillHeader LTSBH ON RVD.UtilityBillID = LTSBH.tbhBillId AND RVD.shopid = LTSBH.tbhShopId'
GO
/****** Object:  View [dbo].[vwreexportvendorsettle]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportvendorsettle]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwreexportvendorsettle    Script Date: 18/01/2003 9:45:40 PM ******/
--Created By 	: Hariharan
--Created Date	: 25/12/2002
--for getting the details of rexport settlements with vendor
CREATE view [dbo].[vwreexportvendorsettle] as
select reh.rehcompanyid, reh.rehshopid, reh.rehexportid, reh.rehexportno, reh.rehvendorid,
reh.rehexportamount, isnull(sum(setamount),0) settled, v.currencyid, rehdepartmentid,
rehexportdate from losexportheader reh
left outer join (select cs.companyid, cs.vsid, cs.shopid, cs.losexportid,
sum(cd.SettlementAmount) setamount  from vendorsettlementheader cs, vendorsettlementdetail cd
where cs.vsid = cd.vsid and cs.cancelled =0 group by cs.companyid, cs.vsid, cs.shopid,
cs.losexportid) csh  on reh.rehcompanyid = csh.companyid and
reh.rehshopid = csh.shopid and reh.rehexportid = csh.losexportid , avendormaster v
where rehcancelled = 0 and rehtype=''I'' and  rehvendorid is not null
and v.vendorid = rehvendorid
group by reh.rehcompanyid, reh.rehshopid, reh.rehexportid, rehdepartmentid,
reh.rehexportno,reh.rehvendorid, v.currencyid, rehexportdate , reh.rehexportamount'
GO
/****** Object:  View [dbo].[vwPurchaseBillSettlementNo]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- verified by leo
-----------------------------------------------------------------------------
-- Modified on  : 06/09/2003
-- Modified by  : Kishore
-- Comments  : Added query to take LC payment
-----------------------------------------------------------------------------
-- Modified on  : 08/11/2010
-- Modified by  : VinothMurugan V
-- Comments  : Adding Confirmation Bit
-----------------------------------------------------------------------------
CREATE view [dbo].[vwPurchaseBillSettlementNo] as
select companyid, vendorid, max(setdate) setdate, max(refno) refno, billid,
sum(PaidAmount) PaidAmount
from (
select vh.companyid, vh.vendorid, vh.vsdate setdate,
vh.vsno refno, vd.pbhbillid billid, SettlementAmount PaidAmount
from vendorsettlementheader vh, vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid
and vd.pbhbillid is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, ph.phvendorid, ph.phpaymentdate setdate,
ph.phpaymentno refno, pd.pdbillsid, pdPaidAmount PaidAmount
from AHQpaymentvoucherheader ph, AHQpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pdbillsid is not null and ph.phConfirmed = 1
union all
-- Take LC Payments
select ph.phcompanyid, b.pbhVendorId, ph.phpaymentdate setdate,
ph.phpaymentno refno, b.pbhBillId, pddAmount
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
lospPurchaseBillHeader b, MiscSettings s
where pdd.pddPaymentID = ph.phPaymentID
and pdd.pddCompanyId = ph.phCompanyId
and pdd.pddHqPoId = b.pbhPoid
and ph.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0
and ph.phLcPayment in (''LCM'', ''LCO'')  and ph.phConfirmed = 1
) settledaccbills
group by companyid, vendorid, billid'
GO
/****** Object:  View [dbo].[vwHQAccBillPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccBillPaidDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 17/11/2001 9:21:45 PM ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 16/06/2001 15:36:33 ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 09/03/2001 02:32:24 ******/
/****** Object:  View dbo.vwHQAccBillPaidDetails    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwHQAccBillPaidDetails] as
select BillsID, phPaymentID, phPaymentDate, pdPaidAmount
from Bills,ahqpaymentvoucherheader,ahqpaymentvoucherdetails
where pdPaymentID=phPaymentID and pdAccBillsID=BillsID and phCancelled=0'
GO
/****** Object:  View [dbo].[vwpaymentsusedincosting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentsusedincosting]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------
--Created by abhishek
--on 05/12/09
--for showing payments are used in costing
--client:Muni
--------------------------------------------------------------------
create view [dbo].[vwpaymentsusedincosting] as
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate,phAmount,
phexchangerate ,(phAmount*phexchangerate)phExchangeAmount   from ahqpaymentvoucherheader, ahqpaymentvoucherdetails,lospPurchaseBillHeader,lopurchaseorderheader,
ahqpaymentvoucherdebitdetails,adepartmentmaster,LOaCostingHeader where chBillID=pbhBillID and pddhqpoid is not null and pddPaymentID=phPaymentID and
DepartmentID=phDepartmentID and  pohPoid=pbhPOID and pbhPOID=pddhqpoid  and  pbhused=1 and pbhVendorID= phVendorID and phCancelled=0 and phDepartmentID = pohDepartmentid
union
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate,phAmount,
phexchangerate ,(phAmount*phexchangerate)phExchangeAmount   from ahqpaymentvoucherheader, ahqpaymentvoucherdetails,lospPurchaseBillHeader,lopurchaseorderheader,
ahqpaymentvoucherdebitdetails,adepartmentmaster,LOaCostingHeader where chBillID=pbhBillID and pddhqpoid is not null and pddPaymentID=phPaymentID and
DepartmentID=phDepartmentID and  pohPoid=pbhPOID and pbhPOID=pddhqpoid  and  pbhused=1 and pbhVendorID= phVendorID and phCancelled=0 and phDepartmentID = pohDepartmentid'
GO
/****** Object:  View [dbo].[vwpaymentsusedincoasting]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpaymentsusedincoasting]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------
--Created by abhishek
--on 05/12/09
--for showing payments are used in costing
--client:Muni
--------------------------------------------------------------------
CREATE view [dbo].[vwpaymentsusedincoasting] as
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate,phAmount,
phexchangerate ,(phAmount*phexchangerate)CompanyAmount,(phAmount*phdepexrate)DepartmentAmount   from ahqpaymentvoucherheader, ahqpaymentvoucherdetails,lospPurchaseBillHeader,lopurchaseorderheader,
ahqpaymentvoucherdebitdetails,adepartmentmaster,LOaCostingHeader where chBillID=pbhBillID and pddhqpoid is not null and pddPaymentID=phPaymentID and
DepartmentID=phDepartmentID and  pohPoid=pbhPOID and pbhPOID=pddhqpoid  and  pbhused=1 and pbhVendorID= phVendorID and phCancelled=0 and phDepartmentID = pohDepartmentid
union
select phpaymentid,phCompanyID,DepartmentName,phPaymentDate,phPaymentNo,phPayee,phVendorID,phDepartmentID,phCustomerID,phFinancialID,phpohid,phdepexrate,phAmount,
phexchangerate ,(phAmount*phexchangerate)CompanyAmount,(phAmount*phdepexrate)DepartmentAmount   from ahqpaymentvoucherheader, ahqpaymentvoucherdetails,lospPurchaseBillHeader,lopurchaseorderheader,
ahqpaymentvoucherdebitdetails,adepartmentmaster,LOaCostingHeader where chBillID=pbhBillID and pddhqpoid is not null and pddPaymentID=phPaymentID and
DepartmentID=phDepartmentID and  pohPoid=pbhPOID and pbhPOID=pddhqpoid  and  pbhused=1 and pbhVendorID= phVendorID and phCancelled=0 and phDepartmentID = pohDepartmentid'
GO
/****** Object:  View [dbo].[vwPayments]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPayments]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- Modified on   : 08/12/2002
-- MOdified by   : leo
-- Comments  : v3
-----------------------------------------------------------------------------------
-- Modified on  : 05/09/2003
-- Modified by  : Kishore
-- Comments  : Added the LC query
-----------------------------------------------------------------------------------
-- Modified on  : 19/09/2003
-- Modified by  : Kishore
-- Comments  : Replaced pddAmount with pddCustomerAmount in Lc
-----------------------------------------------------------------------------------
--RefNo : 01
-- Modified on  : 14/10/2010
-- Modified by  : VinothMurugan V
-- Comments  : Adding inter divisional bills
-----------------------------------------------------------------------------------
--RefNo : 02
-- Modified on  : 22/10/2010
-- Modified by  : VinothMurugan V
-- Comments  : Adding Confirmation bit.
-----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwPayments] AS
select pvd.pdCompanyID companyid, pvh.phDepartmentID departmentid,
pvd.pdBillsID billsid,
pvh.phpaymentdate settleddate,pvd.pdPaidAmount as PaidAmount,
phvendorid vendorid,
isnull(pdshopid,0) shopid, ''fpb'' as type
from aHQPaymentVoucherDetails pvd, aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0 and pvh.phConfirmed = 1 ----RefNo : 02
and pvd.pdbillsid is not null
union all
-- take LC
select pdd.pddCompanyID companyid, pvh.phDepartmentID departmentid,
b.pbhBillId billsid,
pvh.phpaymentdate settleddate, pdd.pddCustomerAmount as PaidAmount,
phvendorid vendorid,
0 shopid, ''fpb'' as type
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader pvh,
lospPurchaseBillHeader b, MiscSettings s
where pdd.pddPaymentID = pvh.phPaymentID
and pdd.pddCompanyId = pvh.phCompanyID
and pdd.pddHqPoId = b.pbhPoid
and pvh.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0 and pvh.phConfirmed = 1 ----RefNo : 02
and pvh.phLcPayment in (''LCM'', ''LCO'')
union all
select vsh.CompanyID, vsh.DepartmentID,
vsd.pbhbillid, vsh.vsdate settleddate,
SettlementAmount as paidamount,vendorid,isnull(vsd.shopid,0) shopid,
''fpb'' as type
from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid
and vsh.vsid = vsd.vsid
and vsh.cancelled = 0
and vsd.pbhbillid is not null
union all
select vsh.CompanyID, vsh.DepartmentID, vsd.lphbillid, vsh.vsdate settleddate,
SettlementAmount as paidamount,vendorid,isnull(vsd.shopid,0) shopid,
''lpb''  as type
from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid
and vsh.vsid = vsd.vsid
and vsh.cancelled = 0
and vsd.lphbillid is not null
union all
select pvd.pdCompanyID, pvh.phDepartmentID, pvd.pdposlpbillid,
pvh.phpaymentdate settleddate,
pvd.pdPaidAmount as PaidAmount ,phvendorid, isnull(pdshopid,0) shopid, ''lpb''  as type
from aHQPaymentVoucherDetails pvd, aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0 and pvh.phConfirmed = 1 ----RefNo : 02
and pvd.pdposlpbillid is not null
union all
select pvd.pdCompanyID, pvh.phDepartmentID,pvd.pdAccBillsID,
pvh.phpaymentdate settleddate,
isnull(pvd.pdPaidAmount,0) as PaidAmount ,
phvendorid,isnull(pdshopid,0) shopid, ''accb''  as type
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0  and pvh.phConfirmed = 1 ----RefNo : 02
and pvd.pdAccBillsID is not null
union all
select vsh.CompanyID, vsh.DepartmentID, vsd.billid, vsh.vsdate settleddate,
SettlementAmount as paidamount,vendorid,isnull(vsd.shopid,0) shopid, ''accb''  as type
from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid and vsh.cancelled = 0 and
vsd.billid is not null
union all
SELECT csd.CompanyID,csh.departmentid, csd.dcnid , csh.vsdate ,
isnull(csd.settlementamount,0) as Amtsettled,vendorid,isnull(csd.shopid,0) shopid, ''cn'' as type
FROM vendorsettlementdetail csd, vendorsettlementHeader csh
where csd.vSID = csh.vSID and csd.CompanyID = csh.CompanyID
and csh.Cancelled = 0 and csh.vendorid is not null and csd.dcnid is not null
union all
select pvd.pdCompanyID, pvh.phDepartmentID, pvd.pddcnid, pvh.phpaymentdate settleddate,
pvd.pdPaidAmount as PaidAmount ,phvendorid, isnull(pdshopid,0) shopid, ''cn''  as type
from aHQPaymentVoucherDetails pvd, aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phConfirmed = 1 ----RefNo : 02
and pvh.phCancelled = 0 and pvd.pddcnid is not null
union all
SELECT csd.CompanyID,csh.departmentid, csd.losdcnid , csh.vsdate ,
isnull(csd.settlementamount,0) as Amtsettled,vendorid,isnull(csd.shopid,0) shopid,
''scn'' as type
FROM vendorsettlementdetail csd, vendorsettlementHeader csh
where csd.vSID = csh.vSID
and csd.CompanyID = csh.CompanyID
and csh.Cancelled = 0
and csh.vendorid is not null
and csd.losdcnid is not null
union all
select pvd.pdCompanyID, pvh.phDepartmentID, pvd.shopdcnid, pvh.phpaymentdate settleddate,
pvd.pdPaidAmount as PaidAmount ,phvendorid, isnull(pdshopid,0) shopid, ''scn''  as type
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0  and pvh.phConfirmed = 1 --RefNo : 02
and pvd.shopdcnid is not null
union all
SELECT csd.CompanyID,csh.departmentid, csd.receiptid , csh.vsdate ,
isnull(csd.settlementamount,0) as Amtsettled,vendorid,
isnull(csd.shopid,0) shopid, ''rf'' as type
FROM vendorsettlementdetail csd, vendorsettlementHeader csh
where csd.vSID = csh.vSID
and csd.CompanyID = csh.CompanyID
and csh.Cancelled = 0
and csh.vendorid is not null
and csd.receiptid is not null
union all
select pvd.pdCompanyID, pvh.phDepartmentID, pvd.pdreceiptid, pvh.phpaymentdate settleddate,
pvd.pdPaidAmount as PaidAmount ,phvendorid, isnull(pdshopid,0) shopid, ''rf''  as type
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0  and pvh.phConfirmed = 1 --RefNo : 02
and pvd.pdreceiptid is not null
------------------------------------------------------------RefNo : 01
union all
select pvd.pdCompanyID, pvh.phDepartmentID,pvd.pdIndevBillsID,
pvh.phpaymentdate settleddate,
isnull(pvd.pdPaidAmount,0) as PaidAmount ,
phvendorid,isnull(pdshopid,0) shopid, ''IDB''  as type
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID
and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0 and pvh.phConfirmed = 1    --RefNo : 02
and pvd.pdIndevBillsID is not null
union all
select vsh.CompanyID, vsh.DepartmentID, vsd.InterdivBillID, vsh.vsdate settleddate,
SettlementAmount as paidamount,vendorid,isnull(vsd.shopid,0) shopid, ''IDB''  as type
from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid and vsh.cancelled = 0 and
vsd.InterdivBillID is not null
-----------------------------------------------------------------------'
GO
/****** Object:  View [dbo].[vwHQCNSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQCNSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQCNSettlementDetails    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwHQCNSettlementDetails    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwHQCNSettlementDetails    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwHQCNSettlementDetails    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwHQCNSettlementDetails    Script Date: 17/11/2001 9:22:00 PM ******/
-- Last Modified on : 18/10/01
-- Modified by      : leo
CREATE view [dbo].[vwHQCNSettlementDetails] as
SELECT csd.CompanyID, csd.dcnid , max(csh.vsdate) vsdate,
csh.departmentid, sum(isnull(csd.settlementamount,0)) as Amtsettled
FROM vendorsettlementdetail csd, vendorsettlementHeader csh
where csd.vSID = csh.vSID and csd.CompanyID = csh.CompanyID
and csh.Cancelled = 0 and csh.vendorid is not null and csd.dcnid is not null
GROUP BY csd.CompanyID, csd.dcnid, departmentid'
GO
/****** Object:  View [dbo].[vwHQBillPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQBillPaidDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by		: Kishore
-- Modified on		: 06/09/2003
-- Comments     	: Added query to take LC amount
---------------------------------------------------------------------------------------------
-- Modified on		: 19/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAmount with pddCustomerAmount in Lc
---------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwHQBillPaidDetails] AS
select pbhBillId, phPaymentId, phPaymentDate, sum(pdPaidAmount) pdPaintAmount
from
	(select pbhBillId, phPaymentId, phPaymentDate, pdPaidAmount
	from losppurchasebillheader, ahqpaymentvoucherheader,
	aHqPaymentVoucherDetails
	where pdPaymentID = phPaymentID
	and pdBillsID = pbhBillID
	and phCancelled = 0
	Union All
	-- Take LC Payments
	select b.pbhBillId, b.pbhVendorId , ph.phPaymentDate,
	pdd.pddCustomerAmount
	from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
	lospPurchaseBillHeader b, MiscSettings s
	where pdd.pddPaymentID = ph.phPaymentId
	and pdd.pddCompanyId = ph.phCompanyId
	and pdd.pddHqPoId = b.pbhPoid
	and ph.phCancelled = 0
	and b.pbhBillId is not null
	and s.LcToAccount = 0
	and ph.phLcPayment in (''LCM'', ''LCO'')) a
Group by  pbhBillId, phPaymentId, phPaymentDate'
GO
/****** Object:  View [dbo].[vwhqpbillsettlementdetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqpbillsettlementdetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwhqpbillsettlementdetails    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwhqpbillsettlementdetails    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwhqpbillsettlementdetails    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwhqpbillsettlementdetails    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwhqpbillsettlementdetails    Script Date: 17/11/2001 9:22:00 PM ******/
-- Last Modified on: 18/10/01
-- Modified by     : leo
CREATE view [dbo].[vwhqpbillsettlementdetails] as
select vsh.CompanyID, vsh.DepartmentID, vsd.pbhbillid, max(vsh.vsdate) settleddate,
sum(SettlementAmount) as paidamount from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid and vsh.cancelled = 0 and
vsd.pbhbillid is not null
group by vsh.CompanyID, vsh.DepartmentID, vsd.pbhbillid'
GO
/****** Object:  View [dbo].[vwHQPBillPaymentDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPBillPaymentDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on : 18/10/01
-- Modified by      : leo
---------------------------------------------------------------------
-- Modified on      : 06/09/2003
-- Modified by	    : Kishore
-- Comments         : Added query to tale LC payments
---------------------------------------------------------------------
-- Modified on		: 19/09/2003
-- Modified by		: Kishore
-- Comments		: Replaced pddAmount with pddCustomerAmount in Lc
-----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwHQPBillPaymentDetails] AS
select pdCompanyID, phDepartmentID, pdBillsID,
MAX(a.settleddate) SettledDate, sum(PaidAmount) as PaidAmount
from (select pvd.pdCompanyId, pvh.phDepartmentId, pvd.pdBillsId,
	pvh.phpaymentdate SettledDate,
	pvd.pdPaidAmount PaidAmount
	from aHQPaymentVoucherDetails pvd, aHQPaymentVoucherHeader pvh
	where pvd.pdPaymentID = pvh.phPaymentID
	and pvd.pdCompanyID = pvh.phCompanyID
	and pvh.phCancelled = 0
	and pvd.pdbillsid is not null
	
	Union All
	-- Take LC Payments
	select ph.phCompanyId, phDepartmentId, b.pbhBillId,
	phPaymentDate, pddCustomerAmount
	from aHQPaymentVoucherDebitDetails pdd,
	aHQPaymentVoucherHeader ph, lospPurchaseBillHeader b, MiscSettings s
	where pdd.pddPaymentID = ph.phPaymentID
	and pdd.pddCompanyId = ph.phCompanyId
	and pdd.pddHqPoId = b.pbhPoid
	and ph.phCancelled = 0
	and b.pbhBillId is not null
	and s.LcToAccount = 0
	and ph.phLcPayment in (''LCM'', ''LCO'')
) a
group by a.pdCompanyID, a.phDepartmentID, a.pdBillsID'
GO
/****** Object:  View [dbo].[vwItemSplitCosting]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSplitCosting]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by	   : Santhosh M
-- Added scfhcancelled on 30/09/2003
------------------------------------------------------------------------------------
-- Modified by     : Kishore
-- Modified on     : 13/01/2003
-- Comments        : Added currency symbol
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwItemSplitCosting] AS
select g.godownname, scfh.scfhCostingId,scfh.scfhid,
ish.ishdate, ish.ishno, scfh.scfhNo,
scfh.scfhDate, scfh.scfhRemarks, case scfh.scfhCostFixed when 1 then ''Yes''
when 0 then ''No'' end costingdone, u.unitname,
scfd.scfdOldItemRate,vw.itemdescription,
scfd.scfdFixedPrice, scfd.scfdCostprice, scfd.scfdQuantity, scfh.scfhQuantity,
scfh.scfhCostedPrice,a.itemcode, scfh.scfhCancelled, Currency.Symbol CurrencySymbol
from loaitemsplitcostingheader scfh,
loaitemsplitcostingdetail scfd, loiitemsplitheader ish,
agodown g, aitem a, aunit u, vwitemdescription vw,
(select top 1 p.CompanyId, cm.Symbol -- top 1 is for extra security
from aPackageSettings p, aAccountMaster am, aCurrencyMaster cm
where p.InventoryId = am.AccountId
and p.CompanyId = am.CompanyId
and am.CurrencyId = cm.CurrencyId
and am.CompanyId = cm.CompanyId) Currency -- this derived table returns the inventory currency
where scfh.scfhid = scfd.scfdid
and scfh.scfhItemSplitId = ish.ishid
and scfh.scfhgodownid = ish.ishgodownid
and ish.ishgodownid = g.godownid
and scfd.scfditemid = a.itemid
and a.unitsid = u.unitid
and vw.itemid = a.itemid
and scfhCompanyId = Currency.CompanyId'
GO
/****** Object:  View [dbo].[vwHQAccinterdevbillPayments]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccinterdevbillPayments]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : VinothMurugan V.
--Date   : 13/10/2010
--Purpose  : Show inter division bill paid in payments
create view [dbo].[vwHQAccinterdevbillPayments] as
select ph.phcompanyid, ph.phvendorid, pd.pdshopid, pd.pdIndevBillsID,0.0 as billamount,
sum(pd.pdpaidamount) as paidamount from ahqpaymentvoucherheader ph, ahqpaymentvoucherdetails pd
where ph.phcompanyid=pd.pdcompanyid and ph.phpaymentid=pd.pdpaymentid and ph.phcancelled=0 and
pd.pdIndevBillsID  is not null group by ph.phcompanyid, ph.phvendorid, pd.pdshopid, pd.pdIndevBillsID'
GO
/****** Object:  View [dbo].[vwHQAccPayments]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccPayments]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQAccPayments    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwHQAccPayments    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwHQAccPayments    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwHQAccPayments    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwHQAccPayments    Script Date: 17/11/2001 9:21:45 PM ******/
/****** Object:  View dbo.vwHQAccPayments    Script Date: 16/06/2001 15:36:33 ******/
CREATE view [dbo].[vwHQAccPayments] as
select ph.phcompanyid, ph.phvendorid, pd.pdshopid, pd.pdaccbillsid,0.0 as billamount,
sum(pd.pdpaidamount) as paidamount from ahqpaymentvoucherheader ph, ahqpaymentvoucherdetails pd
where ph.phcompanyid=pd.pdcompanyid and ph.phpaymentid=pd.pdpaymentid and ph.phcancelled=0 and
pd.pdaccbillsid is not null group by ph.phcompanyid, ph.phvendorid, pd.pdshopid, pd.pdaccbillsid'
GO
/****** Object:  View [dbo].[vwHQLCPaidDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQLCPaidDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 17/11/2001 9:21:46 PM ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 16/06/2001 15:36:33 ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 09/03/2001 02:32:24 ******/
/****** Object:  View dbo.vwHQLCPaidDetails    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwHQLCPaidDetails] as
select pohPoid, phPaymentID, phPaymentDate, pdPaidAmount
from lopurchaseorderheader,ahqpaymentvoucherheader,ahqpaymentvoucherdetails
where pdPaymentID=phPaymentID and pdHQPOID=pohPoid and phCancelled=0'
GO
/****** Object:  View [dbo].[vwHQIssueDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQIssueDetails]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------
--Created By : Yogesh Joe
--Created On : 24-04-2009
--Purpose    : To get details of shopwise HQ Issue details of godowns
-----------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwHQIssueDetails] as
select shopName,issueNoteNo,issueNoteDate,issueQty,confirmed,godownid,barCode from(
select ShopName shopName,INHissuenoteNO issueNoteNo,INHIssuedate issueNoteDate,INDQty issueQty,
case INHTransFinished when 0 then ''No'' when 1 then ''Yes'' end confirmed ,
INHGodownID godownid,PackingBarCode barCode from ahqissuenoteheader inh
left outer join ahqissuenotedetail ind on inh.INHIssuenoteID=ind.INDIssuenoteID
left outer join ashops shp on inh.INHToshopID=shp.ShopID
left outer join aitempackingdetail pd on INDItemID=pd.ItemID
where
INHCancelled = 0 and INHUsed = 0
) Issue Group by shopName,confirmed,issueNoteNo,issueNoteDate,issueQty,godownid,barCode'
GO
/****** Object:  View [dbo].[vwHQinvoicereceipt]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQinvoicereceipt]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwHQinvoicereceipt] as
select rh.companyid ,rd.HQaccountsinvoiceid, rh.customerid, rd.shopid, max(rh.ReceiptDate) receiptdate, rh.ReferenceNo refno,
null departmentid, 0.0 as invoiceamt, sum(amountreceived) settledamt from
receiptvoucherheader rh, receiptvoucherdetails rd, accountsinvoiceheader ah where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.companyid = ah.companyid and rd.HQaccountsinvoiceid = ah.invoiceid and rd.HQaccountsinvoiceid is not null
group by
rh.companyid, HQaccountsinvoiceid, rh.customerid, rd.shopid, rh.ReferenceNo'
GO
/****** Object:  View [dbo].[vwadvancepaidreceipts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidreceipts]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on 	: 28/02/2003
--Modified by	 	: R Harikrishnan
--Comments 		: v3
--Added MultiCustomer option
--Modified by	 	: venki 010903
--Comments 		: added amount field  option
CREATE    view  [dbo].[vwadvancepaidreceipts] as
select
	companyid, receiptid, customerid,sum(customeramount)Amount
from
	(select
		receiptid,companyid,customerid,customeramount
	from
		receiptvoucherheader
	where
		cancelled = 0 and customerid is not null
	
	union all
	
	select
		distinct(rd.receiptid), rd.companyid, rh.customerid,rh.customeramount
	from
		receiptvoucherdetails rd, receiptvoucherheader rh
	where
		rd.companyid = rh.companyid and rd.receiptid = rh.receiptid and rh.cancelled =0 and
		rh.customerid is not null
	union all
	select
		rd.receiptid, rd.companyid, rd.customerid,rd.CustomerAmount amount
	from
		ReceiptVoucherCustomerDetails rd, receiptvoucherheader rh
	where
		rd.companyid = rh.companyid and rd.receiptid = rh.receiptid and rh.cancelled =0 and
		rh.receiptcustomerid is not null
	) temp1
group by
	companyid, customerid, receiptid
having
	count(receiptid) =1'
GO
/****** Object:  View [dbo].[vwspecialinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvoicereceipt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwspecialinvoicereceipt    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwspecialinvoicereceipt] as
select rh.companyid, rd.shopid, rd.posspinvoiceid, max(rh.receiptdate) receiptdate,
rh.customerid, 0.0 as invoiceamt, sum(amountreceived) settledamt
from receiptvoucherheader rh, receiptvoucherdetails rd where rh.companyid=rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled = 0 and rd.posspinvoiceid is not null
group by rh.companyid, rd.shopid, posspinvoiceid, rh.customerid'
GO
/****** Object:  View [dbo].[vwaccbillvs]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccbillvs]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwaccbillvs    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwaccbillvs    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwaccbillvs    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwaccbillvs    Script Date: 20/11/2001 9:59:07 AM ******/
/****** Object:  View dbo.vwaccbillvs    Script Date: 17/11/2001 9:21:56 PM ******/
-- Last Modified on: 18/10/01
-- Modified by     : leo
CREATE view [dbo].[vwaccbillvs] as
select vsh.CompanyID, vsh.DepartmentID, vsd.billid, max(vsh.vsdate) settleddate,
sum(SettlementAmount) as paidamount from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid and vsh.cancelled = 0 and
vsd.billid is not null
group by vsh.CompanyID, vsh.DepartmentID, vsd.billid'
GO
/****** Object:  View [dbo].[vwaccBillsettlementpay]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccBillsettlementpay]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwaccBillsettlementpay    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwaccBillsettlementpay    Script Date: 14/09/2002 12:48:08 AM ******/
/****** Object:  View dbo.vwaccBillsettlementpay    Script Date: 31/07/2002 2:00:29 PM ******/
/****** Object:  View dbo.vwaccBillsettlementpay    Script Date: 20/11/2001 9:59:02 AM ******/
/****** Object:  View dbo.vwaccBillsettlementpay    Script Date: 17/11/2001 9:21:40 PM ******/
-- Last Modified on : 18/10/01
-- Modified by     : leo
CREATE view [dbo].[vwaccBillsettlementpay] as
select pvd.pdCompanyID, pvh.phDepartmentID,pvd.pdAccBillsID, max(pvh.phpaymentdate) settleddate,
isnull(sum(pvd.pdPaidAmount),0) as PaidAmount
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0 and pvd.pdAccBillsID is not null
group by pvd.pdCompanyID, pvh.phDepartmentID, pvd.pdAccBillsID'
GO
/****** Object:  View [dbo].[vwAccVendrPayments]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccVendrPayments]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 20/11/2001 9:59:07 AM ******/
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 17/11/2001 9:21:57 PM ******/
/****** Object:  View dbo.vwAccVendrPayments    Script Date: 16/06/2001 15:36:34 ******/
--Modified By : VinothMurugan V.
--Date		  : 14/10/2010
--Purpose	  : Adding Interdivisional Bills.
CREATE view [dbo].[vwAccVendrPayments] as
select vh.companyid, vh.vendorid, 0 as shopid, vd.billid,vd.InterdivBillID,0.0 as billamount,
sum(vd.settlementamount) as paidamount from VENDORSETTLEMENtheader vh, vendorsettlementdetail vd
where vh.companyid=vd.companyid and vh.vsid=vd.vsid and vh.cancelled=0 and (billid is not null or InterdivBillID is not null)
group by vh.companyid, vh.vendorid, vd.billid  ,vd.InterdivBillID
--previous Code
--CREATE view vwAccVendrPayments as
--select vh.companyid, vh.vendorid, 0 as shopid, vd.billid,0.0 as billamount,
--sum(vd.settlementamount) as paidamount from VENDORSETTLEMENtheader vh, vendorsettlementdetail vd
--where vh.companyid=vd.companyid and vh.vsid=vd.vsid and vh.cancelled=0 and
--vd.billid is not null group by vh.companyid, vh.vendorid, vd.billid'
GO
/****** Object:  View [dbo].[vwVendorSettlementDetails]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 06/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For Vendor Settlement in Detail Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on     :
-- Modified by     :
-- Comments        :
-------------------------------------------------------------------------------------------------------------------------
Create VIEW [dbo].[vwVendorSettlementDetails] AS
--HQ Bills
SELECT VSD.VSID SettlementID,VSD.VSDetailID DetailID,VSD.CompanyID CompanyID,VSD.BillAmount BillAmount,
	VSD.SettlementAmount SettlementAmount,B.BillsNo BillNo,''HQ Bills'' Type
FROM   	VendorSettlementDetail VSD
INNER JOIN Bills B ON VSD.BillID = B.BillsID
UNION ALL
--HQ DCN
SELECT VSD.VSID,VSD.VSDetailID,VSD.CompanyID,VSD.BillAmount,VSD.SettlementAmount,DCN.DCNNo,''HQ DCN''
FROM   	VendorSettlementDetail VSD
INNER JOIN DebitCreditNote DCN ON VSD.dcnid = DCN.DCNId
UNION ALL
--HQ Purchase BIll
SELECT VSD.VSID,VSD.VSDetailID,VSD.CompanyID,VSD.BillAmount,VSD.SettlementAmount,PB.pbhBillNo,''HQ Purchase BIll''
FROM   	VendorSettlementDetail VSD
INNER JOIN LOspPurchaseBillHeader PB ON VSD.pbhbillid = PB.pbhBillID
UNION ALL
--Local Purchase BIll
SELECT VSD.VSID,VSD.VSDetailID,VSD.CompanyID,VSD.BillAmount,VSD.SettlementAmount,LPB.lphBillNo,''Local Purchase BIll''
FROM   	VendorSettlementDetail VSD
INNER JOIN LosLocalPurchaseHeader LPB ON VSD.shopid = LPB.lphShopID AND VSD.lphbillid = LPB.lphBillID
UNION ALL
--Shop DCN
SELECT VSD.VSID,VSD.VSDetailID,VSD.CompanyID,VSD.BillAmount,VSD.SettlementAmount,losDCNNO,''Shop DCN'' Type
FROM   	VendorSettlementDetail VSD
INNER JOIN losDebitCreditNote LDCN ON VSD.shopid = LDCN.losDCNShopid AND VSD.losdcnid = LDCN.losDCNId'
GO
/****** Object:  View [dbo].[vwAdvancePaidPayments]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAdvancePaidPayments]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified on  : 28/02/2003
-- Modified by  : R Harikrishnan
-- Comments : Added Multi vendor options
-- verified by leo
----------------------------------------------------------------
--Modified By : VinothMurugan V.
--Date		  : 14/10/2010
--Purpose     : adding confirm bit
--RefNo-01
----------------------------------------------------------------
CREATE VIEW [dbo].[vwAdvancePaidPayments] AS
select
phCompanyId CompanyId, phPaymentId PaymentId,
phvendorid VendorId, sum(phamount) Amount
from
(select
phpaymentid, phcompanyid, phvendorid,phcustomeramount phamount
from
ahqpaymentvoucherheader
where
phcancelled = 0
AND phlcpayment=''OP''
and phConfirmed = 1 --RefNo-01
union all
select
distinct(pd.pdpaymentid),pd.pdcompanyid, ph.phvendorid,phamount
from
ahqpaymentvoucherdetails pd, ahqpaymentvoucherheader ph
where
ph.phpaymentid = pd.pdpaymentid and ph.phcompanyid = pd.pdcompanyid
and ph.phcancelled =0 and ph.phlcpayment=''OP'' and ph.phConfirmed = 1 --RefNo-01
union all
--Multiple vendor
select
pd.pvdpaymentid,pd.pvdcompanyid, pd.pvdvendorid, pd.pvdamount
from
aHQPaymentVoucherVendorDetails pd, ahqpaymentvoucherheader ph
where
ph.phpaymentid = pd.pvdpaymentid and ph.phcompanyid = pd.pvdcompanyid
and ph.phcancelled =0 and ph.phlcpayment=''OP''  and ph.phConfirmed = 1 --RefNo-01
) temp1
group by
phcompanyid, phvendorid, phpaymentid
having
count(phpaymentid) =1'
GO
/****** Object:  View [dbo].[vwadvancepaidDebitsAmounts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidDebitsAmounts]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 20/11/2001 9:59:07 AM ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 17/11/2001 9:21:57 PM ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 16/06/2001 15:36:34 ******/
/****** Object:  View dbo.vwadvancepaidDebitsAmounts    Script Date: 09/03/2001 02:32:28 ******/
--Modified By : VinothMurugan V.
--Date		  : 14/10/2010
--purpose	  : Adding Confirm bit
CREATE view [dbo].[vwadvancepaidDebitsAmounts] as
select DCNCompanyID, DCNID, DCNVendorId, sum(advanceamt) Pmtamt,
sum(settlementamt) settledamt from
(select dcn.DCNID, dcn.DCNCompanyID, dcn.DCNVendorId, DCNAmount advanceamt,
0.0 as settlementamt from debitcreditnote dcn, vwadvancepaidDebits vw
where dcn.DCNCompanyID = vw.DCNcompanyid and dcn.DCNID = vw.DCNID and
dcn.DCNcancelled = 0 and dcn.DCNDebit = 1 and dcn.DCNConfirmed = 1
union all
select vh.dcnid, vh.companyid, vh.vendorid,0.0 advanceamt,
sum(vd.SettlementAmount) settlementamt from
vendorsettlementheader vh, vendorsettlementdetail vd, vwadvancepaidDebits vw
where vw.DCNcompanyid = vh.companyid and vw.DCNID = vh.dcnid and
vh.companyid = vd.companyid and vh.vsid = vd.vsid and vh.cancelled =0
group by vh.dcnid, vh.companyid, vh.vendorid) temp1
group by DCNcompanyid, DCNID, DCNvendorid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersReceipts]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersReceipts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified by  : Kishore
-- Modified on  : 13/06/2003
-- Comments  : Included the receipt modification script
--                        (on comparison with V2)
---------------------------------------------------------------------------------------
-- Modified by  : R Harikrishnan, Hariharan
-- Modified on  : 19/07/2003,25/07/2003,24/09/2003, 25/01/2004, 29/03/2004,1/7/2010
-- Comments  : Multi customer posting, Bank charges debit account posting
--   : corrected. Deparment Exrate Posting Corrected. The amount
--   : convertion was not correct
--   : Changed the precision to 4
--   : exchange gain or less abs condition given in case of -ve
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
--last modified by Sreejith : 06/04/2010
--Coments   : increased the space between the seperator in remarks column
-----Discount is posted to the accoutnts
---------------------------------------------------------------------------------------
---last modified by Sreejith : 01/07/2010  , jyothish : 05102011
---Discount is posted to the jornal     .corrected discount problem
---------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateLedgersReceipts]
@intCompanyID as int,
@intreceiptid as int
as
begin
--For testing purpose Commented by R Harikrishnan
--set @intCompanyID= 1
--set @intreceiptid= 1895
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@strReceiptNo as varchar(50),
@dtReceiptDate as datetime,
@intCustomerID as int,
@intVendorID as int,
@strRemarks as varchar(750),
@intDepartmentID as int,
@intBankCashID as int,
@numReceiptAmt as numeric(18,4),
@intDebitAccid as int,
@numDebitamt as numeric(18,4),
@intCrEDitAccID as int,
@numCrEDitAmt as numeric(18,4),
@strType as char(2),
@dtchequedate as datetime,
@dtutime as datetime,
@intcurrencyid as int,
@numconsrate as numeric(18,8),
@numdeprate as numeric(18,8),
@numtemp as numeric(18,4),
@numresamount as numeric(18,4),
@strexrates as varchar(250),
@intHeaderCreditAccID as int,
@numHeaderCreditAmount as numeric(18, 4),
@numcustomerequiamt as numeric(18,4),
@intCompanyCurID as int,
@numBuyingRate as numeric(28,8),
@intTransCurID as int,
@numAverageRate as numeric(28,8),
@numTransRate as numeric(28,8),
@intExchangeAccID as int,
@intbankcashcurid as int,
@numPerExRate as numeric(18,8),
@numbankamt as numeric(18,4),
@intreceiptcustomerid as int,
@intMCCustID as int,
@intMCAmt as numeric(18,4),
@intMCCustAmt as numeric(18,4),
@intDiscountID as numeric(18,4),
@numDisAmount as numeric(28,8)
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
moaJournalHeader
WHERE
CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
begin tran
Declare ReceiptCur cursor for
SELECT
ReceiptID, receiptno, ReceiptDate, case when
(chequedetails is null or chequedetails ='''') then remarks
else chequedetails + '';    '' + remarks end as remarks, bankcashAccountID,
vendorID, customerID, Amount, financialID, departmentID,ExchangeRate,
debitaccountid, isnull(debitamount,0), customeramount, chequedate,
updatetime, CreditAccountID, CreditAmount,
Convert(numeric(18,8), substring(cancelledremarks, 1, 15)),receiptcustomerid,
depexrate,exchangerates ,Discountaccountid,isnull(DiscountAmount,0)
FROM
ReceiptVoucherHeader
WHERE
posted = 0 and CompanyID = @intCompanyID and cancellED =0 and
receiptid = @intreceiptid
open ReceiptCur
fetch next FROM
ReceiptCur
into
@intReceiptID, @strreceiptno, @dtReceiptDate, @strRemarks,@intBankCashID,
@intVendorID, @intCustomerID, @numreceiptAmt, @intFinancialID, @intDepartmentID,
@numconsrate ,@intdebitaccid, @numdebitamt, @numcustomerequiamt,@dtchequedate,
@dtutime, @intHeaderCreditAccID, @numHeaderCreditAmount, @numPerExRate,
@intreceiptcustomerid, @numdeprate, @strexrates ,@intDiscountID,@numDisAmount
while @@Fetch_status = 0
begin
/* finding the type of transaction */
if (@intcustomerID is not null) and (@intreceiptcustomerid is null)
begin
SELECT * FROM receiptvoucherdetails WHERE CompanyID = @intCompanyID and
ReceiptID = @intReceiptID
if @@rowcount > 0
set @strType =''CS''
else
set @strType =''CA''
end
if (@intvendorID is not null)
set @strType =''V''
if (@intvendorID is null and @intCustomerID is null and @intreceiptcustomerid is null)
set @strType = ''A''
if (@intreceiptcustomerid is not null)
set @strType = ''MC''
if (@strType =''CA'') or (@strtype =''CS'')
begin -- customer advance payment
-- getting the customer currency
SELECT @intTransCurID = CurrencyID
FROM aCustomerMaster
WHERE CompanyID = @intCompanyID
and customerID = @intCustomerID
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID,Type, CurrencyID,chequedate, updatetime)
values (@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
set @numbankamt = 0.0
set @numbankamt = (@numreceiptamt - @numdebitamt)
set @numbankamt =@numbankamt-@numDisAmount--ref-1
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intBankCashID,
@numbankamt * @numconsrate, @numbankamt, @intDepartmentID, @numbankamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID
and accountID = @intBankCashID
-----------------------------ref-1--------------------------------------
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID
and accountID = @intDiscountID
if (@intDiscountID is not null and @numDisAmount<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDiscountID,
''a'', @strexrates, @numDisAmount, @numresamount output
--debiting the debit account with debit amt
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDiscountID, @numDisAmount * @numconsrate, @numresamount,
@intDepartmentid, @numDisAmount * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
------------------------------------------------------------------
----
if (@intdebitaccID is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output
--debiting the debit account with debit amt
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentid, @numdebitamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
---
exec spConvertequiamount @intcustomerid, ''c'', @intcurrencyid, ''m'',
@strexrates, @numcustomerequiamt, @numresamount output
-- crediting the customer with the whole receipt amount
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
customerID, Amount, actualAmount,departmentid,depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcustomerID, @numresamount * @numconsrate, @numcustomerequiamt,
@intDepartmentid,@numresamount * @numdeprate)
if (@intHeaderCreditAccid is not null and @numHeaderCreditAmounT <>0)
Begin
exec spConvertequiamount @intcustomerid, ''c'', @intHeaderCreditAccid, ''a'',
@strexrates, @numHeaderCreditAmount, @numresamount output
exec spConvertequiamount @intcustomerid, ''c'', @intcurrencyid, ''m'',
@strexrates, @numHeaderCreditAmount, @numCrEDitAmt output
set @intJournalDetailID = @intJournalDetailID + 1
IF @numHeaderCreditAmounT >0 --hari 040125
Begin
-- crediting the customer with the whole receipt amount
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intHeaderCreditAccid, @numCrEDitAmt * @numconsrate,
@numresamount, @intDepartmentid, @numCrEDitAmt * @numdeprate)
End
IF @numHeaderCreditAmounT <0
Begin
-- crediting the customer with the whole receipt amount
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intHeaderCreditAccid, abs(@numCrEDitAmt) * @numconsrate,
abs(@numresamount), @intDepartmentid, abs(@numCrEDitAmt) * @numdeprate)
End
End
end  -- for customer advance payment
if @strType =''V''
begin -- vendor receipt
SELECT @intTransCurID = CurrencyID
FROM avendormaster
WHERE CompanyID = @intCompanyID
AND vendorID = @intvendorID
insert into moaJournalHeader
(JournalID, CompanyID, JournalDate, referenceno, remarks,
financialID,Type, CurrencyID,chequedate, updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate,
@dtutime)
set @intJournalDetailID = 1
set @numbankamt = (@numreceiptamt - @numdebitamt )
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, @numbankamt* @numconsrate, @numbankamt,
@intDepartmentID, @numbankamt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
SELECT
@intcurrencyid = CurrencyID
FROM
aaccountmaster
WHERE
CompanyID = @intCompanyID and accountID = @intBankCashID
if (@intdebitaccid is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output
-- debiting the debit account
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentid, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
exec spConvertequiamount @intvendorid, ''v'', @intcurrencyid, ''m'',
@strexrates, @numcustomerequiamt, @numresamount output
-- crediting the customer with the whole receipt amount
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, vendorID,
Amount, actualAmount,departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intvendorID, @numresamount * @numconsrate, @numcustomerequiamt,
@intDepartmentid, @numresamount * @numdeprate)
if @intHeaderCreditAccid is not null and @numHeaderCreditAmounT <>0
Begin
exec spConvertequiamount @intvendorid, ''v'', @intHeaderCreditAccid, ''a'',
@strexrates, @numHeaderCreditAmount, @numresamount output
exec spConvertequiamount @intvendorid, ''v'', @intcurrencyid, ''m'',
@strexrates, @numHeaderCreditAmount, @numCrEDitAmt output
set @intJournalDetailID = @intJournalDetailID + 1
-- crediting the customer with the whole receipt amount
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountId, Amount, actualAmount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intHeaderCreditAccid, @numCrEDitAmt * @numconsrate,
@numresamount, @intDepartmentid, @numCrEDitAmt * @numdeprate)
End
end  -- for vendor receipt
if @strType =''A''
begin -- for account heads
SELECT
@intcurrencyid = CurrencyID
FROM
aaccountmaster
WHERE
CompanyID = @intCompanyID and AccountID = @intBankcashID
insert into moaJournalHeader
(JournalID, CompanyID, JournalDate, referenceno,remarks,
financialID,Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
SELECT
@numreceiptAmt = sum(Amount)
FROM
receiptvouchercrEDitdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
/* debiting either cash or bank */
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, ((@numReceiptAmt - @numdebitamt) * @numconsRate),
(@numReceiptAmt - @numdebitamt) , @intDepartmentID,
((@numReceiptAmt - @numdebitamt) * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebitaccid is not null and @numdebitamt<>0)
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output
-- debiting the debit account
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentID, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
Declare CrEDitCur cursor for
SELECT
AccountID, Amount
FROM
receiptVouchercrEDitdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
open CrEDitCur
fetch next FROM CrEDitCur  into
@intCrEDitAccID, @numCrEDitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intcreditaccID,
''a'', @strexrates, @numcreditamt, @numresamount output
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount, departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intCrEDitAccID, (@numCrEDitAmt * @numconsRate),
@numresamount, @intDepartmentID,
(@numCrEDitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM CrEDitCur into @intCrEDitAccID, @numCrEDitAmt
end
close CrEDitCur
deallocate CrEDitCur
end -- for account heads
if @strType =''MC''
begin -- for multiple customers
SELECT @intcurrencyid = CurrencyID FROM aaccountmaster
WHERE CompanyID = @intCompanyID and AccountID = @intBankcashID
insert into moaJournalHeader
(JournalID, CompanyID, JournalDate, referenceno,
remarks, financialID,Type, CurrencyID,chequedate,updatetime)
values
(@intJournalID, @intCompanyID, @dtReceiptDate, @strreceiptNo,
@strRemarks, @intFinancialID,''R'', @intcurrencyid, @dtchequedate, @dtutime)
set @intJournalDetailID = 1
/* debiting either cash or bank */
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intBankCashID, ((@numReceiptAmt - @numdebitamt) * @numconsRate),
(@numReceiptAmt - @numdebitamt) , @intDepartmentID,
((@numReceiptAmt - @numdebitamt) * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebitaccid is not null )
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intdebitaccID,
''a'', @strexrates, @numdebitamt, @numresamount output
-- debiting the debit account
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intdebitaccID, @numdebitamt * @numconsrate, @numresamount,
@intDepartmentID, @numdebitamt * @numdeprate)
-- crediting the vendor with the whole receipt amount
set @intJournalDetailID = @intJournalDetailID +1
end
Declare
CrEDitCur
cursor for
SELECT
CustomerId, Amount, CustomerAmount
FROM
receiptVoucherCustomerdetails
WHERE
CompanyID = @intCompanyID and ReceiptID = @intReceiptID
open CrEDitCur
fetch next FROM
CrEDitCur
into
@intMCCustID, @intMCAmt, @intMCCustAmt
while @@Fetch_status =0
begin
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID,
JournalCrEDit, CustomerID, Amount, actualAmount,
departmentID, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intMCCustID, (@intMCAmt  * @numconsRate),
@intMCCustAmt, @intDepartmentID, (@intMCAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM
CrEDitCur
into
@intMCCustID, @intMCAmt, @intMCCustAmt
end
close CrEDitCur
deallocate CrEDitCur
end -- for multiple customers
update ReceiptVoucherHeader set postED =1
WHERE ReceiptID = @intReceiptID and CompanyID = @intCompanyID
set @intJournalID = @intJournalID + 1
fetch next FROM
ReceiptCur
into
@intReceiptID, @strreceiptno, @dtReceiptDate, @strRemarks,
@intBankCashID, @intVendorID, @intCustomerID, @numreceiptAmt,
@intFinancialID, @intDepartmentID, @numconsrate ,@intdebitaccid,
@numdebitamt, @numcustomerequiamt, @dtchequedate, @dtutime,
@intHeaderCreditAccID, @numHeaderCreditAmount, @numPerExRate,
@intreceiptcustomerid, @numdeprate, @strexrates ,@intDiscountID,@numDisAmount
end
Close ReceiptCur
Deallocate ReceiptCur
commit tran
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersPayments]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersPayments]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- modified   : 02/02/2003, 16/07/2003, 22/09/2003, 09/12/2004
-- Last modified by : leo, Hariharan R
-- Comments   : the concept of new exchange rate is included
--------------------------------------------------------------------------
-- modified   : 24/07/2003, 24/09/2003
-- Last modified by : R Harikrishnan
-- Comments   : Multi Vendor Option Included, Debit Account Posting
--   : corrected, Rebate Payment option added, Sales Commission
--   : Payment option added, Sales Promotion Payment option added,
--   : Shipment Projected Expenses and Other department Shipment
--   : Projected expenses corrected
--   : corrected the lc conditions as the details are not inserted
--   : Changed the numeric precision to 4
--   : added ''SCP'' and ''SPP'' for posting
--   : Debit Amount posting done with respect to -ve or +ve balance
--Verified by      : Hariharan
--Verified Date     : 03/05/2004, 09/12/2004
--(verified From Client DB)
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--last modified by Sreejith : 06/04/2010
--Coments   : increased the space between the seperator in remarks column
--------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateLEDgersPayments]
@intCompanyID  as int,
@intpaymentid  as int
as
set nocount on
begin
--For testin purpose by R Harikrishnan
--set @intCompanyID=1
--set @intpaymentid= 1264
--begin tran
Declare
@intJournalID as int,
@intJournalDetailID as int,
@intFinancialID as int,
@strPaymentNo as varchar(50),
@dtPaymentDate as datetime,
@intCustomerID as int,
@intVendorID as int,
@strRemarks as varchar(250),
@intDepartmentID as int,
@intBankCashID as int,
@numPaymentAmt as numeric(18,4),
@intDebitAccID as int,
@numDebitAmt as numeric(18,4),
@strType as char(2),
@strPaymentType varchar(5),
@numvendorequiamt as numeric(18,4),
@intBankcashcurid as int,
@intGoodsInTransitAccID as int,
@intdebit as int,
@numdebit as numeric(18,4),
@dtchequedate as datetime,
@dtutime as datetime,
@numlcAmt as numeric(18,4),
@inthqpoid as int,
@intcurrencyid as int,
@numconsrate as numeric(18,9),
@numdeprate as numeric(18,9),
@strexrates as varchar(250),
@numresamount as numeric(18,4),
@numdepcuramt as numeric(18,4),
@numtemp as numeric(18,4),
@LCtobeAccounted as bit,
@intPaidByVendorid as int,
@intMVVendorID as int,
@numMVAmt as numeric(18,4),
@numMVVendAmt as numeric(18,4)
/* getting the maximum Journal ID FROM journal table */
SELECT
@intJournalID = isnull(max(JournalID),0)
FROM
moaJournalHeader
WHERE CompanyID = @intCompanyID
--R Harikrishnan for LCtobeAccounted checking
select @LCtobeAccounted=isnull(Lctoaccount,0) from miscsettings
set @intJournalID = @intJournalID + 1
SELECT
@intPaymentID=phPaymentID, @strPaymentno= phpaymentno, @dtPaymentDate =
phpaymentdate, @strPaymentType = phLcPayment, @strRemarks = case when
(phchequedetails is null or phchequedetails ='''') then phremarks
else phchequedetails + '';    '' + phremarks end, @intBankCashID = phbankcashID, @intVendorID =
phvendorID, @intCustomerID = phcustomerID, @numPaymentAmt = phAmount, @intFinancialID =
phfinancialID, @intDepartmentID = phdepartmentID,
@numvendorequiamt = phcustomeramount, @intdebit = phDebitAccountID, @numdebit =
isnull(phDebitAmount,0), @dtchequedate = phchequedate, @intGoodsInTransitAccID =
phgoodsintransitaccid, @dtutime = updatetime, @numconsrate = phexchangerate,
@numdeprate = phdepexrate, @strexrates = phexchangerates, @intPaidByVendorid=phpaidbyvendorid
FROM
ahqPaymentVoucherHeader
WHERE
phpostED =0 and phCompanyID = @intCompanyID and
phcancellED =0 and phpaymentid = @intpaymentid
select
@intcurrencyid = currencyid
from
aaccountmaster where companyid =
@intcompanyid and accountid = @intBankCashID
/* finding the type of transaction */
if @strpaymentType <> ''OP'' and @strpaymentType <> ''RP'' and @strpaymentType <> ''SCP'' and @strpaymentType <> ''SPP''
begin
SELECT @numPaymentAmt = sum(pddAmount) FROM ahqPaymentVoucherdebitdetails
WHERE pddCompanyID = @intCompanyID and pddPaymentID = @intPaymentID
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID)
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid )
set @intJournalDetailID = 1
if (@strpaymentType=''SOC'') or (@strpaymentType=''j'') OR (@strpaymentType=''CDP'') OR (@strpaymentType=''SCDP'')
begin
select @numDebitAmt=sum(isnull(pddAmount,0)) FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intPaymentID
exec spConvertequiamount @intcurrencyid, ''m'', @intGoodsInTransitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output, ''''
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount,actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intGoodsInTransitAccID, (@numDebitAmt * @numconsRate),
@numresamount, @intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
if @numPaymentAmt<>0 --hari 041209
Begin
/* inserting the bank or cash */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt, @intDepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
End
end
else
begin
Declare DebitCur cursor for
SELECT pddAccountID, pddAmount, pddhqpoid FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intPaymentID
open debitcur
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt, @inthqpoid
while @@Fetch_status =0
begin
if (@strpaymentType=''LCO'') and @LCtobeAccounted = 1 --hari
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output, ''''
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate), @numresamount,
@intDepartmentID,(@numDebitAmt * @numdepRate) )
set @intJournalDetailID = @intJournalDetailID +1
end
if (@strpaymentType=''LCM'') and @LCtobeAccounted = 1
begin
if @numDebitAmt <>0  --hari 041209
Begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output, ''''
-- lc amount
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate),
@numresamount, @intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
End
set @numlcamt =0.0
select @numlcamt = isnull(pohlcamount,0.0), @intdebitaccid =
pohlcaccountid from lopurchaseorderheader where pohcompanyid =
@intcompanyid and pohpoid = @inthqpoid
exec spConvertequiamount @intDebitAccID, ''a'', @intcurrencyid,
''m'', @strexrates, @numlcamt, @numresamount output, ''''
if @numlcamt > 0.0
begin
-- debiting goods in transit
exec spConvertequiamount @intDebitAccID, ''a'',
@intdepartmentid, ''d'', @strexrates, @numlcamt,
@numdepcuramt output, ''''
set @numlcamt = @numresamount
set @numtemp = (@numlcAmt - @numDebitAmt)
exec spConvertequiamount @intcurrencyid, ''m'',
@intGoodsInTransitAccID, ''a'', @strexrates, @numtemp,
@numresamount output, ''''
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount) values (@intJournalID,
@intjournalDetailID, @intCompanyID, 0,
@intGoodsInTransitAccID, @numtemp * @numconsRate,
@numresamount, @intDepartmentID,
@numtemp * @numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID,
Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intdebitaccid,@numtemp * @numconsRate,
@numtemp,@intDepartmentID, @numtemp * @numdepRate)
set @intJournalDetailID = @intJournalDetailID +1
end
end
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt,@inthqpoid
end --for a
if not (@LCtobeAccounted=0 and (@strpaymentType=''LCO'' or @strpaymentType=''LCM''))
begin
/* inserting the bank or cash */
if isnull(@numPaymentAmt,0)<>0 --hari 041209
Begin
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt, @intDepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
END
end
select * from moaJournalDetails where journalID=@intJournalID
close DebitCur
deallocate debitcur
end
end
/*other payments*/
if ((@strpaymentType =''OP'') or
(@strpaymentType = ''LCM'' and @LCtobeAccounted = 0) or
(@strpaymentType = ''LCO'' and @LCtobeAccounted = 0)) and
(@strpaymentType <> ''SOC'' and @strpaymentType <> ''CDP'' and
@strpaymentType <> ''SCDP'' and @strpaymentType <> ''J'') or
(@strpaymentType = ''SCP'') or (@strpaymentType = ''SPP'' )
begin
if (@intvendorID is not null) and (@intPaidByVendorid is null)
begin
SELECT * FROM ahqpaymentvoucherdetails WHERE pdCompanyID = @intCompanyID and
pdPaymentID = @intPaymentID
if @@rowcount > 0
set @strType =''SS''
else
set @strType =''SA''
end
if (@intCustomerID is not null) and (@intPaidByVendorid is null)
set @strType =''C''
if (@intvendorID is null) and (@intCustomerID is null) and (@intPaidByVendorid is null)
set @strType = ''A''
if (@intPaidByVendorid is not null)
set @strType =''MV''
if (@strType =''SA'') or (@strtype =''SS'')  -- Advance Payment to the Vendor assumes that both bank
-- and vendor curruncy are the same
begin
insert into moajournalheader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid,@dtchequedate, @dtutime )
set @intJournalDetailID = 1
exec spConvertequiamount @intVendorID, ''V'', @intCurrencyID,
''m'', @strexrates, @numdebit,  @numresamount output, ''''
set @numtemp = (@numpaymentamt - @numresamount)
if @numtemp<>0 --hari 041209
Begin
exec spConvertequiamount @intcurrencyid, ''m'', @intvendorid,
''v'', @strexrates, @numtemp, @numresamount output, ''''
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, vendorID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intVendorID, @numtemp * @numconsrate,
@numresamount, @intdepartmentid, @numtemp * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
End
if (@intdebit is not null)
begin
exec spConvertequiamount @intVendorID, ''V'', @intdebit,
''a'', @strexrates, @numdebit, @numresamount output, ''''
exec spConvertequiamount @intVendorID, ''V'', @intcurrencyid,
''m'', @strexrates, @numdebit, @numdebit output, ''''
if @numdebit >0 --hari 040122
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdebit,
abs(@numdebit) * @numconsrate, abs(@numresamount),@intdepartmentid,
abs(@numdebit) * @numdeprate)
else
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount,departmentid, depamount) values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intdebit,
abs(@numdebit) * @numconsrate, abs(@numresamount), @intdepartmentid,
abs(@numdebit) * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
end
if isnull(@numPaymentAmt,0)<>0 --hari 041209
Begin
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, @numPaymentAmt * @numconsrate, @numPaymentAmt,
@intdepartmentid, @numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
End
end
if @strType =''C'' -- Customer Advance
begin
insert into moajournalheader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
exec spConvertequiamount @intcustomeriD, ''C'', @intCurrencyID,
''m'', @strexrates, @numdebit,  @numresamount output, ''''
set @numtemp = (@numpaymentamt - @numresamount)
exec spConvertequiamount @intcurrencyid, ''m'', @intcustomerid,
''c'', @strexrates, @numtemp, @numresamount output, ''''
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, customerID, Amount, actualamount,departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcustomeriD, @numtemp * @numconsrate ,
@numresamount, @intdepartmentid, @numtemp * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
if (@intdebit is not null)
begin
exec spConvertequiamount @intcustomeriD, ''C'', @intdebit,
''a'', @strexrates, @numdebit, @numresamount output, ''''
exec spConvertequiamount @intcustomeriD, ''C'', @intcurrencyid,
''m'', @strexrates, @numdebit, @numdebit output, ''''
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, accountID, Amount, actualamount, departmentid, depamount)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0, @intdebit,
@numdebit * @numconsrate , @numresamount ,@intdepartmentid,
@numdebit * @numdeprate  )
set @intJournalDetailID = @intJournalDetailID +1
end
if @numPaymentAmt<>0 --hari 041209
Begin
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (
@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intBankCashID,
@numPaymentAmt * @numconsrate, @numPaymentAmt ,@intdepartmentid,
@numPaymentAmt * @numdeprate)
set @intJournalDetailID = @intJournalDetailID +1
End
end
if @strType = ''A''
begin
SELECT @numPaymentAmt = sum(pddAmount) FROM ahqpaymentvoucherdebitdetails
WHERE pddCompanyID = @intCompanyID and pddPaymentID = @intPaymentID
insert into moajournalheader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
/* inserting the bank or cash */
if @numPaymentAmt<>0 --hari 041209
Begin
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, (@numPaymentAmt * @numconsRate),
@numPaymentAmt,@intDepartmentid, (@numPaymentAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
End
Declare DebitCur cursor for
SELECT pddAccountID, pddAmount FROM ahqPaymentVoucherdebitdetails WHERE
pddCompanyID = @intCompanyID and pddPaymentID = @intPaymentID
open debitcur
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt
while @@Fetch_status =0
begin
exec spConvertequiamount @intcurrencyid, ''m'', @intDebitAccID,
''a'', @strexrates, @numDebitAmt, @numresamount output,''D''
if @numDebitAmt <> 0 --hari 041209
Begin
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, AccountID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intDebitAccID, (@numDebitAmt * @numconsRate), @numresamount,
@intDepartmentID, (@numDebitAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
End
fetch next FROM debitcur into @intDebitAccID, @numDebitAmt
end --for a
close DebitCur
deallocate debitcur
end
if @strType = ''MV''
begin
SELECT @numPaymentAmt = sum(pvdAmount) FROM aHQPaymentVoucherVendordetails
WHERE pvdCompanyID = @intCompanyID and pvdPaymentID = @intPaymentID
insert into moajournalheader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID, chequedate, updatetime )
values (@intJournalID, @intCompanyID, @dtpaymentDate, @strPaymentNo,
@strRemarks, @intFinancialID, ''P'', @intcurrencyid, @dtchequedate, @dtutime )
set @intJournalDetailID = 1
/* inserting the bank or cash */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualamount, departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intBankCashID, (@numPaymentAmt * @numconsRate),
@numPaymentAmt,@intDepartmentid, (@numPaymentAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
Declare DebitCur cursor for
SELECT pvdVendorid,pvdAmount,pvdVendorAmount FROM
aHQPaymentVoucherVendordetails WHERE
pvdCompanyID = @intCompanyID and pvdPaymentID = @intPaymentID
open debitcur
fetch next FROM debitcur
into @intMVVendorID,@numMVAmt,@numMVVendAmt
while @@Fetch_status =0
begin
insert into moaJournalDetails (JournalID, journaldetailID,
CompanyID, JournalCrEDit, VendorID, Amount, actualamount,
departmentid, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intMVVendorID, (@numMVAmt * @numconsRate), @numMVVendAmt,
@intDepartmentID, (@numMVAmt * @numdepRate))
set @intJournalDetailID = @intJournalDetailID +1
fetch next FROM debitcur
into @intMVVendorID,@numMVAmt,@numMVVendAmt
end --for a
close DebitCur
deallocate debitcur
end
end
update ahqPaymentVoucherHeader set phpostED =1 WHERE phPaymentID = @intPaymentID and
phCompanyID = @intCompanyID
--rollback tran
end
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillBalance]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTillBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 13/Oct/2010
--Created by	: Praveen S
--Comments	: For update the Opening/Closing Balance of the Till
--          : Insert values into Till Balnce History
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spUpdateTillBalance]
@tillhisoryid INT,
@tillcurrencyid INT,
@tillamount FLOAT,
@tilloutletid INT,
@tillcompanyid INT,
@tillstatus BIT  -- 1 OPen, 0 Close
AS BEGIN
	 SET NOCOUNT ON
	 INSERT INTO tillbalancehistory
	 (till_hist_id,
	 till_currencyid,
	 till_amount,
	 till_outletid,
	 till_companyid,
	 till_status) 	
	 VALUES
	 (@tillhisoryid,
	  @tillcurrencyid,
@tillamount,
	  @tilloutletid,
@tillcompanyid,
@tillstatus)
	
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[vwAnalysisItems]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAnalysisItems]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by		: Kishore
-- Modified on 		: 13/01/2003
-- Comments             : Avoided already analysed items
--                        (On comparison with v2)      (11/06/0233)
--                      : Added ''Active = 1'' condition (13/01/2003)
------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwAnalysisItems] AS	
select vw.itemid,a.itemcode, vwi.itemdescription, a.brand, a.modelno, vw.type
from (
	SELECT itemid,''PO'' as type from moapoitems
	union all
	select distinct grditemid,''RQ'' as type
	from mosgoodsrequestdetail md, mosgoodsrequestheader mh
	where grditemid not in (select inditemid
				from ahqissuenotemain inm,ahqissuenoteheader inh,
				ahqissuenotedetail ind
				where inm.INMIssuenoteID = inh.INHIssuenotemainID
				and inh.inhissuenoteid = ind.indissuenoteid
				and inmrequestid = grhrequestid
				and inmshopid = grhshopid
				and inmcancel = 0)
	and mh.grhrequestid = md.grdrequestid
	and mh.grhshopid = md.grdshopid
	and mh.grhcancel = 0
	and grditemid not in (select distinct poditemid
				from lopurchaseorderheader lph,lopurchaseorderdetail lpd
				where lph.pohpoid=lpd.podpoid
				and pohcancel=0
				and lph.updatetime>mh.updatetime)
	and grdItemId Not In (select distinct alItemId
				From aAnalysedPoItems al
				WHERE al.UpdateTime > mh.UpdateTime)
	union all
	select distinct itemid, ''PO''
	from vwshoppendingrequestsforpo) vw,
aitem a,vwitemdescription vwi
where a.itemid = vw.itemid
and vwi.itemid = vw.itemid
and a.Active = 1'
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItemsReport]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAlreadyIssuedItemsReport]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwAlreadyIssuedItemsReport    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwAlreadyIssuedItemsReport    Script Date: 14/09/2002 12:48:08 AM ******/
/****** Object:  View dbo.vwAlreadyIssuedItemsReport    Script Date: 31/07/2002 2:00:28 PM ******/
CREATE view [dbo].[vwAlreadyIssuedItemsReport] as
select type, inhno, issdate, itemdescription, godownname, totalreserve.indgodownid,
totalreserve.indlocationid, totalreserve.inditemid, sum(totalreserve.issuedgood) issuedgood,
sum(totalreserve.issuedbad) issuedbad
from
(select ''Issue Note'' as type, inhissuenoteno inhno, inmissuedate issdate, ind.indgodownid,ind.indlocationid, ind.inditemid,sum(ind.indqty) as issuedgood,
sum(ind.indbadqty) as issuedbad from ahqissuenotedetail ind,ahqIssueNoteHeader inh ,
ahqIssuenoteMain inm where ind.indissuenoteid=inh.inhissuenoteid and
ind.indgodownid=inh.inhgodownid and inh.inhissuenotemainid=inm.inmissuenoteid and
inm.inmCancel=0 and inh.inhused=0 group by ind.indgodownid,ind.indlocationid, ind.inditemid,
Inhissuenoteno, inmissuedate
union all
--for getting the reserved quantity for special invoiced items
select ''Special Invoice'' as type, ihinvoiceno, ihinvoicedate, godownid, locationid, itemid ,
sum(qty) ,0 as issuedbad from vwspecialinvoicereserveitem
group by ihinvoiceno, ihinvoicedate, godownid, locationid, itemid) totalreserve,
vwitemdescription vw, agodown a where inditemid = vw.itemid and indgodownid = a.godownid
group by type, totalreserve.indgodownid, totalreserve.indlocationid,
totalreserve.inditemid,itemdescription, a.godownname, inhno, issdate'
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItems]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAlreadyIssuedItems]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwAlreadyIssuedItems    Script Date: 18/01/2003 9:45:37 PM ******/
/****** Object:  View dbo.vwAlreadyIssuedItems    Script Date: 14/09/2002 12:48:08 AM ******/
/****** Object:  View dbo.vwAlreadyIssuedItems    Script Date: 31/07/2002 2:00:28 PM ******/
/****** Object:  View dbo.vwAlreadyIssuedItems    Script Date: 20/11/2001 9:59:02 AM ******/
/****** Object:  View dbo.vwAlreadyIssuedItems    Script Date: 17/11/2001 9:21:41 PM ******/
-----------------------------------------------------------------------------------
--RefNo-1
--Updated By : Yogesh Joe
--Updated On : 25-01-2010
--Modification : Added the condition inh.inhCancelled=0
--Purpose : To avoid cancelled Issue notes
-----------------------------------------------------------------------------------
CREATE view [dbo].[vwAlreadyIssuedItems] as
select totalreserve.indgodownid, totalreserve.indlocationid, totalreserve.inditemid,
sum(totalreserve.issuedgood) issuedgood,
sum(totalreserve.issuedbad) issuedbad
from
(select ind.indgodownid,ind.indlocationid, ind.inditemid,sum(ind.indqty) as issuedgood,
sum(ind.indbadqty) as issuedbad from ahqissuenotedetail ind,ahqIssueNoteHeader inh ,
ahqIssuenoteMain inm where ind.indissuenoteid=inh.inhissuenoteid and
ind.indgodownid=inh.inhgodownid and inh.inhissuenotemainid=inm.inmissuenoteid and
inm.inmCancel=0 and inh.inhused=0 and inh.inhCancelled=0--RefNo-1
group by ind.indgodownid,ind.indlocationid, ind.inditemid
union all
--for getting the reserved quantity for special invoiced items
select godownid, locationid, itemid , sum(qty) ,0 as issuedbad from vwspecialinvoicereserveitem
group by godownid, locationid, itemid) totalreserve
group by totalreserve.indgodownid, totalreserve.indlocationid, totalreserve.inditemid'
GO
/****** Object:  StoredProcedure [dbo].[spUlSplInv]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlSplInv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spUlSplInv 1,8
-- Modified on  : 07/03/2004
-- Modified by  : Hariharan
-- Comment      : Inserted DepAmount and added Amount conversion
--  : Given moajournalheader insertion out side the condition of @numtotaldiscountvalue <> 0
-------------------------------------
--RefNo-2
-- Modified on      : 30-11-2010
-- Modified by      : Nidheesh P V ,jyothish
-- Comments         : Added the part of GST
------------------------------------------------------------------------------
--20-11-2011 @RetunpostingCommented varible  is used blocked  reverse posting
--09-01-2012 Taxvrible intaily set zero
CREATE  proc [dbo].[spUlSplInv]
@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 @intDiscountAccountId as int
Declare @intDepartmentId as int
Declare @numtotalinvValue as numeric(18,2)
Declare @numTotalDiscountValue as numeric(18,2)
Declare @numtotalcostValue as numeric(18,2)
Declare @intComCurId as int
Declare @intinventoryaccId as int
Declare @intcostofgoodsaccId as int
declare @intCashBankId as int
declare @bitcashinvoice as bit
declare @intGrnId as int
declare @intreturninvId as int
declare @bitreturninvposted as bit
declare @numReturnTotalAmount as numeric(18,2)
declare @strreturninvno as varchar(100)
declare @bitreturncash as bit
declare @dtutime as datetime
declare @intfailcount as int
Declare @numReturnAmount as numeric(18,2)
declare @intPlTransAccId as int
declare @intcomdeptId as int
declare @numProfitTrans as numeric(7,5)
declare @intComProfitAccId as int
declare @strzerorate as varchar(1)
declare @numDepExRate as numeric(18, 8)
declare @numConExRate as numeric(18, 8)
declare @intCurrencyId as int
declare @strExRates VarChar(250)
declare @numAccExRate Numeric(18, 2)
declare @numTransEr Numeric(18, 2)
declare @numAaccAmt Numeric(18, 2)
declare @numTemp Numeric(18, 2),
@intstocktransferaccid as int,
@numCompDepAmt as numeric(18,2)
declare @numAccEr Numeric(18, 2)
--RefNo-2-added for gst--
declare @IntCount as int
declare @TaxCurrId as int
declare @numTaxEr as numeric(18,2)
declare @TaxAcntId as int
declare @TaxCatId as int
declare @TaxAmount as numeric(18,2)
declare @CTaxAmount as numeric(18,2)
declare @DTaxAmount as numeric(18,2)
declare @TaxAccAmount as numeric(18,2)
--
declare @CTotalTaxAmount as numeric(18,2)
declare @DTotalTaxAmount as numeric(18,2)
declare @TotalTaxAmnt as numeric(18,2)
declare @TotalAccTax as numeric(18,2)
declare @RetunpostingCommented as numeric(18,2)
--------------
--RefNo-2-added for gst--
declare  @Taxtable table
(
taxTransId int,
taxShopId int,
taxCateId int,
taxAccntId int,
taxAmount numeric(18,2),            CtaxAmount numeric(18,2),
DtaxAmount numeric(18,2)
)
--RefNo-2-added for gst--
declare  @Taxtable2 table
(
taxTransId int,
taxShopId int,
taxCateId int,
taxAccntId int,
taxAmount numeric(18,2),
CtaxAmount numeric(18,2),
DtaxAmount numeric(18,2)
)
declare  @Taxtable3 table
(
taxTransId int,
taxShopId int,
taxCateId int,
taxAccntId int,
taxAmount numeric(18,2),
CtaxAmount numeric(18,2),
DtaxAmount numeric(18,2)
)
set nocount on
set @RetunpostingCommented=1
/* getting the defaults into the variables
* getting the maximum Journal Id FROM journal table */
SELECT @intJournalId = isnull(max(JournalId),0) FROM moaJournalHeader WHERE CompanyId = @intCompanyId
select @intcomcurId = currencyId from acompanymaster where companyId = @intcompanyId
select @intDiscountAccountId=discountaccountId, @intGrnId = ShopGoodsReturnNoteAccId,
@numProfitTrans = isnull(RevisedCostPricePercent,0) from ashops where ShopId = @intShopId
select @intcostofgoodsaccId = CostofGoodsId, @intInventoryaccId = inventoryId,
@intPlTransAccId = ProfitTransfercontrolacc, @intcomdeptId  = companydepartment,
@intComProfitAccId = compprofitshareacc, @strzerorate = substring(isnull(futurevc,''''),1,1)  ,
@intstocktransferaccid = stocktransfercontrolacc
from apackagesettings where companyId = @intcompanyId
set @intJournalId = @intJournalId + 1
set @intreturninvId = 0.0
set @bitreturninvposted = 0.0
set @bitreturncash = 0.0
set @numTotalDiscountValue = 0.0
set @numTotalcostValue = 0.0
set @numReturnAmount = 0.0
--RefNo-2---to insert tax cateid,tax A/C & tax amount in the table variable---
insert into @Taxtable
select idInvoiceId,ihShopid,idItemTaxCategory,TaxAccountId,isnull(sum(idItemTaxAmount),0)as TaxAmount,
sum(isnull(idItemTaxAmount,0)* ihExchangeRate) as ComTaxAmount,
sum(isnull(idItemTaxAmount,0)* ihDepExRate) as DepTaxAmount
FROM losSpecialInvoiceHeader ph inner join losSpecialInvoicedetail pd
on ph.ihShopid = pd.idShopid and ph.ihInvoiceId = pd.idInvoiceId
inner join ataxcategorymaster tc on TaxCompanyId=ph.IhCompanyId AND idItemTaxCategory=TaxId
and TaxCancelled=0 and TaxAccountable=1
WHERE ihcancelled = 0 and ihtransfinished = 1 and  ihposted = 0 and ihproforma = 0 and isnull(idItemTaxCategory,0)<>0
and ihCompanyId = @intCompanyId and ihShopId = @intShopId  ---  and ihNoofOCDetails= 0
GROUP BY idItemTaxCategory,TaxAccountId,idInvoiceId,ihShopid
insert into @Taxtable2  select *  from  @Taxtable
insert into @Taxtable3  select *  from  @Taxtable
----------
-- and ihNoofOCDetails= 0 is added
Declare splinvcur cursor for
SELECT ihinvoiceId, ihinvoiceno, ihinvoicedate, ihcustomerId,
ihremarks, ihdepartmentId,
ihfinancialId, ihsalesaccId, ihbankcashaccId, ihcashinvoice, updatetime,
ihExchangeRate, ihDepExRate, ihExchangeRates
FROM losSpecialInvoiceHeader
WHERE ihcancelled = 0 and ihtransfinished = 1 and
ihposted = 0 and ihproforma = 0 and ihCompanyId = @intCompanyId and
ihShopId = @intShopId  and ihTransFinished = 1     -- and ihNoofOCDetails= 0
open splinvcur
fetch next FROM splinvcur into @intinvoiceId, @strinvoiceno, @dtinvoicedate,
@intcustomerId, @strremarks, @intdepartmentId, @intfinancialId, @intsalesaccountId,
@intCashBankId, @bitcashinvoice, @dtutime, @numConExrate, @numDepExRate,
@strExRates
while @@Fetch_status = 0
begin
set @intreturninvId = 0
set @bitreturninvposted = 0
set @bitreturncash = 0
set @numTotalDiscountValue = 0.0
set @numTotalcostValue = 0.0
set @numReturnAmount = 0.0
if @bitcashinvoice=0
select @intCurrencyId = CurrencyId
from aCustomerMaster
where CustomerId = @intcustomerId
and CompanyId = @intCompanyId
else
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryAccId
and CompanyId = @intCompanyId
exec spReturnExRate @intCurrencyId, @strExRates,
@numTransEr output
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
--RefNo-2---------TO FIND TOTAL TAX AMOUNT AND TO DEDUCT THE AMOUNT FROM SALE A/C AMOUNT FOR EACH TRANS--
select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),@DTotalTaxAmount=sum(isnull(DtaxAmount,0))
from @Taxtable  where taxTransId=@intinvoiceId and taxShopId=@intShopId group by taxTransId,taxShopId
if @TotalTaxAmnt is null
begin
set @TotalTaxAmnt=0.00
set @CTotalTaxAmount=0.00
set @DTotalTaxAmount=0.00
end
---@TotalTaxAmnt-->in (CASH A/C or CUST A/C currency)
--TO CONVERT INTO SALE A/C CURRENCY---
select @intCurrencyid = currencyid from aaccountmaster a where
accountid = @intSalesAccountID
exec spReturnExrate @intcurrencyid, @strExRates, @numAccEr output
exec spconvertcurrency @numTransEr , @numAccEr , @TotalTaxAmnt,
@TotalAccTax output
--TO CONVERT INTO SALE A/C CURRENCY---
--RefNo-2----------------------------------------
-- 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 011212
set @intFailcount = 0
select @intFailcount = count(*) from losspecialinvoicedetail, aitem where
IdinvoiceId = @intinvoiceId and IdShopId = @intShopId and IditemId = itemId
and (Idcostprice=null or Idcostprice=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
begin --***** checking for itemrate = 0
-- to update the item rate to the gadcostprice
update losspecialinvoicedetail set Idcostprice = itemrate
from aItem
where (Idcostprice=null or Idcostprice=0) and
IdinvoiceId = @intinvoiceId and IdShopId = @intShopId and
IditemId = itemId
set @numTotalDiscountValue = 0.0
-- the amount can be minus or plus figure
SELECT @numTotalDiscountValue = sum(Idunitprice)
FROM vwShopSplInvItemAmount
WHERE IdShopId = @intShopId and
IdinvoiceId  = @intinvoiceId
group by IdShopId, IdinvoiceId
-- only the return amount, assumption if Idunitprice is minus then it is return
SELECT  @numReturnAmount = abs(sum(idQuantity * costprice)) FROM
vwShopSplInvItemAmount WHERE IdShopId = @intShopId and
IdinvoiceId  = @intInvoiceID and Idunitprice <0
group by IdShopId, IdinvoiceId
-- cost of sold items
SELECT @numTotalcostValue = isnull(sum(reqqty * IdCostPrice),0) FROM losspecialinvoicedetail invd
WHERE IdShopId = @intShopId and IdinvoiceId = @intinvoiceId and Idratetype = 0
group by IdShopId, IdinvoiceId
-- check whether this is a spl invoice which is a return and cancelled the previous spl
-- invoice that is posted already.
-- check whether the spl invoice used for return is posted
-- in case of return before despatch the invoice Id of old one is stored in "ihnoofocdetails"
select @intreturninvId = isnull(ihNoofOCDetails,0)
from losspecialinvoiceheader
where IhInvoiceId = @intinvoiceId and ihShopId = @intShopId
if (@intreturninvId > 0 ) -- this is a return which has to reversed posting
begin    -- if this invoice is posted
select @bitreturninvposted = IhPosted, @strreturninvno = IhInvoiceNo,
@bitreturncash = ihcashinvoice  from losspecialinvoiceheader where
IhInvoiceId = @intreturninvId and ihShopId = @intShopId
-- if the invoice used for return is posted then it has to be reversed
if (@bitreturninvposted = 1 and  @RetunpostingCommented=0  )
begin -- to reverse posting begin
--to find the total inv amt
set @numReturnTotalAmount=0.0
SELECT @numReturnTotalAmount = sum(Idunitprice) FROM
vwShopSplInvItemAmount WHERE IdShopId = @intShopId and
IdinvoiceId  = @intreturninvId group by IdShopId, IdinvoiceId
-- debiting the goods return and creding the cash or customer
insert into moaJournalHeader (JournalId, CompanyId, JournalDate,
referenceno, remarks,financialId,Type, CurrencyId,chequedate, updatetime) values
(@intJournalId, @intCompanyId, @dtinvoicedate, @strreturninvNo,
''Goods exchanged'', @intFinancialId,''SPI'', @intcomCurId,@dtinvoicedate, @dtutime)
set @intJournalDetailId = 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intGrnId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numReturnTotalAmount,
@numAaccAmt output
-------------------------------------------------
-- debit the return a/c
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentId)
values
(@intJournalId, @intjournalDetailId, @intCompanyId, 0,
@intGrnId, (@numReturnTotalAmount * @numConExRate)-(@CTotalTaxAmount), (@numaAccAmt-@TotalAccTax),
(@numReturnTotalAmount * @numDepExRate)-@DTotalTaxAmount,
@intDepartmentId)
------------------------------------------------
--RefNo-2---------TO POST SEPERATE TAX AMOUNT TO EACH TAX A/C-------
select @IntCount=count(*) from @Taxtable
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable where taxTransId=@intinvoiceId and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable where taxTransId=@intinvoiceId and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
-- DEBITING TO TAX ACCOUNT BECAUSE IT IS A RETURN----
set @intjournalDetailID=@intjournalDetailID+1
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@TaxAcntId, @CTaxAmount , @TaxAccAmount,
@intDepartmentID, @DTaxAmount)
end
delete from @Taxtable  where taxTransId=@intinvoiceId and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
set @intJournalDetailId = @intJournalDetailId + 1
-- if cash debit cash
if (@bitreturncash = 1)
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCashBankId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numReturnTotalAmount,
@numAaccAmt output
-- cash
-- creding customer
insert into moaJournalDetails (JournalId,
journaldetailId,
CompanyId, JournalCrEDit, AccountId,
Amount, ActualAmount, DepAmount,
DepartmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 1,
@intCashBankId,
@numReturnTotalAmount * @numConExRate,
@numReturnTotalAmount,
@numReturnTotalAmount * @numDepExRate,
@intDepartmentId)
end
else -- credit
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aCustomerMaster
where CustomerId = @intCustomerId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numReturnTotalAmount,
@numAaccAmt output
-- creding customer
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, customerId, Amount,
ActualAmount, DepAmount, departmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 1,
@intCustomerId,
@numReturnTotalAmount * @numConExRate,
@numReturnTotalAmount,
@numReturnTotalAmount * @numDepExRate,
@intDepartmentId)
end
set @intJournalDetailId = @intJournalDetailId +1
if @numTotalcostValue >0
begin
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intstocktransferaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intstocktransferaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,depAmount,departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intstocktransferaccid, @numTotalcostValue * @numConExRate ,
@numAaccAmt, @numTotalcostValue * @numDepExRate,
@intDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intcostofgoodsaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intcostofgoodsaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
-- debiting the cost of goods of shop
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, DepAmount,departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intcostofgoodsaccid, @numTotalcostValue * @numConExRate,
@numAaccAmt,@numTotalcostValue * @numDepExRate,
@intDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
end
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
if (@numTotalcostValue > 0 and @numProfitTrans <> 0)
begin
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intPlTransAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intPlTransAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
--Converting the total cost value into total Company dept Currency
exec spConvertequiamount  @intPlTransAccId, ''a'', @intcomdeptId,
''d'', @strExRates, @numAaccAmt, @numCompDepAmt output, ''''
-- credit transfer control account with shop department
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount, ActualAmount,
DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 0, @intPlTransAccId ,
@numTotalCostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numTotalCostValue * @numProfitTrans * 0.01 * @numDepExRate,
@intDepartmentId )
set @intJournalDetailId = @intJournalDetailId + 1
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEdit, AccountId, Amount, actualAmount,
DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 1, @intPlTransAccId,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numaAccAmt* @numProfitTrans * 0.01 ,
@numCompDepAmt * @numProfitTrans * 0.01,
@intcomdeptId)
-- debit company profit account with shop department
set @intJournalDetailId = @intJournalDetailId + 1
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intComProfitAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intComProfitAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
insert into moaJournalDetails
(JournalId, journaldetailId,
CompanyId, JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId, @intCompanyId, 1,
@intComProfitAccId ,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numTotalcostValue * @numProfitTrans * 0.01 * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId + 1
-- for converting the amount --->
insert into moaJournalDetails
(JournalId, journaldetailId,
CompanyId, JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 0, @intComProfitAccId ,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numCompDepAmt * @numProfitTrans * 0.01 ,
@intcomdeptId )
end
set @intjournalId = @intjournalId + 1
end --reverse posting end, which is done for the case of return before despatch
end -- end for intreturninvId > 0
--because the return and sales both are handled in same table there is a change
-- of being the net value to be zero. so if net value is zero then just update the
-- bit to posted and no posting done
-----------------end of special inv return--------------------------------------------
insert into moaJournalHeader (JournalId, CompanyId, JournalDate,
referenceno, remarks,financialId,Type, CurrencyId,chequedate, updatetime) values
(@intJournalId, @intCompanyId, @dtinvoicedate, @strinvoiceNo,
@strRemarks, @intFinancialId,''SPI'', @intcomCurId,@dtinvoicedate, @dtutime)
if (@numTotalDiscountValue <> 0 )
-- if the value of "@numTotalDiscountValue" is 0 then it is a return equal to sale
-- if > 0 then net result is sales
-- if < 0 then net result is return
begin --either sales or return
set @intJournalDetailId = 1
if (@bitcashinvoice = 0)
begin
if @numTotalDiscountValue > 0  -- then net result is sale
begin -- sales to credit
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intSalesAccountId
--------------------------------CREDIT SALE---------------------------
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTotalDiscountValue,
@numAaccAmt output
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, departmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 1,
@intSalesAccountId,
(@numTotalDiscountValue * @numConExRate)-@CTotalTaxAmount,       --RefNo-2---
(@numAaccAmt-@TotalAccTax),                                      --RefNo-2---
(@numTotalDiscountValue * @numDepExRate)-@DTotalTaxAmount,       --RefNo-2---
@intDepartmentId )
----------------------------------------------------------------------------
--RefNo-2---------TO POST SEPERATE TAX AMOUNT TO EACH TAX A/C-------
select @IntCount=count(*) from @Taxtable2
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
-- CREDITING TO TAX ACCOUNT
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@TaxAcntId, @CTaxAmount , @TaxAccAmount,
@intDepartmentID, @DTaxAmount)
end
delete from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
set @intJournalDetailId = @intJournalDetailId +1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aCustomerMaster
where CustomerId = @intCustomerId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTotalDiscountValue,
@numAaccAmt output
-- DEBITING customer
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, customerId, Amount,
ActualAmount, DepAmount, departmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 0,
@intcustomerId,
@numTotalDiscountValue * @numConExRate,
@numaAccAmt,
@numTotalDiscountValue * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId +1
end  -- for credit sale
else -- the net result is return  (ENDS OF CREDIT SALE)
begin               ------- (BEGIN OF CREDIT RETURN)
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aCustomerMaster
where CustomerId = @intCustomerId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
set @numTemp = abs(@numTotalDiscountValue)
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTemp, @numAaccAmt output
-- crediting customer
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEDit, CustomerId, Amount,
actualAmount, DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 1, @intcustomerId,
abs(@numTotalDiscountValue) * @numConExRate,
@numaAccAmt,
abs(@numTotalDiscountValue) * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId +1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intGrnId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
set @numTemp = abs(@numTotalDiscountValue)
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTemp, @numAaccAmt output
-----------------------CREDIT RETURN-----------------------
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, departmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 0, @intGrnId,
ABS((abs(@numTotalDiscountValue) * @numConExRate)-@CTotalTaxAmount) ,   ---RefNo-2--TO DEDUCT TAX AMOUNT
ABS(@numaAccAmt-@TotalAccTax),
ABS((abs(@numTotalDiscountValue) * @numDepExRate)-@DTotalTaxAmount),
@intDepartmentId )
--------------------------------------------------
--RefNo-2---------TO POST SEPERATE TAX AMOUNT TO EACH TAX A/C-------
select @IntCount=count(*) from @Taxtable2
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
-- DEBITING TO TAX ACCOUNT BECAUSE IT IS A RETURN----
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@TaxAcntId, @CTaxAmount , @TaxAccAmount,
@intDepartmentID, @DTaxAmount)
end
delete from @Taxtable2  where taxTransId=@intinvoiceId and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
set @intJournalDetailId = @intJournalDetailId +1
end --for credit return
end --for  credit check
else
begin --for cash  (FOR CASH SALE/ CASH RETURN)
if @numTotalDiscountValue > 0  -- the net result is sale
begin -- sales to credit
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intSalesAccountId
-------------------------CASH SALE-------------------------------------
exec spConvertequiamount  @intCashBankId, ''a'', @intSalesAccountId, ''a'',
@strExRates, @numTotalDiscountValue, @numAaccAmt output, ''''
/* crediing the sales account with the full invoice Amount */
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount,
ActualAmount, DepAmount, DepartmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 1,
@intSalesAccountId,
(@numTotalDiscountValue * @numConExRate)-@CTotalTaxAmount,    --RefNo-2---TO DEDUCT TAX AMOUNT--
(@numAaccAmt-@TotalAccTax),
(@numTotalDiscountValue * @numDepExRate)-@DTotalTaxAmount,
@intDepartmentId)
------------------------------------------------------------------------
--RefNo-2---------TO POST SEPERATE TAX AMOUNT TO EACH TAX A/C-------
select @IntCount=count(*) from @Taxtable2
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable2 where taxTransId=@intinvoiceId and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
-- CREDITING TO TAX ACCOUNT ----
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@TaxAcntId, @CTaxAmount , @TaxAccAmount,
@intDepartmentID, @DTaxAmount)
end
delete from @Taxtable2  where taxTransId=@intinvoiceId and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
set @intJournalDetailId = @intJournalDetailId + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCashBankId
--      exec spReturnExRate @intCurrencyId, @strExRates,
--       @numAccExRate output
--Commented by R Harikrishnan on 05/06/2003
--      exec spConvertCurrency @numTransEr, @numAccExRate,
--       @numTotalDiscountValue,
--       @numAaccAmt output
-- DEBITING cash or bank
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, accountId, Amount,
actualAmount, DepAmount,departmentId)
values (@intJournalId,@intjournalDetailId,
@intCompanyId, 0, @intCashBankId,
@numTotalDiscountValue * @numConExRate,
@numTotalDiscountValue,
@numTotalDiscountValue * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId + 1
end -- for cash sale
else -- the net result is return
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCashBankId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
set @numTemp = abs(@numTotalDiscountValue)
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTemp, @numAaccAmt output
-- crediting cash
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, departmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 1,
@intCashBankId,
abs(@numTotalDiscountValue) * @numConExRate,
abs(@numTotalDiscountValue),
abs(@numTotalDiscountValue) * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intGrnId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
set @numTemp = abs(@numTotalDiscountValue)
exec spConvertCurrency @numTransEr, @numAccExRate,
@numTemp, @numAaccAmt output
--------------CASH RETURN-----------------
/* debiting the goods return account*/
insert into moaJournalDetails (JournalId,
journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, departmentId)
values (@intJournalId,
@intjournalDetailId, @intCompanyId, 0,
@intGrnId,
ABS((abs(@numTotalDiscountValue) * @numConExRate)-@CTotalTaxAmount),
ABS(abs(@numTotalDiscountValue)-@TotalAccTax),
ABS((abs(@numTotalDiscountValue) * @numDepExRate)-@DTotalTaxAmount),
@intDepartmentId )
---------------------------------------------
--RefNo-2---------TO POST SEPERATE TAX AMOUNT TO EACH TAX A/C-------
select @IntCount=count(*) from @Taxtable3
while (@IntCount>0)
begin
select top 1 @TaxCatId=taxCateId,@TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount
from @Taxtable3 where taxTransId=@intinvoiceId and taxShopId=@intShopId order by taxCateId
if (select COUNT(*) from @Taxtable3 where taxTransId=@intinvoiceId and taxShopId=@intShopId)<> 0 --order by taxCateId
begin
--TO GET TAX EXCHANGE RATE --------------->
select @TaxCurrId = currencyid from aaccountmaster a where
accountid = @TaxAcntId
exec spReturnExrate @TaxCurrId, @strexrates, @numTaxEr output
--TO GET TAX EXCHANGE RATE <---------------
---------------------------------------
exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,
@TaxAccAmount output
------------------------------------------
set @intjournalDetailID=@intjournalDetailID+1
-- DEBITING TO TAX ACCOUNT BECAUSE IT IS A RETURN----
insert into moaJournalDetails (JournalID, journaldetailID,CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@TaxAcntId, @CTaxAmount , @TaxAccAmount,
@intDepartmentID, @DTaxAmount)
end
delete from @Taxtable3  where taxTransId=@intinvoiceId and taxShopId=@intShopId and taxCateId=@TaxCatId
set @IntCount=@IntCount-1
end
--RefNo-2-------------------------------------------
set @intJournalDetailId = @intJournalDetailId +1
end --for cash return
end --for cash
end  -- for cash or credit
-- in case of any return then the stock is added to shop, so that inventory account of shop to be increased
if @numReturnAmount > 0
begin
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intCostOfGoodsAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numReturnAmount,
@numAaccAmt output
-- crediting cost of goods sold
insert into moaJournalDetails (JournalId, journaldetailId,
CompanyId,
JournalCrEDit, AccountId, Amount, actualAmount,
DepAmount,
departmentId)
values (@intJournalId, @intjournalDetailId,
@intCompanyId, 1, @intCostOfGoodsAccId,
@numReturnAmount * @numConExRate,
@numaAccAmt,
@numReturnAmount * @numDepExRate, @intDepartmentId)
set @intJournalDetailId = @intJournalDetailId +1
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intInventoryaccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numReturnAmount,
@numAaccAmt output
/* debiting the goods return account*/
insert into moaJournalDetails (JournalId, journaldetailId,
CompanyId,
JournalCrEDit, AccountId, Amount, actualAmount,
DepAmount, departmentId)
values (@intJournalId, @intjournalDetailId,
@intCompanyId, 0,
@intInventoryaccId,
@numReturnAmount * @numConExRate,
@numAaccAmt,
@numReturnAmount * @numDepExRate,
@intDepartmentId )
set @intJournalDetailId = @intJournalDetailId +1
end -- for accounting inventory in case of any return
if @numTotalcostValue >0
Begin
if @intJournalDetailId is null
set @intJournalDetailId = 1
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intstocktransferaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intstocktransferaccid, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit,
AccountID, Amount, actualAmount,depAmount,departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intstocktransferaccid, @numTotalcostValue * @numConExRate ,
@numAaccAmt, @numTotalcostValue * @numDepExRate,
@intDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'',
@intcostofgoodsaccid, ''a'', @strExRates,
@numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'',
@intcostofgoodsaccid, ''a'', @strExRates,
@numTotalcostValue, @numAaccAmt output, ''''
-- debiting the cost of goods of shop
insert into moaJournalDetails
(JournalID, journaldetailID, CompanyID, JournalCrEDit, AccountID,
Amount, actualAmount, DepAmount,departmentID)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intcostofgoodsaccid, @numTotalcostValue * @numConExRate,
@numAaccAmt,@numTotalcostValue * @numDepExRate,
@intDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
End
-- in case of any return then the stock is added to shop, so that inventory account of shop to be increased
/* @numreturnamount <> 0
begin
-- crediting cost of goods sold
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, @intcostofgoodsaccid,
@numreturnamount, @numreturnamount, @intDepartmentID)
set @intJournalDetailID = @intJournalDetailID +1
--debiting the goods return account
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountID, Amount, actualAmount,departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,
@intInventoryaccid, @numreturnamount, @numreturnamount, @intDepartmentID )
set @intJournalDetailID = @intJournalDetailID +1
end */  --by hari to avoid duplicate posting
-- calcuating the shopwise profit transfering based on RevisedCostPricePercent
if (@numTotalcostValue > 0 and @numProfitTrans <> 0)
begin
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intPlTransAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intPlTransAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
--Converting the total cost value into total Company dept Currency
exec spConvertequiamount  @intPlTransAccId, ''a'', @intcomdeptId,
''d'', @strExRates, @numAaccAmt, @numCompDepAmt output, ''''
-- credit transfer control account with shop department
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEDit, AccountId, Amount, ActualAmount,
DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 1, @intPlTransAccId ,
@numTotalCostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numTotalCostValue * @numProfitTrans * 0.01 * @numDepExRate,
@intDepartmentId )
set @intJournalDetailId = @intJournalDetailId + 1
insert into moaJournalDetails
(JournalId, journaldetailId, CompanyId,
JournalCrEdit, AccountId, Amount, actualAmount,
DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 0, @intPlTransAccId,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numaAccAmt* @numProfitTrans * 0.01 ,
@numCompDepAmt * @numProfitTrans * 0.01,
@intcomdeptId)
-- debit company profit account with shop department
set @intJournalDetailId = @intJournalDetailId + 1
if @bitcashinvoice=0
exec spConvertequiamount  @intcustomerId, ''c'', @intComProfitAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
else
exec spConvertequiamount  @intCashBankId, ''a'', @intComProfitAccId, ''a'',
@strExRates, @numTotalcostValue, @numAaccAmt output, ''''
insert into moaJournalDetails
(JournalId, journaldetailId,
CompanyId, JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId, @intCompanyId, 0,
@intComProfitAccId ,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numTotalcostValue * @numProfitTrans * 0.01 * @numDepExRate,
@intDepartmentId)
set @intJournalDetailId = @intJournalDetailId + 1
-- for converting the amount --->
insert into moaJournalDetails
(JournalId, journaldetailId,
CompanyId, JournalCrEDit, AccountId, Amount,
actualAmount, DepAmount, DepartmentId)
values
(@intJournalId, @intjournalDetailId,
@intCompanyId, 1, @intComProfitAccId ,
@numTotalcostValue * @numProfitTrans * 0.01 * @numConExRate,
@numAaccAmt * @numProfitTrans * 0.01,
@numCompDepAmt * @numProfitTrans * 0.01 ,
@intcomdeptId )
-- for converting the amount --->
--    select @intCurrencyId = CurrencyId
--    from aAccountMaster
--    where AccountId = @intPlTransAccId @numCompDepAmt
--    exec spReturnExRate @intCurrencyId, @strExRates,
--    @numAccExRate output
--    set @numTemp =  @numTotalcostValue * @numProfitTrans * 0.01
--    exec spConvertCurrency @numTransEr, @numAccExRate,
--    @numTemp, @numAaccAmt output
-- credit transfer control account with comp department
end -- for profit trans
/* mark the record as postED */
update losspecialinvoiceheader set ihpostED =1 WHERE ihCompanyId = @intCompanyId
and ihShopId = @intShopId and ihinvoiceId = @intinvoiceId
set @intJournalId = @intJournalId + 1
end --***** checking for itemrate = 0
fetch next FROM splinvcur into @intinvoiceId, @strinvoiceno, @dtinvoicedate,
@intcustomerId, @strremarks, @intdepartmentId, @intfinancialId, @intsalesaccountId,
@intCashBankId, @bitcashinvoice, @dtutime, @numConExrate, @numDepExRate,
@strExRates
end
Close splinvcur
Deallocate splinvcur
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sPBasketSalesAnalysis]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sPBasketSalesAnalysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : SREEJITH G A
--CREATED ON : 20101102
--PURPOSE : USES TO SHOW MONTHLY, WEEKLY, YEARLY SALES BASKET
--Altered By : Nidheesh P V
--Altered on : 09/11/2010
--Comments   : Added the condition for all shops(included the condition @INTSHOPID=0)
--Added @intDeptId parameter
--SPBASKETSALESANALYSIS 1,0,''20110201'',''20110201'',0
--@intDeptId<>0 for pos report & for P&C report in dept login, and @intDeptId=0 for P&C report in company login
create PROC [dbo].[sPBasketSalesAnalysis]
@intCompanyId AS INT,
@intShopId AS INT,
@fromDate AS VARCHAR(15),
@toDate AS VARCHAR(15),
@intDeptId as int
AS
BEGIN
SELECT ''Above 5000'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and abs(ComSaleAmount)>5000) or (@intDeptId<>0 and abs(DepSaleAmount)>5000))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''4999.99 - 3500'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and abs(ComSaleAmount)>=3500) or (@intDeptId<>0 and abs(DepSaleAmount)>=3500)) AND ((@intDeptId=0 and abs(ComSaleAmount)<5000) or (@intDeptId<>0 and abs(DepSaleAmount)<5000))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''3499.99 - 2500'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=2500) or (@intDeptId<>0 and abs(DepSaleAmount)>=2500)) and ((@intDeptId=0 and  abs(ComSaleAmount)<3500) or (@intDeptId<>0 and abs(DepSaleAmount)<3500))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''2499.99 - 1500'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=1500) or (@intDeptId<>0 and abs(DepSaleAmount)>=1500))  AND ((@intDeptId=0 and  abs(ComSaleAmount)<2500 ) or (@intDeptId<>0 and abs(DepSaleAmount)<2500))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''1499.99 - 1000'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>1000) or (@intDeptId<>0 and abs(DepSaleAmount)>=1000)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<=1500) or (@intDeptId<>0 and abs(DepSaleAmount)<1500))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''999.99 - 750'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=750) or (@intDeptId<>0 and abs(DepSaleAmount)>=750)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<1000) or (@intDeptId<>0 and abs(DepSaleAmount)<1000))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''749.99 - 500'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=500) or (@intDeptId<>0 and abs(DepSaleAmount)>=500)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<750 ) or (@intDeptId<>0 and abs(DepSaleAmount)<750 ))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''499.99 - 250'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=250) or (@intDeptId<>0 and abs(DepSaleAmount)>=250)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<500 ) or (@intDeptId<>0 and abs(DepSaleAmount)<500 ))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''249.99 - 100'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and  abs(ComSaleAmount)>=100) or (@intDeptId<>0 and abs(DepSaleAmount)>=100)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<250) or (@intDeptId<>0 and abs(DepSaleAmount)<250) )
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
UNION ALL
SELECT ''99.99 - 0.00'' BASKET,ISNULL(SUM(ComSaleAmount),0) ComSaleAmount, ISNULL(SUM(DepSaleAmount),0) DepSaleAmount,
COUNT(POSHBILLID) COUNT FROM vwBasketSales
inner join ashops s on s.shopid=POSHSHOPID and (s.departmentid=@intDeptId or @intDeptId=0)
WHERE POSHBILLDATE>=@FROMDATE AND POSHBILLDATE<=@TODATE
AND ((@intDeptId=0 and abs(ComSaleAmount)>0)or (@intDeptId<>0 and abs(DepSaleAmount)>0)) AND ((@intDeptId=0 and  abs(ComSaleAmount)<100) or (@intDeptId<>0 and abs(DepSaleAmount)<100 ))
AND (POSHSHOPID=@INTSHOPID or @INTSHOPID=0) AND POSHCOMPANYID=@INTCOMPANYID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spBudgetvariance]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spBudgetvariance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spBudgetvariance   1,1,1,12,1,0,0
-- Last Modified : 10/06/2004
-- Modified by   : venkitesh
--   : For Budgeted Sales and Purchase variance
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spBudgetvariance]
(@intplanid as int,@intcompanyid as int,
@FromMonthid as int,@Tomonthid as int,
@intdepartmentid  as int=0,@PurchaseOnly  as int =0 ,
@intcategoryonly as int=0) AS
begin
set nocount on
set ansi_warnings off
Declare @intInvCurrId as int, @intDepCurrId as int, @numExchangeRate as numeric(18,8)
Create table #TempPlannedPurchaseSales
(companyid int,
departmentid int,
BudgetPlanID int,
BudgetNo VARCHAR(50),
BudgetDate datetime,
ItemID int,
itemcategory int,
Actualvalue numeric(18,2),
PlannedValue numeric(18,2),
Type varchar(2),
BudPer numeric(18,8),
Actualper numeric(18,8))
-- if @purchaseonly= 0 means sales and cost variance only if @purchaseonly=1 then
-- Purchase variance only
if @PurchaseOnly =0
Begin
Create table #Vwshopitems
(
posditemid int,
cUnitPrice numeric(18,2),
dUnitPrice numeric(18,2),
posdUnitPrice numeric(18,2),
posdquantity numeric(18,2),
posdRateType numeric(18,2),
poshBilldate datetime ,
poshbillID int,
poshBillNo varchar(50),
poshShopID int,
costprice  numeric(18,2),
dcostprice numeric(18,2),
ccostprice numeric(18,2),
typemargin varchar(1),
margin numeric(18,2),
dmargin numeric(18,2),
cmargin numeric(18,2),
Amount  numeric(18,2),
cAmount numeric(18,2),
dAmount numeric(18,2))
-- inserting into temperary tables
Insert into #Vwshopitems
select a.* from vwshopitemsales  a,ashops b where
month(poshBilldate)>= @FromMonthid and
month(poshBilldate)<= @toMonthid
and  year(a.poshBilldate)= (select bphplanyear from budgetplanheader
where bphbudgetplanid = @intplanid
and bphdepartmentid=  @intdepartmentid )
and b.shopid=a.poshShopID and b.departmentid=@intdepartmentid
-- Cost Value for Item wise entries
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
case when bpditemcategory =0 then a.itemcategoryid else bpditemcategory end
bpditemcategory, isnull(actualcostprice,0) actualcostprice,
isnull(sum(bpdICostAmt),0)plannedcostamt,''C'',0,0
from budgetplanheader,budgetitemplandetail
left outer join
(select posdItemId, isnull(sum(dcostprice*posdquantity),0) actualcostprice
from #Vwshopitems  group By posdItemId)vwshopitem on
bpdIBudgetItemID = posdItemID left outer join aitem a on
bpdIBudgetItemID = itemid  where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID = @intplanid and bpdIMonthNo >=  @FromMonthid and
bpdIMonthNo <= @toMonthid and  bphCompanyID= @intcompanyid
and bpdIBudgetItemID is not null and bpdIBudgetItemID <> 0
and bphtype=''I'' group by bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID, actualcostprice
-- Cost Value for Category wise entries
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
bpditemcategory, isnull(actualcostprice,0) actualcostprice,
isnull(sum(bpdICostAmt),0)plannedcostamt,''C'',0,0
from budgetplanheader,budgetitemplandetail
left outer join
(select ItemCategoryId, isnull(sum(dcostprice*posdquantity),0)
actualcostprice from #Vwshopitems v, aItem ai where v.posditemid = ai.itemid
group by ItemCategoryId)vwshopitem on
bpdItemCategory = ItemCategoryId where bphBudgetPlanID=bpdIBudgetPlanID
and bphBudgetPlanID = @intplanid and bpdIMonthNo >=  @FromMonthid and
bpdIMonthNo <= @toMonthid and  bphCompanyID= @intcompanyid
and isnull(bpdIBudgetItemID,0) = 0
and bphtype=''I'' group by bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo, bphBudgetDate, bpditemcategory, bphCompanyID, actualcostprice
-- Sales value Item wise entries
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,
bphBudgetDate, case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID
end bpdIBudgetItemID, case when bpditemcategory =0 then a.itemcategoryid
else bpditemcategory end bpditemcategory,
isnull(ActualSalesAmt,0) ActualSalesAmt,
isnull(sum(bpdISalesAmt),0)Plannedsalesamt,''S'',0,0
from budgetplanheader,budgetitemplandetail
left outer join
(select posdItemID, isnull(sum(dAmount),0) ActualSalesAmt from
#Vwshopitems group by PosdItemId )vwshopitem  on
bpdIBudgetItemID=posdItemID left outer join aitem a on
bpdIBudgetItemID = itemid  where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID =@intplanid and bphCompanyID=@intcompanyid
and bpdIMonthNo >=  @FromMonthid and bpdIMonthNo <= @toMonthid
and bpdIBudgetItemID is not null and bpdIBudgetItemID <> 0
and bphtype=''I'' group by  bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID, ActualSalesAmt
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphDepartmentId,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
bpditemcategory, isnull(ActualSalesAmt,0) ActualSalesAmt,
isnull(sum(bpdISalesAmt),0)Plannedsalesamt,''S'',0,0
from budgetplanheader,budgetitemplandetail
left outer join
(select ItemCategoryId, isnull(sum(dAmount),0) ActualSalesAmt
from #Vwshopitems v, aItem ai where v.posditemid = ai.itemid
group by ItemCategoryId)vwshopitem on
bpdItemCategory = ItemCategoryId
where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID = @intplanid and bpdIMonthNo >=  @FromMonthid and
bpdIMonthNo <= @toMonthid and  bphCompanyID= @intcompanyid
and isnull(bpdIBudgetItemID,0) = 0
and bphtype=''I'' group by bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate, bpditemcategory,bphCompanyID, ActualSalesAmt
/*update #TempPlannedPurchaseSales  set BudPer =(plannedvalue/ sumvalue.sumplan),
Actualper =(actualvalue/ sumvalue.sumactual)
from
(select isnull(sum(plannedvalue),0)sumplan,isnull(sum(actualvalue),0)sumactual ,type
from #TempPlannedPurchaseSales
group by type)sumvalue where #TempPlannedPurchaseSales.type= sumvalue.type         */
update #TempPlannedPurchaseSales  set BudPer =
case when sumplan<> 0 then (plannedvalue/ sumvalue.sumplan) else 0 end,
Actualper = case when sumvalue.sumactual <> 0 then
(actualvalue/ sumvalue.sumactual) else 0 end  from
(select isNULL(sum(plannedvalue),0)sumplan,isnull(sum(actualvalue),0)sumactual ,type
from #TempPlannedPurchaseSales
group by type)sumvalue where #TempPlannedPurchaseSales.type= sumvalue.type
Update #TempPlannedPurchaseSales  set BudPer = BudPer * 100, Actualper = Actualper * 100
end
else
begin
Select @intInvCurrId = m.CurrencyId from aPackageSettings a, aAccountMaster m where
a.InventoryId = m.AccountId and a.CompanyId = m.CompanyId and a.COmpanyId = @intCompanyId
Select @intDepCurrId = depCurrencyId from aDepartmentMaster where DepartmentId =
@intDepartmentID  and CompanyId =   @intCompanyID
set @numExchangeRate = 0
exec spGetExchangeRate @intCompanyId, @intInvCurrId, @intDepCurrId, @numExchangeRate OUTPUT
--Purchase details for entries item wise
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphdepartmentid,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
case when bpditemcategory =0 then a.itemcategoryid else bpditemcategory end
bpditemcategory, isnull(ActualPurchasePrice,0) ActualPurchasePrice,
isnull(sum(bpdIPurchaseAmt),0)Purchasesamt,''P'' ,0,0
from  budgetplanheader,budgetitemplandetail
left outer join (Select cdItemId,
sum(isnull(cdItemQuantity*  cdCostingPrice,0)) ActualPurchasePrice from
loacostingheader a ,loacostingdetail  b  Where   a.chCostingID = b.cdCostingID
and a.chCompanyID= @intcompanyid and chCancelled=0
and chDepartmentID= @intdepartmentid  and month(a.chCostingDate)>= @FromMonthid
and month(a.chCostingDate)<= @Tomonthid
and  year(a.chCostingDate)= (select bphplanyear from budgetplanheader
where bphbudgetplanid =@intplanid
and bphdepartmentid= @intdepartmentid) group by cdItemId)purchase  on
bpdIBudgetItemID=cdItemID
left outer join aitem a on
bpdIBudgetItemID = itemid
where bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID =@intplanid
and  bphCompanyID= @intcompanyid
and bpdIMonthNo >=  @FromMonthid and bpdIMonthNo <= @toMonthid
and bphtype=''I'' and bpdIBudgetPlanID =@intplanid and
(bpdIBudgetItemId is not null and bpdIBudgetItemId <> 0)
group by  bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate,a.itemcategoryid,bpditemcategory,bphCompanyID, ActualPurchasePrice
--Purchase details for entries Category wise
Insert into #TempPlannedPurchaseSales
select bphCompanyID,bphdepartmentid,bphBudgetPlanID,bphBudgetNo,bphBudgetDate,
case when bpdIBudgetItemID =0 then 0 else bpdIBudgetItemID end bpdIBudgetItemID,
bpditemcategory, isnull(ActualPurchasePrice,0) ActualPurchasePrice,
isnull(sum(bpdIPurchaseAmt),0)Purchasesamt,''P'' ,0,0
from  budgetplanheader,budgetitemplandetail
left outer join (Select itemCategoryId,
sum(isnull(cdItemQuantity*  cdCostingPrice,0))ActualPurchasePrice from
loacostingheader a ,loacostingdetail  b, aitem ai  Where
a.chCostingID = b.cdCostingID and a.chCompanyID= @intcompanyid and
chCancelled=0 and chDepartmentID= @intdepartmentid  and
month(a.chCostingDate)>= @FromMonthid and
month(a.chCostingDate)<= @Tomonthid and cditemid = ai.itemid and
year(a.chCostingDate)= (select bphplanyear from budgetplanheader where
bphbudgetplanid = @intplanid and bphdepartmentid= @intdepartmentid)
group by itemCategoryId) purchase  on
bpdItemCategory = purchase.itemCategoryId where
bphBudgetPlanID=bpdIBudgetPlanID and
bphBudgetPlanID =@intplanid and  bphCompanyID= @intcompanyid
and bpdIMonthNo >=  @FromMonthid and bpdIMonthNo <= @toMonthid
and bphtype=''I'' and bpdIBudgetPlanID =@intplanid and
isnull(bpdIBudgetItemID,0) = 0
group by  bpdIBudgetItemID,bphDepartmentId,bphBudgetPlanID,
bphBudgetNo,bphBudgetDate, bpditemcategory,bphCompanyID, ActualPurchasePrice
update #TempPlannedPurchaseSales  set BudPer =
case when sumplan<> 0 then (plannedvalue/ sumvalue.sumplan) else 0 end,
Actualper = case when sumvalue.sumactual <> 0 then
(actualvalue/ sumvalue.sumactual) else 0 end  from
(select isNULL(sum(plannedvalue),0)sumplan,isnull(sum(actualvalue),0)sumactual ,type
from #TempPlannedPurchaseSales
group by type)sumvalue where #TempPlannedPurchaseSales.type= sumvalue.type
Update #TempPlannedPurchaseSales  set Actualvalue = Actualvalue * @numExchangeRate,
BudPer = BudPer * 100, Actualper = Actualper * 100
end
if @intcategoryonly >0
select  max(companyid) companyid, max(departmentid) departmentid, BudgetPlanID,
max(BudgetNo) BudgetNo, max(BudgetDate) BudgetDate, 0 ItemID, itemcategory,
sum(Actualvalue) actualvalue, sum(PlannedValue) plannedvalue, Type,
sum(BudPer) budper, sum(Actualper) actualper,'''' ItemDescription,
b.CategoryNameDescription from #TempPlannedPurchaseSales T,aitemcategory b
where T.itemcategory =b.ItemCategoryID
group by BudgetPlanID,itemcategory,b.CategoryNameDescription,t.type
else  select T.*,a.ItemDescription,b.CategoryNameDescription
from  aitemcategory b,#TempPlannedPurchaseSales T
left outer join aitem a on  T.itemid=a.itemid where T.itemcategory =
b.ItemCategoryID
drop table #TempPlannedPurchaseSales
set nocount off
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRebateApproval]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRebateApproval]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------
--Created  on 	: 22/05/2003
--Created  by	: R Harikrishnan
--Comments	: For Rebate Approval transaction report
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
--Added rccancelled on 01/10/2003
-----------------------------------------------------------------
CREATE Procedure [dbo].[spRebateApproval]
	@intShopID 	as int,
	@intApprovalID	as int
as
select
	rc.rcapprovedno,rc.rcapproveddate,rc.rcapprovedby,rc.rcremarks,rc.rcCustomerSalesMargin,
	rc.rcRebatePerson,sm.sperName,rcd.rcditemid,rcd.rcdQuantity,rcd.rcdUnitPrice,
	rcd.rcdrebateamount,rcd.rcdrebateper,cm.CustomerName,itm.ItemCode,itm.ItemDescription,ih.ihInvoiceNo PONo,
	rc.rccancelled
from
	losRebateConfirmHeader rc,losRebateConfirmDetail rcd,
	losrebaterequest rr,losinvoiceheader ih, aitem itm,
	aSalesPersonMaster sm,aCustomerMaster cm
where
	rc.rcshopID=rcd.rcdShopID and rc.rcapprovedid=rcd.rcdapprovedid and
	rc.rcShopID=rr.rrShopID and rc.rcReqID=rr.rrReqID and
	rr.rrshopid=ih.ihshopid and rr.rrpoid=ih.ihInvoiceID and
	rr.rrSalesPersonID=sm.sperID and rcd.rcditemid=itm.itemid and
	ih.ihCustomerID=cm.CustomerID and rc.rcapprovedid=@intApprovalID and
	rc.rcshopid= @intShopID' 
END
GO
/****** Object:  StoredProcedure [dbo].[spRemoveTillHeader]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemoveTillHeader]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created on 	: 12/Oct/2010
--Created by	: Praveen S
--Comments	: For Removing the TillHeader
------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spRemoveTillHeader]
@tillid INT,
@tilloutletid INT,
@tillcompanyid INT
AS BEGIN
	 SET NOCOUNT ON
	 exec spRemoveTillDetails  @tillid,@tilloutletid,@tillcompanyid
--	 DELETE FROM TillCurrentStatus
--	 WHERE till_id = @tillid AND
--	 till_outletid = @tilloutletid AND
--	 till_companyid = @tillcompanyid
	 DELETE FROM TillHeader
	 WHERE till_th_tillid = @tillid AND
	 till_th_outletid = @tilloutletid AND
	 till_th_companyid = @tillcompanyid
	 SET NOCOUNT OFF
END' 
END
GO
/****** Object:  View [dbo].[vwAverageSalesQtyOfAllShopsItemWise]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAverageSalesQtyOfAllShopsItemWise]'))
EXEC dbo.sp_executesql @statement = N'
--Created by: MANUNADH. U
--Created on: 04-02-2009
--To find average sales Qty of items in all shops
CREATE view [dbo].[vwAverageSalesQtyOfAllShopsItemWise] as
SELECT VW.ITEMID ,SUM(VW.totalSalesQty)totalSalesQty,SUM(VW.noOfSalesDays)noOfSalesDays,SUM(VW.avgSalesQty)avgSalesQty FROM
(select  s1.posditemid itemID, sum(s1.posdquantity) totalSalesQty, a.noOfSalesDays,
sum(s1.posdquantity)/a.noOfSalesDays avgSalesQty from vwShopItemSales s1,
(select poshShopID, min(poshBillDate) startDate, max(poshBillDate)endDate,
datediff("d",min(poshBillDate),max(poshBillDate)) noOfSalesDays
from vwShopItemSales group by poshShopID) a
where s1.poshShopID=a.poshShopID
group by s1.poshShopID, s1.posditemid, a.noOfSalesDays)VW GROUP BY  VW.ITEMID'
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWiseForecasting]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockOutCompanyWiseForecasting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- spStockOutCompanyWiseForecasting  0,10
-- ===================================================
-- Author		:	MANUNADH. U
-- Create Date	:	02-003-2009
-- Description	:	To Get The Forecasting Stockout Items Company Wise
-- Purpose		:	Stock Out Items Automated Mailing.
-- ===================================================
CREATE PROCEDURE [dbo].[spStockOutCompanyWiseForecasting]
(
	@basedOnReorderLevel bit,
	@days  int
)
AS
BEGIN
	
	IF @basedOnReorderLevel=1
		
		BEGIN
			select distinct * from
									(
										select	a.itemId,
												itemcode,
												itemdescription,
												ic.itemcategoryid,
												ic.categorynamedescription,
												IsNull ( Stock, 0 ) stock,
												a.reorderlevel,
												a.reorderquantity,
												isnull ( v.avgSalesQty, 0 ) avgSalesQty,
												isnull (avgSalesQty, 0 ) * @days  expectedSalesQty,
												( isnull ( stock, 0 ) - isnull ( avgSalesQty, 0 ) * @days ) expectedStock,
												isnull ( c.colorname, '''''''' ) colorName,
												isnull ( s.sizename, '''''''' ) sizeName,
												isnull ( a.brand, '''''''' )brand
										From aitem a
											Left Outer Join acolor c On a.colorid = c.colorid
											Left Outer Join asize s on a.sizeid = s.sizeid
											Left Outer Join vwsellingtotalstock vs On a.itemid = vs.itemid
											Left Outer Join vwAverageSalesQtyOfAllShopsItemWise v on a.itemID = v.itemID,
											aitemcategory ic,
											vwDepWiseItems dep
										Where
											ic.itemcategoryid = a.itemcategoryid
											And a.active = 1
											And a.onetimeshipment = 0
											And dep.departmentid = 0
									) vw
			where vw.reorderlevel > vw.expectedStock
				AND IsNull ( vw.stock, 0 ) <= vw.reorderlevel
				AND vw.reorderlevel > 0
		END
	ELSE
		BEGIN
			select distinct * from
									(
										select	a.itemId,
												itemcode,
												itemdescription,
												ic.itemcategoryid,
												ic.categorynamedescription,
												IsNull ( Stock, 0 ) stock,
												a.reorderlevel,
												a.reorderquantity,
												isnull ( v.avgSalesQty, 0 ) avgSalesQty,
												isnull (avgSalesQty, 0 ) * @days  expectedSalesQty,
												( isnull ( stock, 0 ) - isnull ( avgSalesQty, 0 ) * @days ) expectedStock,
												isnull ( c.colorname, '''''''' ) colorName,
												isnull ( s.sizename, '''''''' ) sizeName,
												isnull ( a.brand, '''''''' )brand
										From aitem a
											Left Outer Join acolor c On a.colorid = c.colorid
											Left Outer Join asize s on a.sizeid = s.sizeid
											Left Outer Join vwsellingtotalstock vs On a.itemid = vs.itemid
											Left Outer Join vwAverageSalesQtyOfAllShopsItemWise v on a.itemID = v.itemID,
											aitemcategory ic,
											vwDepWiseItems dep
										Where
											ic.itemcategoryid = a.itemcategoryid
											And a.active = 1
											And a.onetimeshipment = 0
											And dep.departmentid = 0
									) vw
			where vw.reorderlevel > vw.expectedStock
				AND IsNull ( vw.stock, 0 ) <= vw.reorderlevel
				AND vw.reorderlevel >= 0
		END
END' 
END
GO
/****** Object:  View [dbo].[vwAverageSalesQtyItemWise]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAverageSalesQtyItemWise]'))
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- Created by: Regin T.
-- Created on: 09-10-2008
-- To find average sales of items in all shops.
-- This view is used in spReorderLevelForecasting.
-- spReorderLevelForecasting is for Stockout Items Forecasting report
--------------------------------------------------------------------------------
--LIMITATION OF THIS VIEW
-- Even though this view works good for those items which were added to the shop when the shop created,
-- it may not find the exact average sale of those items which was newly added to the shop later.
-- Reason is that the Total No Of Sales Days (noOfSalesDays) of given shop is used find the average of items.
--Recommended solution
-- Find the no of days that the item has been in the shop.(i.e. PackageDate - Item Added Date)
-- Use this value instead of Total No Of Sales Days (noOfSalesDays) to find the average.
-- But it would take time to compute the result.
--------------------------------------------------------------------------------
CREATE view [dbo].[vwAverageSalesQtyItemWise] as
select s1.poshShopID shopID, s1.posditemid itemID, sum(s1.posdquantity) totalSalesQty, a.noOfSalesDays,
case when a.noOfSalesDays=0 then 0 else sum(s1.posdquantity)/a.noOfSalesDays end avgSalesQty from vwShopItemSales s1,
(select poshShopID, min(poshBillDate) startDate, max(poshBillDate)endDate,
datediff("d",min(poshBillDate),max(poshBillDate)) noOfSalesDays
from vwShopItemSales group by poshShopID) a
where s1.poshShopID=a.poshShopID
group by s1.poshShopID, s1.posditemid, a.noOfSalesDays
------------------------------------------------'
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecastingMailAlert]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spReorderLevelForecastingMailAlert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===================================================
-- Author		:	MANUNADH. U
-- Create Date	:	25-03-2009
-- Description	:	To Get The Inventory Forecast Report Company Wise
-- Purpose		:	Stock Out Items Automated Mailing.
-- ===================================================
--------------------------------------------------------------------------------
--Steps:	
--1.	Find the average sales
--2.	Find the current stock of each item
--3.	Find the difference between package date and the given future date.
--4.	Find the future stock level using below formula.
--		Future Stock = Current Stock - Avg. Sales per day * No.of days between package date and given future date.
--5.	If the future stock is less than reorder level then display that item.
--6.	Avg.Sales
--------------------------------------------------------------------------------
--   [dbo].[spReorderLevelForecastingMailAlert]1
CREATE PROCEDURE [dbo].[spReorderLevelForecastingMailAlert]
(	
	@days  int	-- No. of days in between package date and asOnDate
)
AS
	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT
		d.itemid,
		itemcode,
		itemdescription,
		convert(numeric(18,2),d.itemreorderlevel) itemreorderlevel,
		convert(numeric(18,2),d.reorderquantity) reorderquantity,
		d.shopid,
		ic.categorynamedescription,
		ic.itemcategoryid,
		isnull(c.colorname,'''''''') colorname,
		a.brand,
		isnull(z.sizename,'''''''') sizename,
		convert(numeric(18,2),isnull(Stock,0)) stock,
		convert(numeric(18,2),isnull(v.avgSalesQty,0))  avgSalesQty,
		convert(numeric(18,2),isnull(avgSalesQty,0) * convert(varchar, @days))   expectedSalesQty,
		convert(numeric(18,2),(isnull(avgSalesQty,0) * convert(varchar, @days)) + d.itemreorderlevel) expectedStock,
		convert(numeric(18,2),isnull(Stock,0)  / ( case  when v.avgSalesQty is null or  v.avgSalesQty =0 then 1 else  v.avgSalesQty end )) SuffPhysicalBalance
		--isnull(stock,0) - isnull(avgSalesQty,0) *  convert(varchar, @days)  expectedStock
	FROM
		aitem  a
			left outer join acolor c ON a.colorid=c.colorid
			left outer join asize z on a.sizeid=z.sizeid, aShopItemDetail d
			left outer join vwinquiryshopstock ss on d.shopid = ss.shopid  and d.itemid = ss.itemid
			left outer join vwAverageSalesQtyItemWise v on  d.shopid=v.shopID and d.itemID=v.itemID, aitemcategory ic
	WHERE
		a.itemid=d.itemid and
		a.itemcategoryid= ic.itemcategoryid
		and itemreorderlevel>isnull(stock,0)-isnull(avgSalesQty,0) * convert(varchar, @days)
END' 
END
GO
/****** Object:  View [dbo].[vwhqposbillsettlementdetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqposbillsettlementdetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwhqposbillsettlementdetails    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwhqposbillsettlementdetails    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwhqposbillsettlementdetails    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwhqposbillsettlementdetails    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwhqposbillsettlementdetails    Script Date: 17/11/2001 9:22:01 PM ******/
-- Last Modified on: 18/10/01
-- Modified by     : leo
CREATE view [dbo].[vwhqposbillsettlementdetails] as
select vsh.CompanyID, vsh.DepartmentID,vsd.shopid, vsd.lphbillid, max(vsh.vsdate) settleddate,
sum(SettlementAmount) as paidamount from vendorsettlementheader vsh, vendorsettlementdetail vsd
where vsh.companyid = vsd.companyid and vsh.vsid = vsd.vsid and vsh.cancelled = 0 and
vsd.lphbillid is not null
group by vsh.CompanyID, vsh.DepartmentID,vsd.shopid, vsd.lphbillid'
GO
/****** Object:  View [dbo].[vwHQPBillVendrPayments]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPBillVendrPayments]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 17/11/2001 9:22:01 PM ******/
/****** Object:  View dbo.vwHQPBillVendrPayments    Script Date: 16/06/2001 15:36:34 ******/
CREATE view [dbo].[vwHQPBillVendrPayments] as
select vh.companyid, vh.vendorid, 0 as shopid, vd.pbhbillid,0.0 as billamount,
sum(vd.settlementamount) as paidamount from VENDORSETTLEMENtheader vh, vendorsettlementdetail vd
where vh.companyid=vd.companyid and vh.vsid=vd.vsid and vh.cancelled=0 and
vd.pbhbillid is not null group by vh.companyid, vh.vendorid, vd.pbhbillid'
GO
/****** Object:  StoredProcedure [dbo].[spDailyItemSalesFandB]    Script Date: 10/06/2012 14:17: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].[spDailyItemSalesFandB]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spDailyItemSalesFandB 5,''20101001''
-- Created On  : 22/10/2010
-- Created By  : Nidheesh P V
-- Comments    : To show details in daliy sales item report for FandB shop
CREATE PROCEDURE [dbo].[spDailyItemSalesFandB] @intShopID as int, @strDate as varchar(10) AS
-----for dishAdds[sd.DishType=''DishAdd''] (dishid in aitem)
SELECT posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sum(sd.posdquantity) posdQuantity,
sd.poshBillDate, sd.poshShopId, sd.Type, s.ShopName, a.ItemCode, a.ItemDescription,
costprice, cCostPrice, dCostPrice, z.SizeName, u.UnitCode, c.ColorName,
MIN(sid.sellingprice) SellingPrice,
MIN(sid.wholesaleprice) WholeSalePrice, MIN(sid.discountprice ) DiscountPrice,
A.ItemCode, SUM(Amount) Amount, SUM(cAmount) cAmount, SUM(dAmount) dAmount,
a.Brand, ic.CategoryNameDescription, cm.Symbol SpCurrencySymbol,a.part_code,
isnull(m.CustomCategoryPercent,0.00)CustomCategoryPercent,s.futurevarchar
FROM vwShopItemSalesFandB sd inner Join
(SELECT sd.ItemId, sd.Shopid, MIN(SellingPrice) SellingPrice,
MIN(WholeSalePrice) WholeSalePrice, MIN(DiscountPrice) DiscountPrice, sd.CurrencyId
FROM vwShopItemShipmentDetail sd inner join vwitemretailpacking pd
on sd.itemid = pd.itemid AND sd.Packingtypeid = pd.packingTypeId
inner join aCompanyMaster c on sd.CurrencyId=c.CurrencyId
GROUP BY Sd.ItemId, Sd.ShopId, sd.CurrencyId
) sid
ON sd.posditemid = sid.itemid
AND sd.poshshopid = sid.shopid and sd.DishType=''DishAdd''
LEFT OUTER JOIN aCurrencyMaster cm
ON sid.CurrencyId = cm.CurrencyId,
aShops s, aUnit u, aItem a
LEFT OUTER JOIN aColor c ON a.ColorID = c.ColorID
LEFT OUTER JOIN aSize z ON a.SizeID = z.SizeID
LEFT OUTER JOIN acustomsmaster m on  m.CustomID=a.CustomID, aItemCategory ic
WHERE sd.poshShopID = s.ShopID
AND a.UnitsID = u.UnitID
AND posdItemID = a.itemid
AND sd.poshShopID = @intShopID
AND sd.poshBilldate = @strDate
AND a.ItemCategoryId = ic.ItemCategoryId
GROUP BY s.ShopName, sd.poshBilldate, sd.poshShopID, sd.type,
a.Brand, ic.CategoryNameDescription,
a.ItemCode, a.ItemDescription, z.SizeName,
u.UnitCode, c.ColorName, sd.posdunitprice, sd.cUnitPrice, sd.dUnitPrice,
sd.costprice, sd.cCostPrice, sd.dCostPrice, posditemid, cm.Symbol,a.part_code,m.CustomCategoryPercent,s.futurevarchar
union all
-----for dish[sd.DishType=''Dish''] (dishid in FB_Dishdetails)
SELECT posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sum(sd.posdquantity) posdQuantity,
sd.poshBillDate, sd.poshShopId, sd.Type, s.ShopName, dd.fb_dd_dishcode, dd.fb_dd_dishname,
sd.costprice, sd.cCostPrice, sd.dCostPrice,
''''SizeName, ''''UnitCode, ''''ColorName,
Price.SellingPrice,Price.WHoleSalePrice,Price.SellingPrice as DiscountPrice,
dd.fb_dd_dishcode,SUM(Amount) Amount, SUM(cAmount) cAmount, SUM(dAmount) dAmount,
''''Brand, ''''CategoryNameDescription, ''''SpCurrencySymbol,''''part_code,
''0.00''CustomCategoryPercent,s.futurevarchar
FROM vwShopItemSalesFandB sd inner join
FB_Dishdetails dd on fb_dd_dishid=posditemid and sd.DishType=''Dish''
inner join ashops s on shopid=poshshopid
inner join
(select seg_detail_dishid,sum(SellingPrice)SellingPrice,sum(WHoleSalePrice)WHoleSalePrice from
(
select seg_detail_dishid, seg_header_name,
case when seg_header_name=''SellingPrice'' then sum(seg_detail_dish_sp_fig) end SellingPrice,
case when seg_header_name=''WHoleSalePrice'' then sum(seg_detail_dish_sp_fig) end WHoleSalePrice
from DishSegmentHeader dsh inner join DishSegmentDetail dsd on seg_header_id=seg_detail_header_id
group by seg_header_name,seg_detail_dishid
)a
group by seg_detail_dishid
)Price on posdItemId=seg_detail_dishid
AND sd.poshShopID = @intShopID
AND sd.poshBilldate = @strDate
GROUP BY posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sd.poshBillDate, sd.poshShopId, sd.Type, s.ShopName, fb_dd_dishcode, dd.fb_dd_dishname,
costprice, cCostPrice, dCostPrice,s.futurevarchar,Price.SellingPrice,Price.WHoleSalePrice' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDailyItemSales]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailyItemSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- spDailyItemSales 11, ''20080715''
-- Created On  : 30/12/2003
-- Created By  : Kishore
-- Comments    : Created from v2 for rptShopDailyItemSalesPerUnitPrice.rpt
--Modifed by dheena adding partcode
-- Modified by : Jyothis
--Modified on :09-10-09
--comments :to consider while calculating costprice and profit(requirement for ECHOCHEM)
-----------------------------------------------------------------------------------------------
--Modified By : Yogesh Joe(11-03-2010)
--Replaced losShopItemShipmentDetail with vwShopItemShipmentDetail.Because if an item having sp fixed both at HQ and Shops,
--then losShopItemShipmentDetail will return two records.It will lead to doubling the quatity.
----------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by : Regin T.
-- Modified on : 16-03-2010
-- Comments    :
-- Item repetition happened if prices are fixed in more currencies.
-- So the code was modified to get the prices fixed only in company currency.
--------------------------------------------------------------------------------
-- Modified by : Regin T.
-- Modified on : 27-09-2010
-- Refer       : RefNo-2
-- Comments    :
-- If company currency is different from department currency, selling prices
-- are not displayed. So selling prices fixed in dept currency are displayed
-- instead of company currency.
--------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spDailyItemSales] @intShopID as int, @strDate as varchar(10) AS
SELECT posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sum(sd.posdquantity) posdQuantity,
sd.poshBillDate, sd.poshShopId, sd.Type, s.ShopName, a.ItemCode, a.ItemDescription,
costprice, cCostPrice, dCostPrice, z.SizeName, u.UnitCode, c.ColorName,
MIN(sid.sellingprice) SellingPrice,
MIN(sid.wholesaleprice) WholeSalePrice, MIN(sid.discountprice ) DiscountPrice,
A.ItemCode, SUM(Amount) Amount, SUM(cAmount) cAmount, SUM(dAmount) dAmount,
a.Brand, ic.CategoryNameDescription, cm.Symbol SpCurrencySymbol,a.part_code,
isnull(m.CustomCategoryPercent,0.00)CustomCategoryPercent,s.futurevarchar
FROM vwShopItemSales sd LEFT Outer Join
-- TO GET ITEM PRICES
-- Below code caused item repetition if prices are fixed in more currencies.
-- So below code was modified to get the prices fixed only in company currency.
-- By Regin On 16-03-2010
--(SELECT sd.ItemId, sd.Shopid, MIN(SellingPrice) SellingPrice,
-- MIN(WholeSalePrice) WholeSalePrice, MIN(DiscountPrice) DiscountPrice, CurrencyId
-- FROM vwShopItemShipmentDetail sd, vwitemretailpacking pd
-- WHERE sd.itemid = pd.itemid
-- AND sd.Packingtypeid = pd.packingTypeId
-- GROUP BY Sd.ItemId, Sd.ShopId, sd.CurrencyId) sid
(SELECT sd.ItemId, sd.Shopid, MIN(SellingPrice) SellingPrice,
MIN(WholeSalePrice) WholeSalePrice, MIN(DiscountPrice) DiscountPrice, sd.CurrencyId
FROM vwShopItemShipmentDetail sd inner join vwitemretailpacking pd
on sd.itemid = pd.itemid AND sd.Packingtypeid = pd.packingTypeId
--inner join aCompanyMaster c on sd.CurrencyId=c.CurrencyId
inner join aDepartmentMaster d on sd.CurrencyId=d.depcurrencyid  -- RefNo-2
GROUP BY Sd.ItemId, Sd.ShopId, sd.CurrencyId ) sid
ON sd.posditemid = sid.itemid
AND sd.poshshopid = sid.shopid
LEFT OUTER JOIN aCurrencyMaster cm
ON sid.CurrencyId = cm.CurrencyId,
aShops s, aUnit u, aItem a
LEFT OUTER JOIN aColor c ON a.ColorID = c.ColorID
LEFT OUTER JOIN aSize z ON a.SizeID = z.SizeID
LEFT OUTER JOIN acustomsmaster m on  m.CustomID=a.CustomID, aItemCategory ic
WHERE sd.poshShopID = s.ShopID
AND a.UnitsID = u.UnitID
AND posdItemID = a.itemid
AND sd.poshShopID = @intShopID
AND sd.poshBilldate = @strDate
AND a.ItemCategoryId = ic.ItemCategoryId
GROUP BY s.ShopName, sd.poshBilldate, sd.poshShopID, sd.type,
a.Brand, ic.CategoryNameDescription,
a.ItemCode, a.ItemDescription, z.SizeName,
u.UnitCode, c.ColorName, sd.posdunitprice, sd.cUnitPrice, sd.dUnitPrice,
sd.costprice, sd.cCostPrice, sd.dCostPrice, posditemid, cm.Symbol,a.part_code,m.CustomCategoryPercent,s.futurevarchar' 
END
GO
/****** Object:  View [dbo].[vwImportRegister]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwImportRegister]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------------
--Created by  : Shinu
--Created on  : 04/02/2008
--Purpose     : For Reports Import Purchase Details
------------------------------------------------------------------------------------------------------------------------
--Modified by :
--Modified on :
--Purpose     :
------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwImportRegister] AS
select pbhDepartmentID,PbhVendorID,pbdbillID,pbhBillNo,vw.pbhbillDate, ''FOB VALUE'' Type,
sum(pbdItemQuantity*pbdItemUnitPrice*pbhinvaccexrate)Amount from vwPurchaseBillDetail vw
INNER JOIN LOspPurchaseBillHeader pb ON  pb.pbhbillID=vw.pbdbillID
group by pbdbillID,pbhBillNo,vw.pbhbillDate,pbhDepartmentID,PbhVendorID
Union All
select pbhDepartmentID,PbhVendorID,chBillID,pbhBillNo,pbhbillDate,AccountDesc,sum(cadAmount) from
loacostingaccountdetails INNER JOIN aAccountMaster ON cadAccountID=AccountID
INNER JOIN (select pbhDepartmentID,chCostingID,chBillID,pbhBillNo,pbhbillDate,PbhVendorID from
loacostingHeader INNER JOIN LOspPurchaseBillHeader
ON pbhbillID=chBillID where chcancelled=0 )PBill ON cadCostingID=chCostingID
group by  chBillID,AccountDesc,pbhBillNo,pbhbillDate,pbhDepartmentID,PbhVendorID'
GO
/****** Object:  View [dbo].[vwshopsaleinvoicereceipt]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopsaleinvoicereceipt]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopsaleinvoicereceipt    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshopsaleinvoicereceipt] as
select rh.companyid, rd.posaccountsinvoiceid, max(rh.receiptdate) receiptdate, rd.shopid,
rh.customerid, null departmentid, 0.0 as invoiceamt, sum(amountreceived) settledamt from
receiptvoucherheader rh, receiptvoucherdetails rd where rh.companyid=rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled = 0 and rd.posaccountsinvoiceid is not null
group by
rh.companyid, posaccountsinvoiceid, rd.shopid, rh.customerid'
GO
/****** Object:  View [dbo].[vwshoppurchasePayments_OLD]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchasePayments_OLD]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshoppurchasePayments    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
CREATE view [dbo].[vwshoppurchasePayments_OLD] as
--Bfore Updation Loal Purchase Settlement in Vendosettlement.
select ph.phcompanyid, pdshopid, ph.phvendorid, pd.pdposlpbillid,0.0 as billamount,
sum(pd.pdpaidamount) as paidamount, sum(pd.pdpaidamount) * phexchangerate cpaidamount,
sum(pd.pdpaidamount) * phdepexrate dpaidamount from ahqpaymentvoucherheader ph,
ahqpaymentvoucherdetails pd where ph.phcompanyid=pd.pdcompanyid and
ph.phpaymentid=pd.pdpaymentid and ph.phcancelled=0 and
pd.pdposlpbillid is not null group by ph.phcompanyid, ph.phvendorid, pd.pdshopid,
pd.pdposlpbillid, phexchangerate, phdepexrate'
GO
/****** Object:  View [dbo].[vwshoppurchasePayments]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshoppurchasePayments]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------
/****** Object:  View dbo.vwshoppurchasePayments    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
--MODIFIED BY		: PRASANTH
--LAST MODIFIED ON  : 17-12-2009
--MODIFIED FOR      : IN VENDOR SETTLEMENT LOCAL PURCHASE FROM SHOPS CAN SETTLE. BUT WHEN COUNTING THE TOTAL
--					  SETTLED AMOUNT,IT TAKING ONLY FROM HQ PAYMENT SETTLEMENT. TO SOLVE THIS VENDOR SETTLEMENT DETAIL ALSO
--					  TAKEN
-----------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwshoppurchasePayments] as
select  phcompanyid , pdshopid, phvendorid,pdposlpbillid,sum(billamount) billamount ,
sum(paidamount) paidamount,sum(cpaidamount) cpaidamount,sum(dpaidamount) dpaidamount from
(
select ph.phcompanyid , pdshopid, ph.phvendorid, pd.pdposlpbillid,0.0 as billamount,
sum(pd.pdpaidamount) as paidamount, sum(pd.pdpaidamount) * phexchangerate cpaidamount,
sum(pd.pdpaidamount) * phdepexrate dpaidamount from ahqpaymentvoucherheader ph,
ahqpaymentvoucherdetails pd where ph.phcompanyid=pd.pdcompanyid and
ph.phpaymentid=pd.pdpaymentid and ph.phcancelled=0 and
pd.pdposlpbillid is not null group by ph.phcompanyid, ph.phvendorid, pd.pdshopid,
pd.pdposlpbillid, phexchangerate, phdepexrate
union all
select h.CompanyID phcompanyid,d.shopid pdshopid,h.VendorID phvendorid,d.lphbillid pdposlpbillid,0.0 as billamount,sum(d.SettlementAmount) paidamount,
sum(d.SettlementAmount) cpaidamount ,sum(d.SettlementAmount)dpaidamount
from vendorsettlementheader h inner join vendorsettlementdetail d on h.VSID=d.VSID
and h.CompanyId=d.CompanyID and h.Cancelled=0 --where vendorid=4
group by h.CompanyID,h.VendorID,d.shopid,d.lphbillid
) A
GROUP BY phcompanyid , pdshopid, phvendorid,pdposlpbillid'
GO
/****** Object:  View [dbo].[vwLPBillVendrPayments]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLPBillVendrPayments]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Ref.No.1
--Modified By :Jyoyhish(Reference written By Aadyakumar.D.V)
--Reference On:01/11/20011
--Comment     : Condition "vh.shopid=vd.shopid " is commeted,because vd.shopid may contains "NULL"
CREATE view [dbo].[vwLPBillVendrPayments] as
select vh.companyid, vh.vendorid, vd.shopid , vd.lphbillid,0.0 as billamount,
sum(vd.settlementamount) as paidamount from VENDORSETTLEMENtheader vh, vendorsettlementdetail vd
where vh.companyid=vd.companyid and vh.vsid=vd.vsid and vh.cancelled=0 and
--vh.shopid=vd.shopid and --Ref.No.1
vd.lphbillid is not null group by vh.companyid, vd.shopid , vh.vendorid, vd.lphbillid'
GO
/****** Object:  View [dbo].[vwHqPurchasePayments]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchasePayments]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by 	: Kishore
-- Modified on	: 05/09/2003
-- Comments     : Added the LC entries also
---------------------------------------------------------------------------------------------
-- Modified by	: Kishore
-- Modified on	: 19/09/2003
-- Comments	: Replaced the pddAmount with pddCustomerAmount in aHqPaymentVoucherDebitDetails
-- Modified by	: hari	
-- Modified on	: 26/10/2003
-- Comments	: removed shop group by clause
---------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwHqPurchasePayments] AS
select
	phCompanyId, phVendorId,
	pdBillsId, 0.0 as BillAmount,
	sum(PaidAmount) as PaidAmount
From
	(select
		ph.phCompanyId, ph.phVendorId,
		pd.pdBillsId,0.0 as BillAmount,
		pd.pdpaidamount as PaidAmount, pdShopId
	from
		aHqPaymentVoucherHeader ph, aHqPaymentVoucherDetails pd
	where
		ph.phcompanyid = pd.pdcompanyid
		and ph.phpaymentid = pd.pdpaymentid
		and ph.phcancelled = 0
		and pd.pdbillsid is not null
	--
	UNION ALL
	--
	select
		ph.phcompanyid, ph.phvendorid,
		b.pbhBillId, 0.0 as billamount,
		pdd.pddCustomerAmount as paidamount, 0 pdShopId
	from
		aHqPaymentVoucherHeader ph, aHQPaymentVoucherDebitDetails pdd,
		lospPurchaseBillHeader b, MiscSettings s
	where
		ph.phcompanyid = pdd.pddcompanyid
		and ph.phpaymentid = pdd.pddpaymentid
		and pdd.pddhqpoid = b.pbhPOId
		and ph.phcancelled = 0
		and b.pbhBillId is not null
		and s.LcToAccount = 0
		and ph.phLcPayment in (''LCM'', ''LCO'')) a	
group by
	a.phcompanyid, a.phvendorid, a.pdbillsid'
GO
/****** Object:  View [dbo].[vwReceiptSettlementNo]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwReceiptSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Created by     :    Kishore
-- Created on     :    25/11/2003
-- Comments       :    Created to be used in vwSupplierLedger
--                     Gets the last reference no and sum of amount paid.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Created by     :    VinothMurugan V
-- Created on     :    08/11/2010
-- Comments       :   Adding Confimation Bit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwReceiptSettlementNo] AS
select companyid, vendorid, max(setdate) setdate, max(refno) refno,
ReceiptId, sum(PaidAmount) PaidAmount
from
(select vh.companyid, vh.vendorid, vh.vsdate setdate, vh.vsno refno,
vd.receiptid ReceiptId, SettlementAmount PaidAmount
from vendorsettlementheader vh, vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid
and vd.receiptid is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, ph.phvendorid, ph.phpaymentdate setdate,
ph.phpaymentno refno, pd.pdReceiptId, pdPaidAmount PaidAmount
from AHQpaymentvoucherheader ph, AHQpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pdReceiptId is not null and ph.phConfirmed = 1) SettledReceipts
group by companyid, vendorid, ReceiptId'
GO
/****** Object:  View [dbo].[vwreceiptlisting]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreceiptlisting]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Last Modified on  : 28/12/02
--Modified by   : dheena,Aadyakumar
--Comments   : add dep id
--Modified by   : venki 290083 ,Shinu 14062007 @sonee ,jyothish S R  19112010
--Comments   : removed the customerid link  ,Added Amount and added Isnull to Debitamount,Added AccountDesc
--multiple recipt is added
--Verified by       : Hariharan
--Verified Date      : 03/05/2004 (verified From Client DB)
--------------------------------------------------------------------------------------------
--RefNo.1
--Modified by   : Bijesh.B
--Modified date : 17/08/2011
--Ticket Id     : SEN-620602
--Description   : Receipt Amount is not tally with Daily sales and collection
--                summary report(Dep.wise)
--------------------------------------------------------------------------------------------
CREATE view [dbo].[vwreceiptlisting] as
	select rh.companyid, receiptid, receiptno, receiptdate, rh.receivedfrom,
	 convert(varchar(250),remarks) remarks, bankcashaccountid, customerid,Amount,
	isnull(debitamount,0)debitamount, customeramount, case when cancelled = 1 then ''Yes'' else ''No'' end cancelled,
	cancelledremarks,rh.departmentid,acc.AccountDesc from
	receiptvoucherheader rh, aaccountmaster acc
	where acc.companyid = rh.companyid  and
	rh.companyid = acc.companyid and rh.bankcashaccountid = acc.accountid
	and receiptid  not in(select     ReceiptId from ReceiptVoucherCustomerDetails)
union
	select
	 rh.companyid,rh.receiptid, receiptno,  rh.receiptdate ,rh.receivedfrom,
	convert(varchar(250),remarks) remarks, bankcashaccountid,rd.CustomerId, rd.Amount,
	 isnull(debitamount,0)debitamount,rd.CustomerAmount ,case when cancelled = 1 then ''Yes'' else ''No'' end cancelled,
	 cancelledremarks,rh.departmentid,acc.AccountDesc
	from
	 receiptvoucherheader rh, ReceiptVoucherCustomerDetails rd, acustomermaster c ,
	 aaccountmaster acc
	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
	   and rh.companyid = acc.companyid and rh.bankcashaccountid = acc.accountid
-- RefNo.1 start
union
	select drcompanyid, drId,drNo, drdate,cm.CustomerName,
	convert(varchar(250),drremarks) remarks, 0 bankcashaccountid,drcustomerid customerid,drAmount,
	0 debitamount,drAmount as customeramount,
	case when drcancelled = 1 then ''Yes'' else ''No'' end cancelled,
	drcancelledremarks cancelledremarks,drdepartmentid departmentid,'''' AccountDesc
	from losDummyReceiptHeader rh, acustomermaster cm
	where drcancelledremarks IS NULL and
	rh.drcustomerid = cm.customerid
	and rh.drcompanyid = cm.companyid
-- RefNo.1 ends'
GO
/****** Object:  View [dbo].[vwrebatePO]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwrebatePO]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwrebatePO    Script Date: 18/01/2003 9:45:38 PM ******/
CREATE view [dbo].[vwrebatePO] as
select rcshopid,rcapprovedid,rcapprovedno,rrpoid,rcditemid,rcdrebateamount
from losrebaterequest
,losrebateconfirmheader,losrebateconfirmdetail where
rrreqid=rcreqid and rrshopid =rcshopid
and rcdshopid=rcshopid and rrcancelled=0
and rcapprovedid=rcdapprovedid'
GO
/****** Object:  View [dbo].[vwPurchaseOrderVendorWisePre]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderVendorWisePre]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------
--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
/****** Object:  View [dbo].[vwPurchaseOrderVendorWise]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseOrderVendorWise]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------
--Created By   : Sreejith G A
--Created Date : 20100505
--Comment       : Used for printing foreign PO vendorwise with purchase amount and sub total for each vendor
----------------------------------------------------------------
CREATE view [dbo].[vwPurchaseOrderVendorWise] 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.pohquotconfirmed, a.pohpoonhold,
c.purchaseAmount ,isnull(remarks,'''') remarks,vwpo.ShopRequetNO as ShopRequetNO,vwpo.HQRequestNo as HQRequestNo,
vwpo.QuotationNO as QuotationNo,a.pohPrePurchaseid,vwpo.PrePurchaseNO as PrePurchaseNo
from loPurchaseOrderHeader 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 a.pohcancel=0'
GO
/****** Object:  View [dbo].[vwpurchasetransflow]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchasetransflow]'))
EXEC dbo.sp_executesql @statement = N'
--select * from vwpurchasetransflow where pohpoid<>0 and pohDepartmentID=1 and pohpodate >= ''20101207'' and left(pohtype,1)= ''Q''  and  pohPoID=40
----------------------------------------------------------------
--Modified By   : Benzigar S D
--Modified Date : 04102008
--Comment       : Added Pre Purchase No
----------------------------------------------------------------
--RefNo-01
--Modified By   : VinothMurugan V
--Modified Date : 2010-07-28
--Comment       : Added Approved Column
----------------------------------------------------------------
--Modified By   : Sreejith G A
--Modified Date : 2010-10-20
--Comment       : Added ls.Type in the view
----------------------------------------------------------------
CREATE  view [dbo].[vwpurchasetransflow] as
select a.pohpoid,a.pohpono,a.pohpodate,b.vendorname,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,c.purchaseAmount,a.pohdeliveryaddr, a.pohremarks, case a.pohpogenerated when 1 then ''Yes'' --,a.pohvalue
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.pohquotconfirmed, a.pohpoonhold,a.pohvalue,--c.purchaseAmount ,
isnull(remarks,'''') remarks,case when a.pohrequestid is not null then mos.Grhrequestno end as ShopRequetNO,
case when a.pohQuotationid is null then '''' end as HQRequestNo,
case when a.pohQuotationid is null then '''' end as QuotationNo,a.pohPrePurchaseid,case when a.pohprepurchaseid is null then '''' end as PrePurchaseNo,
case  isnull(a.pohApproved,0) when 1 then ''Yes'' when 0 then ''No'' end as pohApproved,ls.Type  --RefNo-01
from loPurchaseOrderHeader a inner join  avendormaster b on  a.pohvendorid=b.VendorID left outer join mosgoodsrequestheader mos on a.pohrequestid=mos.grhrequestid and a.pohshopid =mos.grhshopid
left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
left outer join purchsetracking vw on a.pohpoid=vw.pohquotationid
left outer join lostype ls on a.pohtypeid=ls.typeid
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=''R''
union
(select a.pohpoid,a.pohpono,a.pohpodate,b.vendorname,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,c.purchaseAmount,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.pohquotconfirmed, a.pohpoonhold, a.pohvalue ,
isnull(remarks,'''') remarks,vwq.ShopRequetNO as ShopRequetNO,vwq.hqrequestno as HQRequestNo,
vwq.QuotationNo as QuotationNo,a.pohPrePurchaseid,case when a.pohprepurchaseid is null then '''' end as PrePurchaseNo,
case  isnull(a.pohApproved,0) when 1 then ''Yes'' when 0 then ''No'' end as pohApproved,ls.Type    --RefNo-01
from loPurchaseOrderHeader a inner join  avendormaster b on  a.pohvendorid=b.VendorID
left outer join vwquotationtracking2 vwq on a.pohpoid=vwq.pohpoid ---and a.pohshopid=vwq.pohshopid
----left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid
left outer join lostype ls on a.pohtypeid=ls.typeid
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=''Q'')
union
(select a.pohpoid,a.pohpono,a.pohpodate,b.vendorname,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,c.purchaseAmount,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.pohquotconfirmed, a.pohpoonhold, a.pohvalue ,
isnull(remarks,'''') remarks,vwpo.ShopRequetNO as ShopRequetNO,vwpo.HQRequestNo as HQRequestNo,vwpo.QuotationNO as QuotationNo,a.pohPrePurchaseid,vwpo.PrePurchaseNO as PrePurchaseNo,
case  isnull(a.pohApproved,0) when 1 then ''Yes'' when 0 then ''No'' end as pohApproved,ls.Type     --RefNo-01
from loPurchaseOrderHeader 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 lostype ls on a.pohtypeid=ls.typeid
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'')'
GO
/****** Object:  View [dbo].[vwmonthwiseproductsales]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwmonthwiseproductsales]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwmonthwiseproductsales    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwmonthwiseproductsales] as
select monthsales.monthname, monthsales.monthcode, monthsales.yearname, monthsales.posditemid,
sum(monthsales.unitprice) unitprice, sum(monthsales.dunitprice) dunitprice,
sum(monthsales.cunitprice) cunitprice, sum(monthsales.quantity) quantity, monthsales.poshShopID,
a.itemcode, a.brand, a.modelno, a.itemcategoryid, monthsales.monthno
from
(select datename(month,poshbilldate) monthname, substring(datename(month,poshbilldate),1,3)
+ ''-'' + substring(convert(varchar(4),year(poshbilldate)),3,2) monthcode,
year(poshbilldate) yearname, posditemid, avg(posdunitprice) unitprice,
avg(dunitprice) dunitprice, avg(cunitprice) cunitprice,
sum(posdquantity) quantity, poshShopID, month(poshbilldate) monthno from vwshopitemsales
group by  poshshopid, posditemid, year(poshbilldate), month(poshbilldate), poshbilldate)
monthsales, aitem a where monthsales.posditemid = a.itemid group by monthsales.yearname,
monthsales.monthname, monthsales.monthcode, monthsales.posditemid, a.itemcode, a.brand,
a.modelno, monthsales.poshShopID, a.itemcategoryid, monthsales.monthno'
GO
/****** Object:  View [dbo].[vwCosting]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCosting]'))
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : SREEJITH G A
--CREATED ON : 27-08-2010
--PURPOSE : TO GET LOCAL AND MAIN COSTING DETAILS
CREATE view [dbo].[vwCosting]
as
select chCostingDate Date, chtime [Time], d.cdItemID ItemId,cdNewItemCostPrice ItemCost,updatetime,cdCostingID costingid
from LOaCostingDetail d
left outer  join LOaCostingHeader on cdCostingID=chCostingID
where isnull(chCancelled,0)=0
union all
select lpchDate, lpchTime, d.lpcditemid,lpcdnewitemcostprice ,updatetime,lpcdcostingid
from loalocalpurchasecostingdetail d
left outer  join loalocalpurchasecostingHeader on lpcdcostingid=lpchCostingid
where isnull(lpchCancelled,0)=0'
GO
/****** Object:  View [dbo].[vwConfirmedLocalPurchaseBill]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwConfirmedLocalPurchaseBill]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------
-- Ceated by : MANUNADH.U
-- Date	     : 07/12/2011
-- Comments  : To get all the confirmed local purchase bill to list in the Unconfirm Transaction
--			 : interface
------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwConfirmedLocalPurchaseBill]
AS
SELECT DISTINCT LPH.lphShopID,LPH.lphBillID,LPH.lphBillNo,LPH.lphBillDate,LPH.lphBillAmount,
LPH.lphDepartmentID,LPH.lphVendorID,LPH.lphcosted
FROM losLocalPurchaseHeader LPH
INNER JOIN avendormaster V ON V.vendorid=LPH.lphVendorID AND V.CompanyID=LPH.lphCompanyID
LEFT OUTER JOIN
(
	SELECT VH.shopid,VD.lphbillid FROM vendorsettlementheader VH
	inner join vendorsettlementdetail VD ON VH.VSID = VD.VSID and VH.companyid=VD.companyid
	  AND VH.Cancelled=0
)VS ON VS.lphbillid=LPH.lphbillid and LPH.lphshopid=VS.shopid 		
LEFT OUTER JOIN
(
	SELECT PVD.pdshopid,PVD.pdposlpbillid FROM ahqpaymentvoucherheader PVH
	inner join ahqpaymentvoucherdetails PVD ON PVH.phpaymentid = PVD.pdpaymentid AND
	  PVH.phcompanyid=PVD.pdcompanyid AND PVH.phCancelled=0
)P ON P.pdposlpbillid=LPH.lphbillid AND LPH.lphshopid=P.pdshopid 	
WHERE  LPH.lphCancelled=0 AND LPH.lphPosted=0 AND LPH.lphcosted=0
AND LPH.lphUsed=0 AND LPH.lphSettled=0 and LPH.lphConfirmed=1
AND ISNULL(VS.lphbillid,0)=0 AND ISNULL(P.pdposlpbillid,0)=0
--AND LPH.lphbilldate = ''20111128'' and LPH.lphShopID=1'
GO
/****** Object:  View [dbo].[vwCreditNoteSettlementNo]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditNoteSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- verified by leo
---------------------------------------------------------------------------------
-- Modified by    :    Kishore
-- Modified on    :    17/11/2003
-- Comments       :    Added the PaidAmount column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by    :    VinothMurugan V
-- Modified on    :    08/11/2010
-- Comments       :    Added Confimation Bit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwCreditNoteSettlementNo] AS
select companyid, vendorid, max(setdate) setdate, max(refno) refno, dcnid,
sum(SettlementAmount) PaidAmount
from (select vh.companyid, vh.vendorid, vh.vsdate setdate,
vh.vsno refno, vd.dcnid, SettlementAmount
from vendorsettlementheader vh, vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid
and vd.dcnid is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, ph.phvendorid, ph.phpaymentdate setdate,
ph.phpaymentno refno, pd.pddcnid, phAmount SettlementAmount
from ahqpaymentvoucherheader ph, ahqpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pddcnid is not null  and ph.phConfirmed = 1
union all
-- Take LC Payments
select pdd.pddpaymentid, b.pbhVendorId, ph.phPaymentDate,
ph.phPaymentNo RefNo, b.pbhBillId, pddAmount
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
lospPurchaseBillHeader b, MiscSettings s
where pdd.pddPaymentID = ph.phPaymentID
and pdd.pddCompanyId = ph.phCompanyId
and pdd.pddHqPoId = b.pbhPoid
and ph.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0
and ph.phLcPayment in (''LCM'', ''LCO'') and ph.phConfirmed = 1
) SettledAccBills
group by companyid, vendorid, dcnid'
GO
/****** Object:  View [dbo].[vwshipmentcostprice]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentcostprice]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentcostprice    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE VIEW [dbo].[vwshipmentcostprice] as
--shipment cost price including opening shipment
select cditemid itemid, sshipmentid shipmentid, sshipmentno, cdCostingPrice shipcost
from ashipment h
left outer join losppurchasebillheader pb on h.sbillid= pb.pbhbillid and pbhcancelled=0
left outer join loacostingheader ch on ch.chbillid=pb.pbhbillid and
ch.chcompanyid=pb.pbhcompanyid and chcancelled=0 left outer join loacostingdetail cd on
ch.chcostingid = cd.cdcostingid
UNION ALL
--shipment cost price of splitted items
select scfdItemid, sshipmentid, sshipmentno, scfdcostprice shipcost from ashipment h,
loaitemsplitcostingheader ish,  loaitemsplitcostingdetail isd WHERE
ish.scfhshipmentid = h.sshipmentid  AND ish.scfhid = isd.scfdid and ish.scfhcancelled=0'
GO
/****** Object:  View [dbo].[vwSalesRegister]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesRegister]'))
EXEC dbo.sp_executesql @statement = N'
--CREATED BY : AADYAKUMAR.D.V
--PURPOSE    : AS PER TICKET SXJ-583458 Vinod modified the view vwCustomerSales
--           : So in sales register report invoice is shown as splited on the basis of detail table
--           : In ticket LES-771128,this bug want to fix,so i am creating new view for sales register report
--           : As per instruction by Benziger and Jyothish i created the view
--           : In reports set location property vwCustomerSales is replaced with vwSalesRegister
--Report Name: "rptsalesregister"
--CREATE VIEW dbo.vwCustomerSales AS
--SELECT * FROM vwCustomerSales   WHERE ihInvoiceNo=''10/CHG/CS/5919''
CREATE VIEW [dbo].[vwSalesRegister] 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
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 ,
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
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
from
losspecialinvoiceheader ih, losspecialinvoicedetail invd, vwShopSplInvItemAmount 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 ihproforma = 0 and
ihcashinvoice = 1 and invd.idratetype = 0 and ihcustomerid = c.customerid and
c.countryid = cm.countryid  and ih.ihtransfinished=1
group by
ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid, ihbankcashaccid,
ihexchangerate, ihCustomerID, ihdepartmentid, countryname , CustomerCardNo,
Customername, ihReferenceNo, ihDepExRate
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
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
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
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 ,
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
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
from
losspecialinvoiceheader ih, (select idinvoiceID,idShopId,iditemid,idRateType,sum(idquantity)idquantity,idCostPrice
from losspecialinvoicedetail group by idinvoiceID,idShopId,iditemid,idRateType,idCostPrice)  invd,
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
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
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
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, ''''
from
losposheader ih
left outer join acustomermaster c on poshcustomerid = c.customerid
left outer join acountrymaster cm on c.CountryId = cm.CountryId,
losposdetail invd
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
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, ''''
from
losposexchangeheader ih, losposexchangedetail invd,
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
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, ''''
from
losposexchangeheader ih, losposexchangedetail invd,
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
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
from
losExportHeader ih, losExportDetail invd, acustomermaster c, acountrymaster cm
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''
group by
rehcompanyid, rehshopid, rehExportNo, rehExportDate, rehExportID, rehCustomerID,
rehbankcashaccid, rehexchangerate, rehCustomerid ,rehdepartmentid,
countryname, rehExportNO, CustomerCardNo, Customername, rehReferenceno, rehDepExRate
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,
convert(numeric(18, 2), sum(grndUnitPrice) * grnhdepExRate -
sum(grnCostPrice * invd.grndQuantity * grnhdepExRate)) DepProfit,
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, ''''
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
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
from
losspecialinvoiceheader ih, (select idinvoiceID,idShopId,iditemid,idRateType,sum(reqqty)reqqty,idCostPrice
from losspecialinvoicedetail group by idinvoiceID,idShopId,iditemid,idRateType,idCostPrice) invd,
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'
GO
/****** Object:  View [dbo].[vwPopulateUserSignatures]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPopulateUserSignatures]'))
EXEC dbo.sp_executesql @statement = N'
/*
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 [dbo].[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
/****** Object:  View [dbo].[VwpendingControlAccTrans]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwpendingControlAccTrans]'))
EXEC dbo.sp_executesql @statement = N'
--created by :- venkitesh  01072004
--purpose : pending control accounts
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  VIEW [dbo].[VwpendingControlAccTrans] as
select Transno,Transid,TransDate,Remarks,DepName,MainDepid,CompanyId,Accountid,Amount,Cr,Accountdesc,Type
From
(select journalno Transno,journaltransid Transid,JournalTransDate Transdate,Remarks,departmentname depname,maindepid,companyid,accountid,amount,cr,accountdesc,''J'' type  from  vwjournalswithcontrolaccs
union all
select phpaymentno,phpaymentid,phpaymentDate,phRemarks,departmentname,maindepid,phcompanyid,pddaccountid,pddamount,credit,accountdesc,''P'' from  vwpaymentswithcontrolaccs
union all
select receiptno,receiptid,receiptDate,Remarks,departmentname,maindepid,companyid,accountid,amount,credit,accountdesc,''R'' from  vwreceiptswithcontrolaccs
union all
select BillsNo,BillsID,BillDate,Remarks,departmentname,maindepid,companyid,accountid,amount,cr,accountdesc,''B'' from  vwBillsWithControlAccounts
UNION ALL
select InvoiceNo,InvoiceID,InvoiceDate,Remarks,departmentname,maindepid,companyid,accountid,amount,cr,accountdesc,''I'' from  vwInvoicesWithControlAccounts
union all
select dcnno,dcnid,dcndate,dcnremarks, departmentname,maindepid,dcncompanyid,dcnotheraccid,dcnamount,dcndebit,accountdesc,''D'' from  vwdcnwithcontrolaccdep
)
a'
GO
/****** Object:  View [dbo].[vwsalesandcostvalue]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesandcostvalue]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 08/05/2004
--Modified by		: Hariharan
--Comments		: v3
CREATE view [dbo].[vwsalesandcostvalue] as
select yearsale.yearname,ai.itemcategoryid,sum(yearsale.quantity) totqty
,sum(yearsale.salesvalitem) salesvalcate, sum(yearsale.dsalesvalitem) dsalesvalcate,
sum(yearsale.csalesvalitem) csalesvalcate,cast(sum(yearsale.quantity)as varchar) +
space(20-len(cast(sum(yearsale.quantity)as varchar)))+'' | ''+
cast(sum(yearsale.salesvalitem) as varchar)+
space(20-len(cast(sum(yearsale.salesvalitem) as varchar))) qtysales,
sum(yearsale.costvalitem) costvalcate, sum(yearsale.dcostvalitem) dcostvalcate ,
sum(yearsale.ccostvalitem) ccostvalcate  from aitem ai, (select
year(poshbilldate) yearname, posditemid, sum(Amount) salesvalitem,
sum(dAmount) dsalesvalitem, sum(cAmount) csalesvalitem,
sum(posdquantity) quantity, poshShopID, sum(posdquantity*costprice) costvalitem,
sum(posdquantity*dcostprice) dcostvalitem, sum(posdquantity*ccostprice) ccostvalitem  from
vwshopitemsales
group by  poshshopid, posditemid, year(poshbilldate), poshbilldate) yearsale
where ai.itemid=yearsale.posditemid group by yearsale.yearname, ai.itemcategoryid'
GO
/****** Object:  View [dbo].[vwSalesMarginAndPercGSTSeparately]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesMarginAndPercGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
-- 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 [dbo].[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
/****** Object:  View [dbo].[vwSalesMarginAndPerc]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesMarginAndPerc]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
----------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwSalesMarginAndPerc]  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
from vwshopitemsales 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
/****** Object:  View [dbo].[vwFANDBInvoice]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwFANDBInvoice]'))
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------
--Ref.No.1
--modified on:29/02/2012
--Modified by:Aadyakumar.D.V
--Comment    :Added fb_pd_DishTaxAmount
-----------------------------------------------------------------------
CREATE  view [dbo].[vwFANDBInvoice] as
--created jyothish
select ch.CompanyID,DepartmentID,poshShopID,poshBillID,poshBillNo,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,dateadd("day",DuePeriod,dateadd(dd,0, datediff(dd,0, poshBillDate))) duedate,poshcustomerid,poshBillAmount ,''fandb'' type ,
isnull(vw.settledamount,0)+ isnull(vw2.Received,0)settledamount ,ch.debtoraccid,
poshExchangeRates ,poshdepexrate *poshBillAmount depBiilAmount,
poshExchangeRate*poshBillAmount cBiilAmount,poshFinancialId ,ch.customercategory,isnull(ch.custgroupname,'''')custgroupname,
fb_pd_DishTaxAmount  --Ref.No.1
from
(select * from losPosFandBHeader  where poshvoucherid is null and isnull(poshCustomerId,0) <> 0) fh
inner join Fb_processdetail D on fh.poshBillID=D.fb_pd_processid  and fh.poshShopID=d.fb_pd_outletid and fh.poshCompanyID=d.fb_pd_companyid --Ref.No.1
inner join ashops s on poshShopID=ShopID
inner join aCustomerMaster ch on ch.CustomerID= poshcustomerid
left outer join
(
select drcustomerid,lt.drdShopID ,drdfandbInvoiceID, sum(drdsettledamount) settledamount
from LosDummyReceiptHeader lh
inner join LosDummyReceiptdetail  lt on lh.drShopid=lt.drdShopID and lt.drdid=lh.drId  and drcancelled=0
group by drcustomerid,lt.drdShopID ,drdfandbInvoiceID
)vw on fh.poshShopID = vw.drdShopID and   fh.poshBillID = vw.drdfandbInvoiceID
left outer join
(
select shopid,fandbInvoiceID,sum(AmountReceived)Received   from ReceiptVoucherHeader rh   inner join  Receiptvoucherdetails  rt on
rh.ReceiptID=rt.ReceiptID where  Cancelled=0 and isnull(fandbInvoiceID,0)<>0
group by  shopid,fandbInvoiceID
)vw2 on fh.poshShopID=vw2.shopid and   fh.poshBillID = vw2.fandbInvoiceID'
GO
/****** Object:  View [dbo].[vwposBillsettlementpay]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwposBillsettlementpay]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwposBillsettlementpay    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwposBillsettlementpay    Script Date: 14/09/2002 12:48:09 AM ******/
/****** Object:  View dbo.vwposBillsettlementpay    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwposBillsettlementpay    Script Date: 20/11/2001 9:59:04 AM ******/
/****** Object:  View dbo.vwposBillsettlementpay    Script Date: 17/11/2001 9:21:49 PM ******/
-- Last Modified on :18/10/01
-- Modified by      :leo
CREATE view [dbo].[vwposBillsettlementpay] as
select pvd.pdCompanyID, pvh.phDepartmentID,pvd.pdshopid, pvd.pdposlpbillid, max(pvh.phpaymentdate) settleddate,
sum(pvd.pdPaidAmount) as PaidAmount
from aHQPaymentVoucherDetails pvd , aHQPaymentVoucherHeader pvh
where pvd.pdPaymentID = pvh.phPaymentID and pvd.pdCompanyID = pvh.phCompanyID
and pvh.phCancelled = 0 and pvd.pdposlpbillid is not null
group by pvd.pdCompanyID, pvh.phDepartmentID,pvd.pdshopid, pvd.pdposlpbillid'
GO
/****** Object:  View [dbo].[vwBillSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- verified by leo
--------------------------------------------------------------------------
-- Modified by  : Kishore
-- Modified on  : 06/09/2003
-- Comments  : Added query to include LC Payments
--------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 25/11/2003
-- Comments             : Added the PaidAmount column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by         : VinothMurugan V
-- Modified on          : 04/11/2010
-- Comments             : Added Confirm bit
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwBillSettlementNo] AS
select companyid, vendorid, max(setdate) setdate,
max(refno) refno, billid, Sum(PaidAmount) PaidAmount
from (select vh.companyid, vh.vendorid, vh.vsdate setdate, vh.vsno refno, vd.billid,
SettlementAmount PaidAmount
from vendorsettlementheader vh,
vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid
and vd.billid is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, ph.phvendorid, ph.phpaymentdate setdate,
ph.phpaymentno refno, pd.pdaccbillsid, pdPaidAmount PaidAmount
from AHQpaymentvoucherheader ph, AHQpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pdaccbillsid is not null and ph.phConfirmed = 1
union all
-- Take LC Payments
select pdd.pddpaymentid, b.pbhVendorId, ph.phPaymentDate,
ph.phPaymentNo RefNo, b.pbhBillId, pddAmount PaidAmount
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
lospPurchaseBillHeader b, MiscSettings s
where pdd.pddPaymentID = ph.phPaymentID
and pdd.pddCompanyId = ph.phCompanyId
and pdd.pddHqPoId = b.pbhPoid
and ph.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0
and ph.phLcPayment in (''LCM'', ''LCO'') and ph.phConfirmed = 1
) settledaccbills
group by companyid, vendorid, billid'
GO
/****** Object:  View [dbo].[vwDailySalesUserWise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesUserWise]'))
EXEC dbo.sp_executesql @statement = N'
CREATE View   [dbo].[vwDailySalesUserWise]
AS
Select poshbillid as Billid,poshbillno as BillNo,poshCompanyID,poshshopid As shopid, poshbilldate As billdate,
poshcAshaccid As accountid, COnvert(numeric(18,2), Sum( posdunitprice ))  As amount,
COnvert(numeric(18,2), Sum( posdunitprice ) * poshdepexrate)  As damount,
COnvert(numeric(18,2), Sum( posdunitprice) * poshexchangerate) As camount,1 As cAsh,''p'' As transtype,
poshdepartmentid departmentid,ph.poshuserid
From  losposheader ph
	left outer join losposdetail pd on ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid
Where ph.poshcancelled=0
Group By
	poshbillid,poshbillno,poshCompanyID,poshshopid,poshbilldate,poshcAshaccid,poshdepexrate,poshexchangerate,
	poshdepartmentid,ph.poshuserid
	
union all
Select sehexchangeid as Billid,sehExchangeNo as BillNo,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,lo.userid
From  losposexchangeheader ph
	left outer join losposexchangedetail pd on ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid
	left outer join lousers lo on ph.sehrecadduser=lo.username and lo.shopid=ph.sehshopid
Where sehcancelled=0 And sedbillorexchange =''E''
Group By
	sehexchangeid,sehExchangeNo,sehcompanyid,sehshopid,sehexchangedate,sehcAshaccid,sehdepexrate, sehexchangerate,
	sehdepartmentid,lo.userid
UniOn All
Select sehexchangeid as Billid,sehExchangeNo as BillNo,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,lo.userid
From losposexchangeheader ph
	left outer join losposexchangedetail pd on ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid
	left outer join lousers lo on ph.sehrecadduser=lo.username and lo.shopid=ph.sehshopid
Where sehcancelled=0 And sedbillorexchange =''B'' And sedexchangeqty > 0
Group By
	sehexchangeid,sehExchangeNo,sehcompanyid,sehshopid,sehexchangedate,sehcAshaccid,sehdepexrate, sehexchangerate,
	sehdepartmentid,lo.userid
union all
Select ih.ihInvoiceID,ih.ihInvoiceNo,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,lo.userid
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
	left outer join Ashops s on ihshopid = s.shopid And ihcompanyid = s.COmpanyid
	left outer join lousers lo on ih.ihRecAddUser=lo.username and lo.shopid=ih.ihShopID
Where
ihcancelled=0 And ihcAshinvoice = 1 And ih.ihproforma =0 And ih.ihtype=''I''
Group By ihInvoiceID,ihInvoiceNo,ihcompanyid, ihshopid, ihinvoicedate,ihbankcAshaccid,
ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar, ih.ihdutypaidby,lo.userid
union all
Select
	IhInvoiceID,IhInvoiceNo,ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
	COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
	COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
	COnvert(numeric(18,2),Sum( vw.idunitprice) * ihexchangerate)  As camount,
	1, ''d'' As transtype, ihdepartmentid departmentid,ihUserId
From
	losspecialinvoiceheader ih
	left outer join vwShopSplInvItemAmount vw on ih.ihshopid = vw.idshopid And ih.ihinvoiceid = vw.idinvoiceid
Where
	ihcancelled=0 And ihcAshinvoice =1 And ih.ihproforma =0 And ihtransfinIshed=1 and ihNoofOCDetails=0
Group By
	ihinvoiceid,IhInvoiceNo,IhCompanyId,ihshopid,ihinvoicedate, ihbankcAshaccid,ihdepexrate, ihexchangerate,
	ihdepartmentid,ihUserId
	
union all
Select
	IhInvoiceID,IhInvoiceNo,ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
	-COnvert(numeric(18,2),Sum( vw.idunitprice ))  As amount,
	-COnvert(numeric(18,2),Sum( vw.idunitprice) * ihdepexrate)  As damount,
	-COnvert(numeric(18,2),Sum( vw.idunitprice) * ihexchangerate)  As camount,
	1, ''d'' As transtype, ihdepartmentid departmentid,ihUserId
From
	losspecialinvoiceheader ih
	left outer join vwShopSplInvItemAmount vw on ih.ihshopid = vw.idshopid And ih.ihinvoiceid = vw.idinvoiceid
Where
	ihcancelled=0 And ihcAshinvoice =1 And ih.ihproforma =0 And ihtransfinIshed=1 and ihNoofOCDetails<>0
Group By
	IhInvoiceID,IhInvoiceNo,ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,ihdepexrate, ihexchangerate,
	ihdepartmentid,ihUserId
union all
Select
	lah.aiInvoiceID,lah.aiinvoiceno,lah.aiCompanyID, lah.aiShopID,lah.aiInvoiceDate, lah.aibankcAshid,
	COnvert(numeric(18,2),(vws.siamount )) As amount,COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
	COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,lah.aicAshinvoice , ''s'' As transtype,
	aidepartmentid departmentid,lo.userid
From LOsAccountsInvoiceHeader lah
	left outer join vwshopservicesales vws on aiinvoiceid=siinvoiceid And aIshopid = sIshopid
	left outer join lousers lo on lah.aiCreated=lo.username and lo.shopid=lah.aiShopID
Where
	aicancelled=0 And aiproforma=0  And lah.aicAshinvoice =1
Group By lah.aiInvoiceID,lah.aiInvoiceNo,lah.aiCompanyID, lah.aiShopID, lah.aiInvoiceDate,lah.aiBankCashID,
lah.aicAshinvoice,lah.aiDepartmentID,vws.siamount,lah.aidepexrate, lah.aiExchangeRate,lo.userid
union all
Select
	ih.ihInvoiceID,ih.ihInvoiceNo,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,
	0 ihcAshinvoice, ''c'' As transtype, ih.ihdepartmentid  departmentid ,lo.userid
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
	left outer join Ashops s on ihshopid = s.shopid And ihcompanyid = s.COmpanyid
	left outer join lousers lo on ih.ihRecAddUser=lo.username and lo.shopid=ih.ihShopID
Where
	ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype=''I''
Group By
	ihInvoiceID,ihInvoiceNo,ihcompanyid, ihshopid, ihinvoicedate,ihbankcAshaccid,
ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar, ih.ihdutypaidby,lo.userid
union all
Select
	lah.aiInvoiceID,lah.aiinvoiceno,lah.aiCompanyID, lah.aiShopID,lah.aiInvoiceDate, lah.aibankcAshid,
	COnvert(numeric(18,2),(vws.siamount )) As amount,COnvert(numeric(18,2),(vws.siamount * aidepexrate)) As damount,
	COnvert(numeric(18,2),(vws.siamount * aiexchangerate)) As camount,lah.aicAshinvoice , ''s'' As transtype,
	aidepartmentid departmentid,lo.userid
From LOsAccountsInvoiceHeader lah
	left outer join vwshopservicesales vws on aiinvoiceid=siinvoiceid And aIshopid = sIshopid
	left outer join lousers lo on lah.aiCreated=lo.username and lo.shopid=lah.aiShopID
Where
	aicancelled=0 And aiproforma=0  And lah.aicAshinvoice =0
Group By lah.aiInvoiceID,lah.aiInvoiceNo,lah.aiCompanyID, lah.aiShopID, lah.aiInvoiceDate,lah.aiBankCashID,
lah.aicAshinvoice,lah.aiDepartmentID,vws.siamount,lah.aidepexrate, lah.aiExchangeRate,lo.userid
union all
Select
	serbookhid,serbookhInspectionNo,serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,
	COnvert(numeric(18,2), serbookadvanceamount) ,
	COnvert(numeric(18,2), serbookadvanceamount * serbookhdepexrate),
	COnvert(numeric(18,2), serbookadvanceamount * serbookhcmpexrate), 1  ,''sb'',
	serbookhdepartmentid ,    serbookhUserid
From LOsServiceBookingHeader
Where
	serbookhinpcancelled=0 And serbookadvanceamount>0
union all
Select
	serinvhid,serinvno,serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,
	COnvert(numeric(18,2), serinvhamount) ,COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
	COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
	serinvhdepartmentid ,serinvhuserid
From
	losserviceinvheader
Where
	serinvhcancelled = 0   And
	serinvhamount>0 And serinvhcAshacc Is Not Null
union all
Select
	serinvhid,serinvno,serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,
	COnvert(numeric(18,2), serinvhamount) ,COnvert(numeric(18,2), serinvhamount * seinvhdepexrate) ,
	COnvert(numeric(18,2), serinvhamount * serinvhcmpexrate) , 1 , ''sbi'',
	serinvhdepartmentid ,serinvhuserid
From
	losserviceinvheader
Where
	serinvhcancelled = 0   And
	serinvhamount>0 And serinvhcAshacc Is Null
union all
Select GrnhGoodsreturnnoteID,GrnhGoodsreturnnoteNO,GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate,GrnReturnAccID,
-COnvert(numeric(18,2),Sum(grndunitprice))  amount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhdepExRate)  damount,
-COnvert(numeric(18,2),Sum(grndunitprice) * grnhExchangeRate)  camount,
0, ''c'' As transtype, Grnhdepartmentid  departmentid,lo.userid
From losGoodsReturnNoteHeader ih
	left outer join losGoodsReturnNoteDetail invd on ih.GrnhShopid = invd.grndshopid And
		ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID
	left outer join lousers lo on ih.GrnhRecAdduser=lo.username and lo.shopid=ih.grnhShopid
Where
grnhCancel = 0
Group By GrnhGoodsreturnnoteID,GrnhGoodsreturnnoteNO,grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,
GrnReturnAccID,grnhdepartmentid, grnhdepExRate, grnhExchangeRate,lo.userid
union all
Select losDCNId,losDCNNo,  losdcnCompanyID, losdcnshopid,losdcndate, losDCNOtherAccId,
COnvert(numeric(18,2),Sum(losDCNAmount))  amount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  damount,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  camount,
0, ''sdcn'' As type , losdcndepartmentid ,lo.userid
From losdebitcreditnote dc
	left outer join Ashops s on s.shopid = losdcnshopid
	left outer join lousers lo on dc.losDCNRecAddUser=lo.username and lo.shopid=dc.losDCNShopid
Where s.accountable Is Not Null
And losdcncustomerid Is Not Null And
losdcncancelled =0 And losdcndebit =1
Group By losDCNId,losDCNNo,losdcnCompanyID,losdcnshopid,
losdcndate, losDCNOtherAccId,losdepexrate, losexchangerate,losdcndepartmentid  ,lo.userid'
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginDetWithOutGST]'))
EXEC dbo.sp_executesql @statement = N'
---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
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginDet]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginDet]'))
EXEC dbo.sp_executesql @statement = N'
---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
----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollectionWithMarginDet] AS
Select
cashcreditcollection.shopname, cashcreditcollection.poshshopid,
cashcreditcollection.poshbilldate, convert(numeric(18,2),sum(cashsales)) cashsales,
convert(numeric(18,2), sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
convert(numeric(18,2), sum(creditsales)) creditsales,
convert(numeric(18,2), sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
convert(numeric(18,2),sum(costvalue)) costvalue,
convert(numeric(18,2), sum(dcostvalue)) dcostvalue,
convert(numeric(18,2),sum(ccostvalue)) ccostvalue,
convert(numeric(18,2),sum(margin)) margin,
convert(numeric(18,2), sum(dmargin)) dmargin,
convert(numeric(18,2),sum(cmargin)) cmargin,
convert(numeric(18,2),sum(Exchange)) Exchange,
convert(numeric(18,2), sum(dExchange)) dExchange,
convert(numeric(18,2),sum(cExchange)) cExchange,
convert(numeric(18,2),sum(GReturn)) GReturn,
convert(numeric(18,2), sum(dGReturn)) dGReturn,
convert(numeric(18,2),sum(cGReturn)) cGReturn,
cashcreditcollection.departmentname, cashcreditcollection.departmentid
--RefNo-2 start -------------------------
,convert(numeric(18,2),sum(PdChequeSales)) PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
from
(
select
shopname, losposheader.poshShopID, poshbilldate, convert(numeric(18,2),
sum(posdunitprice )) cashsales, convert(numeric(18,2),
sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,2),
sum(posdunitprice * 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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
sum(posdunitprice * 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
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,2),sum(posdunitprice )) cashsales,
--convert(numeric(18,2),sum(posdunitprice * poshdepexrate)) dcashsales,
--convert(numeric(18,2),sum(posdunitprice * poshexchangerate)) ccashsales,
convert(numeric(18,2),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,
convert(numeric(18,2),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,
convert(numeric(18,2),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) 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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
sum(posdunitprice * 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
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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
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
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
select
shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -
sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,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
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,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,
0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,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
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,2),
sum(cashsales )) cashsales, convert(numeric(18,2),
sum(dcashsales)) dcashsales,convert(numeric(18,2),
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
from
vwPosExchangeDetailsWithMargin
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,2),
sum(cashsales )) Exchange, convert(numeric(18,2),
sum(dcashsales)) dExchange,convert(numeric(18,2),
sum(ccashsales)) cExchange,0.00,0.00,0.00, departmentname, departmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
from
vwPosExchangeDetailsWithMargin
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, 2),sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
(convert(numeric(18,2), 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 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, 2),-sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),-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,2), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), 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
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, 2),-sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),-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,2), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), sum(idunitprice )) - 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
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, 2),sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),sum(idUnitPrice * ihExchangeRate)) ccreditsales,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
(convert(numeric(18,2), 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 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, 2),-sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
--(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), 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,2), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), 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
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, 2),-sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
--(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), 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,2), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), sum(idunitprice )) - 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
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,2),
------  sum(idunitprice )) cashsales, convert(numeric(18,2),
------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,2),
------  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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
------  (convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
------  (convert(numeric(18,2), 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,2), sum(idunitprice )) creditsales,
------  convert(numeric(18,2), sum(idunitprice * ihdepexrate)) dcreditsales,
------  convert(numeric(18,2), sum(idunitprice * ihexchangerate)) ccreditsales,
------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
------  convert(numeric(18,2), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,
------  convert(numeric(18,2), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,
------  convert(numeric(18,2), 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,2),
------  -(sum(idunitprice ))) cashsales, convert(numeric(18,2),
------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,2),
------  -(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,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2), 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,2), sum(idunitprice ))) creditsales,
------  -(convert(numeric(18,2), sum(idunitprice * ihdepexrate))) dcreditsales,
------  -(convert(numeric(18,2), sum(idunitprice * ihexchangerate))) ccreditsales,
------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
------  -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2),
------  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,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity)) margin, -(convert(numeric(18,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity))* grnhdepexRate dmargin, -(convert(numeric(18,2),
(sum(GRNDunitprice ))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
0.00,0.00,0.00,-convert(numeric(18,2), (sum(GRNDunitprice ))) GReturn,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhdepexRate))) dGReturn,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhExchangeRate))) cGReturn, departmentname, grnhdepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2) ,
sum(repinvdrate* repinvdqty)) cashsales, convert(numeric(18,2) ,
sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,
convert(numeric(18,2), sum(repinvdrate* serinvhcmpexrate * repinvdqty)) 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,2) , ( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty),
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate, convert(numeric(18,2) ,
( sum(repinvdrate  * repinvdqty))) - 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
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,2) , (sum(repinvdrate* repinvdqty))) creditsales ,
convert(numeric(18,2) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,
convert(numeric(18,2) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,
sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*
seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty), convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,2) ,
( sum(repinvdrate * repinvdqty))) - 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
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,2) , serinvhserviceamt) creditsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  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
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,2) , serinvhserviceamt) cashsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcashsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  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
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,2), sum(redunitprice)) creditsales,
convert(numeric(18,2), sum(redunitprice * rehdepexrate))  dcreditsales,
convert(numeric(18,2), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,
sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *
rehexchangerate ccostvalue,  (convert(numeric(18,2), sum(redunitprice ))) -
sum(redcostprice * redquantity) margin, (convert(numeric(18,2), sum(redunitprice * rehdepexrate))) -
sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,2),
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
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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccashsales,
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
from
vwshopservicesales 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,2),sum(vws.siamount)) as  creditsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dcreditsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
convert(numeric(18,2),sum(vws.siamount)) as  margin,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dmargin,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) 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
from vwshopservicesales 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,2),Sum(losDCNAmount))  creditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(losDCNAmount))  margin,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dmargin,
COnvert(numeric(18,2),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
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,2),Sum(serviceqty * amount))  creditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(serviceqty * amount))  margin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dmargin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * 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
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
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginAsOn10062011]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMarginAsOn10062011]'))
EXEC dbo.sp_executesql @statement = N'
--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
---------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollectionWithMarginAsOn10062011] AS
Select
cashcreditcollection.shopname, cashcreditcollection.poshshopid,
cashcreditcollection.poshbilldate, convert(numeric(18,2),sum(cashsales)) cashsales,
convert(numeric(18,2), sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
convert(numeric(18,2), sum(creditsales)) creditsales,
convert(numeric(18,2), sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
convert(numeric(18,2),sum(costvalue)) costvalue,
convert(numeric(18,2), sum(dcostvalue)) dcostvalue,
convert(numeric(18,2),sum(ccostvalue)) ccostvalue,
convert(numeric(18,2),sum(margin)) margin,
convert(numeric(18,2), sum(dmargin)) dmargin,
convert(numeric(18,2),sum(cmargin)) cmargin,
cashcreditcollection.departmentname, cashcreditcollection.departmentid
from
(
select
shopname, poshShopID, poshbilldate, convert(numeric(18,2),
sum(posdunitprice )) cashsales, convert(numeric(18,2),
sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,2),
sum(posdunitprice * 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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
departmentname, poshdepartmentid  departmentid
from
losposdetail, losposheader, ashops s, adepartmentmaster d
where
poshBillid=posdBillid and poshShopid=posdshopid AND
s.shopid = posdshopid and POSHCANCELLED=0 and
poshDepartmentid = d.departmentid
group by
shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,
poshdepexrate, poshexchangerate,poshBillid
union all
select
shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
convert(numeric(18,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -
sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -
sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,
departmentname, ihdepartmentid departmentid
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,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,
0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -
sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -
sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,
departmentname, ihdepartmentid departmentid
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,2),
sum(sedunitprice )) cashsales, convert(numeric(18,2),
sum(sedunitprice * sehdepexrate)) dcashsales,convert(numeric(18,2),
sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedquantity) margin, convert(numeric(18,2), sum(sedunitprice* sehdepexrate)) -
sum(sedcostprice * sedquantity) * sehdepexrate dmargin, convert(numeric(18,2),
sum(sedunitprice * sehexchangerate )) - sum(sedcostprice * sedquantity)
* sehexchangerate  cmargin, departmentname, sehdepartmentid departmentid
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
--gave idratetype condition for special invoice return
--special invoice return - cash
select
shopname, ihShopID, ihinvoicedate, convert(numeric(18,2),
sum(idunitprice )) cashsales, convert(numeric(18,2),
sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,2),
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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid
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,2), sum(idunitprice )) creditsales,
convert(numeric(18,2), sum(idunitprice * ihdepexrate)) dcreditsales,
convert(numeric(18,2), sum(idunitprice * ihexchangerate)) ccreditsales,
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
convert(numeric(18,2), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,
convert(numeric(18,2), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,
convert(numeric(18,2), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,
departmentname, ihDepartmentId departmentid
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
select
shopname, sehshopid, sehexchangedate, convert(numeric(18,2),
-sum(sedunitprice )) cashsales, convert(numeric(18,2),
-sum(sedunitprice * sehdepexrate)) dcashsales, convert(numeric(18,2),
-sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedExchangeQty)) margin, -(convert(numeric(18,2), sum(sedunitprice )) -
sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin, -(convert(numeric(18,2),
sum(sedunitprice )) - sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,
departmentname, sehdepartmentid departmentid
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
--gave idratetype condition for special invoice return
--special invoice return - cash
select
shopname, ihShopID, ihinvoicedate, convert(numeric(18,2),
-(sum(idunitprice ))) cashsales, convert(numeric(18,2),
-(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,2),
-(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,2), sum(idunitprice ))) -
sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2), sum(idunitprice ))) -
sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,
departmentname, ihdepartmentid departmentid
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,2), sum(idunitprice ))) creditsales,
-(convert(numeric(18,2), sum(idunitprice * ihdepexrate))) dcreditsales,
-(convert(numeric(18,2), sum(idunitprice * ihexchangerate))) ccreditsales,
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
-((convert(numeric(18,2), sum(idunitprice ))) -
sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2),
sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,
departmentname, ihdepartmentid departmentid
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
select
shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,
-convert(numeric(18,2), (sum(GRNDunitprice ))) creditsales,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales,
-sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,
-sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,
-(convert(numeric(18,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity)) margin, -(convert(numeric(18,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity))* grnhdepexRate dmargin, -(convert(numeric(18,2),
(sum(GRNDunitprice ))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
departmentname, grnhdepartmentid departmentid
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,2) ,
sum(repinvdrate* repinvdqty)) cashsales, convert(numeric(18,2) ,
sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,
convert(numeric(18,2), sum(repinvdrate* serinvhcmpexrate * repinvdqty)) 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,2) , ( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty),
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate, convert(numeric(18,2) ,
( sum(repinvdrate  * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,
departmentname, serinvhDepartmentid departmentid
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,2) , (sum(repinvdrate* repinvdqty))) creditsales ,
convert(numeric(18,2) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,
convert(numeric(18,2) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,
sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*
seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty), convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,2) ,
( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,
departmentname, serinvhDepartmentid departmentid
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,2) , serinvhserviceamt) creditsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  serinvhcmpexrate) ,
departmentname, serinvhDepartmentid departmentid
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,2) , serinvhserviceamt) cashsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcashsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  serinvhcmpexrate) ,
departmentname, serinvhDepartmentid departmentid
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,2), sum(redunitprice)) creditsales,
convert(numeric(18,2), sum(redunitprice * rehdepexrate))  dcreditsales,
convert(numeric(18,2), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,
sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *
rehexchangerate ccostvalue,  (convert(numeric(18,2), sum(redunitprice ))) -
sum(redcostprice * redquantity) margin, (convert(numeric(18,2), sum(redunitprice * rehdepexrate))) -
sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,2),
sum(redunitprice * rehexchangerate))) - sum(redcostprice * redquantity) * rehexchangerate cmargin,
departmentname, rehdepartmentid
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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccashsales,
d.departmentname,lah.aidepartmentid  departmentid
from
vwshopservicesales 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,2),sum(vws.siamount)) as  creditsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dcreditsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
convert(numeric(18,2),sum(vws.siamount)) as  margin,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dmargin,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as cmargin,
d.departmentname,lah.aidepartmentid  departmentid
from vwshopservicesales 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,2),Sum(losDCNAmount))  creditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(losDCNAmount))  margin,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dmargin,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  cmargin,
d.departmentname,losdcndepartmentid
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,2),Sum(serviceqty * amount))  creditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(serviceqty * amount))  margin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dmargin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  cmargin,
d.departmentname,ai.departmentid
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
	union all
	----F&B---------------------------
	select v.* from
	(
	select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,
	case when poshBillType=''CA'' then COnvert(numeric(18,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,
	convert(numeric(18,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,
	convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
	convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
	convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,
	d.departmentname[deptname],poshDepartmentid[deptid]
	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,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,
	convert(numeric(18,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,
	convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
	convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
	convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,
	d.departmentname[deptname],poshDepartmentid[deptid]
	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
) cashcreditcollection
group by
cashcreditcollection.shopname, cashcreditcollection.poshshopid,
cashcreditcollection.departmentname, cashcreditcollection.departmentid,
cashcreditcollection.poshbilldate'
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMargin]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionWithMargin]'))
EXEC dbo.sp_executesql @statement = N'
--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.
----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollectionWithMargin] AS
Select
cashcreditcollection.shopname, cashcreditcollection.poshshopid,
cashcreditcollection.poshbilldate, convert(numeric(18,2),sum(cashsales)) cashsales,
convert(numeric(18,2), sum(dcashsales)) dcashsales,
convert(numeric(18,2),sum(ccashsales)) ccashsales,
convert(numeric(18,2), sum(creditsales)) creditsales,
convert(numeric(18,2), sum(dcreditsales)) dcreditsales,
convert(numeric(18,2),sum(ccreditsales)) ccreditsales,
convert(numeric(18,2),sum(costvalue)) costvalue,
convert(numeric(18,2), sum(dcostvalue)) dcostvalue,
convert(numeric(18,2),sum(ccostvalue)) ccostvalue,
convert(numeric(18,2),sum(margin)) margin,
convert(numeric(18,2), sum(dmargin)) dmargin,
convert(numeric(18,2),sum(cmargin)) cmargin,
cashcreditcollection.departmentname, cashcreditcollection.departmentid
--RefNo-2 start -------------------------
,convert(numeric(18,2),sum(PdChequeSales)) PdChequeSales,
convert(numeric(18,2),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,2),sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 ends -------------------------
from
(
select
shopname, poshShopID, poshbilldate, convert(numeric(18,2),
sum(posdunitprice )) cashsales, convert(numeric(18,2),
sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,2),
sum(posdunitprice * 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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
departmentname, poshdepartmentid  departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2),
--sum(posdunitprice )) cashsales, convert(numeric(18,2),
--sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,2),
--sum(posdunitprice * poshexchangerate)) ccashsales,
convert(numeric(18,2),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,
convert(numeric(18,2),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,
convert(numeric(18,2),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) 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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),
sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
departmentname, poshdepartmentid  departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2), sum(posdunitprice ))) -
sum(posdcostprice*posdquantity) margin,
(convert(numeric(18,2), sum(posdunitprice * poshdepexrate))) -
sum(posdcostprice*posdquantity) * poshdepexrate dmargin,
(convert(numeric(18,2), 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,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -
sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,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
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,2), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,
convert(numeric(18,2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,
0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))) costvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,
convert(numeric(18,2),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -
sum(isnull(idcostprice*idquantity,0)))) margin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -
sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,
(convert(numeric(18,2), (sum(isnull(invd.idunitprice,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
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,2),
sum(sedunitprice )) cashsales, convert(numeric(18,2),
sum(sedunitprice * sehdepexrate)) dcashsales,convert(numeric(18,2),
sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedquantity) margin, convert(numeric(18,2), sum(sedunitprice* sehdepexrate)) -
sum(sedcostprice * sedquantity) * sehdepexrate dmargin, convert(numeric(18,2),
sum(sedunitprice * sehexchangerate )) - sum(sedcostprice * sedquantity)
* sehexchangerate  cmargin, departmentname, sehdepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2),
------  sum(idunitprice )) cashsales, convert(numeric(18,2),
------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,2),
------  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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
------  (convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
------  (convert(numeric(18,2), 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,2), sum(idunitprice )) creditsales,
------  convert(numeric(18,2), sum(idunitprice * ihdepexrate)) dcreditsales,
------  convert(numeric(18,2), sum(idunitprice * ihexchangerate)) ccreditsales,
------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
------  convert(numeric(18,2), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,
------  convert(numeric(18,2), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,
------  convert(numeric(18,2), 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,2),
-sum(sedunitprice )) cashsales, convert(numeric(18,2),
-sum(sedunitprice * sehdepexrate)) dcashsales, convert(numeric(18,2),
-sum(sedunitprice * 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,2), sum(sedunitprice)) -
sum(sedcostprice * sedExchangeQty)) margin, -(convert(numeric(18,2), sum(sedunitprice )) -
sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin, -(convert(numeric(18,2),
sum(sedunitprice )) - sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,
departmentname, sehdepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2),
------  -(sum(idunitprice ))) cashsales, convert(numeric(18,2),
------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,2),
------  -(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,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2), 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,2), sum(idunitprice ))) creditsales,
------  -(convert(numeric(18,2), sum(idunitprice * ihdepexrate))) dcreditsales,
------  -(convert(numeric(18,2), sum(idunitprice * ihexchangerate))) ccreditsales,
------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
------  -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,2), sum(idunitprice ))) -
------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,2),
------  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, 2),sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
(convert(numeric(18,2), 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 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, 2),-sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),-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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-sum(idcostprice * reqqty) costvalue ,
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), 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
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, 2),-sum(idUnitPrice)) cashsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,
convert(numeric(18, 2),-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,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*-1*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 = 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, 2),sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),sum(idUnitPrice * ihExchangeRate)) ccreditsales,
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
(convert(numeric(18,2), 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 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, 2),-sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
--(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-sum(idcostprice * reqqty) costvalue ,
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), 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
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, 2),-sum(idUnitPrice)) creditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcreditsales,
convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,
--(convert(numeric(18,2), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,
--(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,
--(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,
-(convert(numeric(18,2), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,
-(convert(numeric(18,2), sum(idunitprice )) - sum(idcostprice*-1*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 = 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,2), (sum(GRNDunitprice ))) creditsales,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,
-convert(numeric(18,2), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales,
-sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,
-sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,
-(convert(numeric(18,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity)) margin, -(convert(numeric(18,2), (sum(GRNDunitprice ))) -
sum(grncostprice*grndquantity))* grnhdepexRate dmargin, -(convert(numeric(18,2),
(sum(GRNDunitprice ))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
departmentname, grnhdepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2) ,
sum(repinvdrate* repinvdqty)) cashsales, convert(numeric(18,2) ,
sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,
convert(numeric(18,2), sum(repinvdrate* serinvhcmpexrate * repinvdqty)) 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,2) , ( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty),
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate, convert(numeric(18,2) ,
( sum(repinvdrate  * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,
departmentname, serinvhDepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2) , (sum(repinvdrate* repinvdqty))) creditsales ,
convert(numeric(18,2) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,
convert(numeric(18,2) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,
sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*
seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,
convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty), convert(numeric(18,2) , ( sum(repinvdrate * repinvdqty))) -
sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,2) ,
( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,
departmentname, serinvhDepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2) , serinvhserviceamt) creditsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  serinvhcmpexrate) ,
departmentname, serinvhDepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2) , serinvhserviceamt) cashsales ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcashsales ,
convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,
0 costvalue, 0 dcostvalue, 0 ccostvalue,
convert(numeric(18,2) , serinvhserviceamt) ,
convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) ,
convert(numeric(18,2) ,  serinvhserviceamt *  serinvhcmpexrate) ,
departmentname, serinvhDepartmentid departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2), sum(redunitprice)) creditsales,
convert(numeric(18,2), sum(redunitprice * rehdepexrate))  dcreditsales,
convert(numeric(18,2), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,
sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *
rehexchangerate ccostvalue,  (convert(numeric(18,2), sum(redunitprice ))) -
sum(redcostprice * redquantity) margin, (convert(numeric(18,2), sum(redunitprice * rehdepexrate))) -
sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,2),
sum(redunitprice * rehexchangerate))) - sum(redcostprice * redquantity) * rehexchangerate cmargin,
departmentname, rehdepartmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),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,2),sum(vws.siamount)) as cashsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as  dcashsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccashsales,
d.departmentname,lah.aidepartmentid  departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
from
vwshopservicesales 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,2),sum(vws.siamount)) as  creditsales,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dcreditsales,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
convert(numeric(18,2),sum(vws.siamount)) as  margin,
convert(numeric(18,2),sum(vws.siamount * aidepexrate)) as   dmargin,
convert(numeric(18,2),sum(vws.siamount * aiexchangerate)) as cmargin,
d.departmentname,lah.aidepartmentid  departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
from vwshopservicesales 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,2),Sum(losDCNAmount))  creditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(losDCNAmount))  margin,
COnvert(numeric(18,2),Sum(losDCNAmount) * losdepexrate)  dmargin,
COnvert(numeric(18,2),Sum(losDCNAmount) * losexchangerate)  cmargin,
d.departmentname,losdcndepartmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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,2),Sum(serviceqty * amount))  creditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dcreditsales,
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  ccreditsales,
0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,
COnvert(numeric(18,2),Sum(serviceqty * amount))  margin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dmargin,
COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  cmargin,
d.departmentname,ai.departmentid
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
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
union all
----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,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,
--convert(numeric(18,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,
--convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
--convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
--convert(numeric(18,2),((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,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,
--convert(numeric(18,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,
--convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,
--convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,
--convert(numeric(18,2),(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
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,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,
convert(numeric(18,2),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,
convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,
convert(numeric(18,2),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,
convert(numeric(18,2),((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,2),(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,2),(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,2),(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,2),(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,2),(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,2),(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,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,
convert(numeric(18,2),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,
convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,
convert(numeric(18,2),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,
convert(numeric(18,2),(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
/****** Object:  View [dbo].[vwTableBlock]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTableBlock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwTableBlock    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwTableBlock] as
select * from
(select gsgodownid, gslocationid, gsshipmentid, gsitemid, (gsstock - tb.issuedgood) gsstock ,
(gsbadstock - tb.issuedbad) gsbadstock from moigodownstock gs,
(select ind.indgodownid,ind.indlocationid, ind.inditemid,
ind.indshipmentid, sum(ind.indqty) as issuedgood,
sum(ind.indbadqty) as issuedbad from ahqissuenotedetail ind,ahqIssueNoteHeader inh ,
ahqIssuenoteMain inm where ind.indissuenoteid=inh.inhissuenoteid and
ind.indgodownid=inh.inhgodownid and inh.inhissuenotemainid=inm.inmissuenoteid and
inm.inmCancel=0 and inh.inhused=0
group by ind.indgodownid,ind.indlocationid, ind.indshipmentid,
ind.inditemid) tb
where gs.gsgodownid = tb.indgodownid and gs.gslocationid = tb.indlocationid
and gs.gsshipmentid = tb.indshipmentid and gs.gsitemid = tb.inditemid) one
where gsstock >0 or gsbadstock >0'
GO
/****** Object:  View [dbo].[vwItemShipmentPrice]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemShipmentPrice]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwItemShipmentPrice    Script Date: 18/01/2003 9:45:38 PM ******/
/****** Object:  View dbo.vwItemShipmentPrice    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwItemShipmentPrice    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwItemShipmentPrice    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwItemShipmentPrice    Script Date: 17/11/2001 9:22:01 PM ******/
CREATE view [dbo].[vwItemShipmentPrice] as
select sshipmentno, sshipmentid,cditemid, cdcostingprice  from loacostingdetail cd,
loacostingheader ch, ashipment s where
ch.chcostingid =cd.cdcostingid and ch.chbillid = sbillid and ch.chcancelled = 0
union
select sshipmentno, sshipmentid,scfditemid,scfdcostprice from loacostingheader ch, loaitemsplitcostingdetail iscd,
loaitemsplitcostingheader isch, ashipment s
where iscd.scfdid = isch.scfhid and ch.chcostingid = isch.scfhcostingid and
s.sbillid = ch.chbillid and ch.chcancelled = 0'
GO
/****** Object:  View [dbo].[vwItemsoldCustomerwise]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsoldCustomerwise]'))
EXEC dbo.sp_executesql @statement = N'
--<<Ref-01>>
--Modified ON :- 14/05/2012
--Modified By :- MANUNADH.U
--Comment     :- Customer - Item Sold History Report (P&C - Inventory Reports)
--				 doesnot show data for a purticular customer for the corresponding department
--				 (DepartmentId Is joined incorrectly with shopid ).
CREATE VIEW [dbo].[vwItemsoldCustomerwise] AS
SELECT VW.posdItemId ItemId,itemcode,itemdescription,VW.poshShopId ShopId,VW.posdQuantity Qty,
	VW.posdUnitPrice SoldRate,dUnitPrice dSoldRate, cUnitPrice cSoldRate,VW.poshBillDate SoldDate,VW.poshBillNo RefNo,
	a.ItemCategoryId,CostPrice,dCostPrice, cCostPrice,Amount, dAmount, cAmount,apt.Packingtypename PackingType,
	Customername,CustomerID,adp.departmentid Departmentid,
	case posdUnitPrice when 0 then 0 else (posdUnitPrice-costprice)/posdUnitPrice*100 end margin
FROM vwShopItemSalesWithCustomerAndPack vw, aItem a, aItemcategory b, apackingtype apt,ashops S,adepartmentmaster adp
WHERE VW.posdItemId = a.ItemId AND a.ItemCategoryId = b.ItemCategoryId and apt.packingtypeid=vw.packingtypeid
	--AND vw.poshShopId=adp.departmentid   --<<Ref-01>>  Comment the Previous code
	AND VW.poshShopId=S.SHOPID AND S.departmentid =adp.departmentid'
GO
/****** Object:  StoredProcedure [dbo].[spSeasonalSalesPrediction]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSeasonalSalesPrediction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created On  : 14/05/2009
--Created By  : Sebin.T.S
--Comments    : Created for Seasonal Sales Prediction Report
--spSeasonalSalesPrediction 1,1,1,''20100201''
---------------------------------------------------------------
CREATE PROCEDURE [dbo].[spSeasonalSalesPrediction]
(
@categoryId as int=0,
@shopId as int=0,
@departmentId as int=0,
@date as varchar(15)
)
As
BEGIN
set nocount on
CREATE TABLE #temp
(
BillYear int,
ItemId int,
ItemDesc varchar(500),
Qty  numeric(18,3),
SellingPrice numeric(18,3),
StockValue numeric(18,3),
Margin  numeric(18,3)
)
insert into #temp
SELECT  year(BillDate),posditemID,ItemDescription, sum(posdQuantity)Quantity,
isnull(SellingPrice,0)SellingPrice,sum(stockvalue)StockValue,
sum(margin)Margin FROM
(SELECT posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sum(sd.posdquantity) posdQuantity,
(sum(sd.posdquantity) * sum(costprice)) StockValue,
sd.poshBillDate BillDate, sd.poshShopId, sd.Type, s.ShopName, a.ItemCode, a.ItemDescription,
costprice, cCostPrice, dCostPrice, z.SizeName, u.UnitCode, c.ColorName,
MIN(sid.sellingprice) SellingPrice,margin,
MIN(sid.wholesaleprice) WholeSalePrice, MIN(sid.discountprice ) DiscountPrice,
SUM(Amount) Amount, SUM(cAmount) cAmount, SUM(dAmount) dAmount,
a.Brand, ic.CategoryNameDescription, cm.Symbol SpCurrencySymbol,a.part_code
FROM  vwShopItemSalesforSeasonalPrediction sd
LEFT Outer Join
(SELECT sd.ItemId, sd.Shopid, MIN(SellingPrice) SellingPrice,
MIN(WholeSalePrice) WholeSalePrice, MIN(DiscountPrice) DiscountPrice, CurrencyId
FROM losShopItemShipmentDetail sd, vwitemretailpacking pd
WHERE sd.itemid = pd.itemid
AND sd.Packingtypeid = pd.packingTypeId
GROUP BY Sd.ItemId, Sd.ShopId, sd.CurrencyId) sid
ON sd.posditemid = sid.itemid
AND (sd.poshshopid = sid.shopid OR sid.shopid IS NULL)
LEFT OUTER JOIN aCurrencyMaster cm
ON sid.CurrencyId = cm.CurrencyId,
aShops s, aUnit u, aItem a
LEFT OUTER JOIN aColor c ON a.ColorID = c.ColorID
LEFT OUTER JOIN aSize z ON a.SizeID = z.SizeID, aItemCategory ic
WHERE sd.poshShopID = s.ShopID
AND a.UnitsID = u.UnitID
AND posdItemID = a.itemid
AND sd.poshShopID = @shopId
AND Month(sd.poshBilldate) = Month(@date)
AND Year(sd.poshBilldate) in (year(DateAdd(year,-3,@date)), year(DateAdd(year,-2,@date)),year(DateAdd(year,-1,@date)))
AND a.ItemCategoryId = ic.ItemCategoryId
AND a.ItemCategoryId = @categoryId
GROUP BY s.ShopName, sd.poshBilldate, sd.poshShopID, sd.type,
a.Brand, ic.CategoryNameDescription,
a.ItemCode, a.ItemDescription, z.SizeName,margin ,
u.UnitCode, c.ColorName, sd.posdunitprice, sd.cUnitPrice, sd.dUnitPrice,
sd.costprice, sd.cCostPrice, sd.dCostPrice, posditemid, cm.Symbol,a.part_code
--order by posditemid
)a
GROUP BY posditemID,ItemDescription,year(BillDate),SellingPrice
ORDER BY Quantity desc
--select * from #temp
CREATE TABLE #temp1
(
BillYear int,
ItemId int,
ItemDesc  varchar(500),
Qty  numeric(18,3),
SellingPrice numeric(18,3),
StockValue numeric(18,3),
Margin  numeric(18,3),
Qty1  numeric(18,3),
SellingPrice1 numeric(18,3),
StockValue1 numeric(18,3),
Margin1  numeric(18,3),
Qty2  numeric(18,3),
SellingPrice2 numeric(18,3),
StockValue2 numeric(18,3),
Margin2  numeric(18,3)
)
insert into #temp1 select BillYear,ItemId,ItemDesc,Qty,SellingPrice,StockValue,Margin,
0,0,0,0,0,0,0,0 from #temp
where BillYear= year(DateAdd(year,-3,@date))--and ItemId=#temp.ItemId
insert into #temp1 select BillYear,ItemId,ItemDesc,0,0,0,0,Qty,SellingPrice,StockValue,Margin,
0,0,0,0 from #temp
where BillYear= year(DateAdd(year,-2,@date)) --and ItemId=#temp.ItemId
insert into #temp1 select BillYear,ItemId,ItemDesc,0,0,0,0,0,0,0,0,Qty,SellingPrice,StockValue,Margin
from #temp
where BillYear= year(DateAdd(year,-1,@date)) --and ItemId=#temp.ItemId
select * from #temp1
--select ItemId,ItemDesc,sum(Qty)Qty,Min(SellingPrice)SellingPrice,sum(StockValue)StockValue
--    ,sum(Margin)Margin,sum(Qty1)Qty1,min(SellingPrice1)SellingPrice1
--    ,sum(StockValue1)StockValue1,sum(Margin1)Margin1,sum(Qty2)Qty2
--    ,min(SellingPrice2)SellingPrice2,sum(StockValue2)StockValue2,sum(Margin2)Margin2
--from #temp1 group by ItemId,ItemDesc
drop table #temp1
drop table #temp
END' 
END
GO
/****** Object:  View [dbo].[vwItemDetailedSalesForecastment]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailedSalesForecastment]'))
EXEC dbo.sp_executesql @statement = N'
----------DB 4 -------------------------------------------------------------------------------
---Created By    :Prasanth Joseph
---Created on    :06-05-2008
---Created For   :Monthly item sale forecaststatement
---Modified on   :
---Modified By   :
Create VIEW [dbo].[vwItemDetailedSalesForecastment] AS
SELECT posdItemId ItemId,vw.itemDescription, Year(poshBillDate) sYear, Month(PoshBillDate) sMonth,
poshShopId ShopId, posdQuantity Qty,
posdUnitPrice SoldRate, dUnitPrice dSoldRate, cUnitPrice cSoldRate,
poshBillDate SoldDate, poshBillNo RefNo,
a.ItemCategoryId,
CostPrice, dCostPrice, cCostPrice,
Amount, dAmount, cAmount--,sum(stock.stock) ComStock
FROM vwShopItemSales vws, aItem a, aItemcategory b,vwItemDescription vw--,vwCompanyTotalStock stock
WHERE posdItemId = a.ItemId  and vw.itemid=vws.posdItemId --and stock.itemid=posdItemId
AND a.ItemCategoryId = b.ItemCategoryId
--group by  posdItemId, vw.itemDescription ,poshBillDate,poshShopId,posdQuantity,posdUnitPrice,
--dUnitPrice,cUnitPrice,poshBillNo,a.ItemCategoryId,CostPrice,dCostPrice,cCostPrice,Amount,
--dAmount,cAmount,stock.stock'
GO
/****** Object:  StoredProcedure [dbo].[spItemDetailedSalesForecastment]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemDetailedSalesForecastment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---Created By  : Prasanth Joseph
---Created on  : 6-05-2008
---Created For : To get Month wise forecastsatement
---Modified By :
---Modified On :
CREATE proc [dbo].[spItemDetailedSalesForecastment] @dtFromDAte as varchar(10),
@dtToDate as varchar(10),
@ShopID as int,
@itemId as int,
@ItemCatID as int as
set nocount on
create table #Forecastment(
ItemId numeric,
itemDescription nvarchar(200),
sYear numeric,
sMonth numeric,
ShopId numeric,
Qty numeric(18,2),
SoldRate numeric,
dSoldRate numeric(18,2),
cSoldRate numeric,
SoldDate  datetime,
RefNo nvarchar(200),
ItemCategoryId numeric,
CostPrice numeric (18,2),
dCostPrice numeric(18,2),
cCostPrice numeric(18,2),
Amount  numeric(18,2),
dAmount numeric(18,2),
cAmount numeric(18,2),
avgQty numeric(18,3),
avlStock numeric(18,2)
)
declare @totalQty float,
@totalDays float,
@fetchitemid int,
@avgQty float,
@strsql nvarchar(2000) ,
@AvlStock float,
@openingStock float
begin
if @itemId <> 0
begin
select @totalDays= datediff(day,@dtFromDAte,@dtToDate)
select @totalQty= sum(qty)  from vwItemDetailedSalesForecastment where itemid=@itemId and
solddate>=@dtFromDAte and solddate <=@dtToDate  and shopid=@ShopID
select @openingStock=Stock from MOsShopStock  where itemid=@itemId and ShopID=@ShopID
select @AvlStock= sum(transqty*mode) from vwshopbincardAudit where shopid=@ShopID and itemid=@itemId
and sdate<=@dtToDate
--select  sum(transqty*mode) from vwshopbincardAudit where shopid=7 and itemid=3845
--     and sdate<=''20080531''
--  select Stock from MOsShopStock  where itemid=3845 and ShopID=7
set @AvlStock=@openingStock+@AvlStock
--set @AvlStock
select @avgQty= @totalQty/@totalDays
insert into #Forecastment
select vw.*,@avgQty,@AvlStock from vwItemDetailedSalesForecastment vw where
vw.soldDate>=@dtFromDAte and vw.soldDate<=@dtToDate and vw.shopid=@ShopID
and vw.itemid=@itemId order by vw.syear,vw.Smonth
end
else if  @ItemCatID<> 0 and @itemId=0
begin
set @totalDays=0
set @openingStock=0
select @totalDays=  datediff(day,@dtFromDAte,@dtToDate)
declare curfetch cursor  for
select itemid from vwItemDetailedSalesForecastment where itemcategoryid=@ItemCatID
open curfetch
fetch next from curfetch into @fetchitemid
while @@fetch_status =0
begin
set @openingStock=0
set @totalQty=0
set @AvlStock=0
set @avgQty=0
select @totalQty= sum(qty)  from vwItemDetailedSalesForecastment where itemid=@fetchitemid
and solddate>=@dtFromDAte and solddate<=@dtToDate
select @openingStock=Stock from MOsShopStock  where itemid=@fetchitemid
select @AvlStock= sum(transqty*mode) from vwshopbincardAudit where shopid=@ShopID and itemid=@fetchitemid
set @AvlStock=@openingStock+ @AvlStock
select @avgQty= @totalQty/@totalDays
insert into #Forecastment
select vw.*,@avgQty,@AvlStock from vwItemDetailedSalesForecastment vw where
vw.soldDate >= @dtFromDAte and vw.soldDate<=@dtToDate and vw.shopid=@ShopID
and vw.itemid=@fetchitemid order by vw.syear,vw.Smonth
fetch next from curfetch into @fetchitemid
end
close curfetch
deallocate curfetch
end
end
set @strsql=N''Select ItemId ,itemDescription,sYear, sMonth, ShopId ,Qty, SoldRate, dSoldRate, cSoldRate,SoldDate, RefNo,
ItemCategoryId, CostPrice, dCostPrice,cCostPrice,Amount, dAmount, cAmount,isnull(avgQty,0),isnull(avlStock,0) from #Forecastment order by sYear, sMonth ''
print @strsql
exec sp_executesql @strsql
set nocount off' 
END
GO
/****** Object:  View [dbo].[vwItemDetailedSales]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailedSales]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 22/12/02
-- Modified by  : Hariharan R
-- Comments  : v3
-- Rexporting transaction details added
-----------------------------------------------------------
-- Modified on  : 17/06/2003
-- Modified by  : Kishore
-- Comments             : Now this view takes value directly from vwShopItemSales
--                        Earlier it was taking values from ''unioning'' 3 or 4 queries
--     Also, added Amount columns
-----------------------------------------------------------
-- Modified on: 10/11/2009
-- Modified by: Regin
-- Modification: Added the fields margin, dmargin, cmargin.
-- These fields are going to be used in Total Item Sales report (rptProfitShopwiseItemwise.rpt)
-----------------------------------------------------------
CREATE VIEW [dbo].[vwItemDetailedSales] AS
SELECT posdItemId ItemId, Year(poshBillDate) sYear, Month(PoshBillDate) sMonth,
poshShopId ShopId, posdQuantity Qty,
posdUnitPrice SoldRate, dUnitPrice dSoldRate, cUnitPrice cSoldRate,
poshBillDate SoldDate, poshBillNo RefNo,
a.ItemCategoryId,
CostPrice, dCostPrice, cCostPrice,
Amount, dAmount, cAmount, margin, dmargin, cmargin
FROM vwShopItemSales, aItem a, aItemcategory b
WHERE posdItemId = a.ItemId
AND a.ItemCategoryId = b.ItemCategoryId
/*
sp_help vwShopItemSales
select posditemid ItemID, year(poshbilldate) as syear, month(poshbilldate) as smonth,
posdshopid ShopID, posdquantity qty,
convert(numeric(18,2),round((posdunitprice)/posdquantity,2)) SoldRate,
convert(numeric(18,2),round((posdunitprice)/posdquantity,2))* poshdepexrate dSoldRate,
convert(numeric(18,2),round((posdunitprice)/posdquantity,2))* poshexchangerate cSoldRate,
poshbilldate SoldDate, poshbillno as refno,a.ItemCategoryID,
convert(numeric(18,2),posdcostprice) costprice,
convert(numeric(18,2),posdcostprice*poshdepexrate)
dcostprice, convert(numeric(18,2),posdcostprice*poshexchangerate) ccostprice
from losposheader lph, losposdetail lpd, aitem a,aitemcategory b
where posditemid=itemid and posdbillid = poshbillid and posdshopid=poshshopid
and poshcancelled=0 and a.ItemCategoryID=b.ItemCategoryID
union all
select seditemid, year(sehexchangedate), month(sehexchangedate), sedshopid, sedquantity,
convert(numeric(18,2),round((sedunitprice)/sedquantity,2)),
convert(numeric(18,2),round((sedunitprice/sedquantity)* sehdepexrate,2)),
convert(numeric(18,2),round((sedunitprice/sedquantity)* sehexchangerate,2)),
sehexchangedate, sehexchangeno, a.ItemCategoryID, convert(numeric(18,2),sedcostprice) costprice,
convert(numeric(18,2),sedcostprice*sehdepexrate) dcostprice,
convert(numeric(18,2),sedcostprice*sehexchangerate) cccostprice
from losposexchangeheader lph, losposexchangedetail lpd, aitem a, aitemcategory b
where seditemid=itemid and sedexchangeid = sehexchangeid and sehcancelled=0
and sedshopid=sehshopid and  sedBillorExchange =''e'' and sehfullyreturned=0
and a.ItemCategoryID=b.ItemCategoryID
union all
select iditemid, year(ihinvoicedate), month(ihinvoicedate), ihshopid, idquantity,
convert(numeric(18,2),round((idUnitPrice)/ idquantity,2)) ,
convert(numeric(18,2),round((idUnitPrice/ idquantity)* ihDepexrate,2)) ,
convert(numeric(18,2),round((idUnitPrice/ idquantity)* ihexchangerate,2)) ,
ihinvoicedate, ihinvoiceno, a.ItemCategoryID, convert(numeric(18,2),idcostprice) costprice,
convert(numeric(18,2),idcostprice*ihdepexrate) dcostprice,
convert(numeric(18,2),idcostprice*ihexchangerate) ccostprice
from losinvoiceheader lih, losinvoicedetail lid, aitem a, aitemcategory b
where itemid=iditemid and ihinvoiceid=idinvoiceid and ihcancelled=0 and ihtype =''i''
and ihshopid=idshopid and ihproforma=0 and a.ItemCategoryID=b.ItemCategoryID
union all
select vw.iditemid, year(ihinvoicedate), month(ihinvoicedate), ihshopid, vw.idquantity,
convert(numeric(18,2),round((vw.idUnitPrice)/vw.idquantity,2)),
convert(numeric(18,2),round((vw.idUnitPrice/vw.idquantity)* ihdepexrate,2)),
convert(numeric(18,2),round((vw.idUnitPrice/vw.idquantity)* ihexchangerate,2)),
ihinvoicedate, ihinvoiceno, a.ItemCategoryID, convert(numeric(18,2),vw.costprice) costprice,
convert(numeric(18,2),vw.costprice*ihdepexrate) dcostprice,
convert(numeric(18,2),vw.costprice*ihexchangerate) ccostprice
from losspecialinvoiceheader lsh, vwShopSplInvItemAmount vw,
aitem a, aitemcategory b
where vw.idinvoiceid = lsh.ihinvoiceid and a.itemid = vw.iditemid and
ihcancelled=0 and lsh.ihshopid = vw.idshopid and ihproforma=0 and
a.ItemCategoryID=b.ItemCategoryId
union all
-- REXPORTING transaction details
select reditemid, year(rehExportDate), month(rehExportdate), rehshopid, redquantity,
convert(numeric(18,2),round((redUnitPrice)/ redquantity,2)) ,
convert(numeric(18,2),round((redUnitPrice/ redquantity)* rehDepexrate,2)) ,
convert(numeric(18,2),round((redUnitPrice/ redquantity)* rehexchangerate,2)) ,
rehExportDate, rehExportno, a.ItemCategoryID, convert(numeric(18,2),redcostprice) costprice,
convert(numeric(18,2),redcostprice*rehdepexrate) dcostprice,
convert(numeric(18,2),redcostprice*rehexchangerate) ccostprice
from losExportHeader lih, losExportDetail lid, aitem a, aitemcategory b
where itemid=reditemid and rehExportID = redExportID and rehcancelled=0 and rehtype =''i''
and rehshopid=redshopid and rehproforma=0 and a.ItemCategoryID=b.ItemCategoryID
*/'
GO
/****** Object:  View [dbo].[vwItemSalesRate]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemSalesRate]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on  : 22/12/02, 24/11/2003
--Modified by  : Hariharan , Hariharan
--Comments  : v3
--Added reexporting transaction details
-- included department wise cost price and company wise cost price
--modi 181203 venki for specialinvoice chking
CREATE view [dbo].[vwItemSalesRate] as
select posditemid ItemID, posdshopid ShopID, posdcostprice itemrate,isnull(posdquantity,0.00)
as qty, convert(numeric(18,2),round(((posdunitprice)/posdquantity),2))
SoldRate, convert(numeric(18,2),round(((posdunitprice * poshdepexrate)/posdquantity),2))
dSoldRate, convert(numeric(18,2),round(((posdunitprice * poshexchangerate)/posdquantity),2))
cSoldRate, poshbilldate SoldDate,
convert(numeric(18,2), posdcostprice * poshdepexrate) dcostprice,
convert(numeric(18,2), posdcostprice  * poshexchangerate) ccostprice
from losposheader lph, losposdetail lpd
where posdbillid = poshbillid and posdshopid=poshshopid
and poshcancelled=0 and round(((posdunitprice )/posdquantity),2) <
posdcostprice and poshreturned=0 and posdquantity <> 0
union all
select seditemid, sedshopid, sedcostprice,isnull(sedquantity,0.00),
convert(numeric(18,2),round(((sedunitprice)/sedquantity),2)),
convert(numeric(18,2),round(((sedunitprice*sehdepexrate)/sedquantity),2)),
convert(numeric(18,2),round(((sedunitprice*sehexchangerate)/sedquantity),2)), sehexchangedate ,
convert(numeric(18,2), sedcostprice * sehdepexrate) dcostprice,
convert(numeric(18,2), sedcostprice  * sehexchangerate) ccostprice
from losposexchangeheader lph, losposexchangedetail lpd
where sedexchangeid = sehexchangeid and sehcancelled=0 and sedBillorExchange=''E''
and sedshopid=sehshopid and round(((sedunitprice)/sedquantity),2) < sedcostprice
and sehfullyreturned=0 and sedquantity <> 0
union all
select iditemid, ihshopid, idcostprice,isnull(idquantity,0.00),
convert(numeric(18,2),round(((idUnitPrice )/idquantity),2)),
convert(numeric(18,2),round(((idUnitPrice * ihdepexrate)/idquantity),2)),
convert(numeric(18,2),round(((idUnitPrice * ihexchangerate)/idquantity),2)),ihinvoicedate,
convert(numeric(18,2), idcostprice * ihdepexrate) dcostprice,
convert(numeric(18,2),idcostprice  * ihexchangerate) ccostprice
from losinvoiceheader lih, losinvoicedetail lid
where ihinvoiceid=idinvoiceid and ihcancelled=0 and ihtype =''i''
and ihshopid=idshopid and round(((idUnitPrice )/idquantity),2) < idcostprice
and ihproforma=0 and idquantity <> 0
union all
select iditemid, ihshopid, costprice,isnull(idquantity,0.00),
convert(numeric(18,2),round(((idUnitPrice )/idquantity),2)),
convert(numeric(18,2),round(((idUnitPrice * ihdepexrate)/idquantity),2)),
convert(numeric(18,2),round(((idUnitPrice * ihexchangerate)/idquantity),2)), ihinvoicedate,
convert(numeric(18,2),costprice * ihdepexrate) dcostprice,
convert(numeric(18,2),costprice  * ihexchangerate) ccostprice
from losspecialinvoiceheader lsh, vwShopSplInvItemAmount lsd
where ihinvoiceid=idinvoiceid and ihcancelled=0
and ihshopid=idshopid and round(((idUnitPrice)/idquantity),2) < costprice and
ihproforma=0 and idquantity <> 0 and ihtransfinished=1
union all
--FOR REEXPORTING TRANSACTION DETAILS
select reditemid, rehshopid, redcostprice,isnull(redquantity,0.00),
convert(numeric(18,2),round(((redUnitPrice )/redquantity),2)),
convert(numeric(18,2),round(((redUnitPrice * rehdepexrate)/redquantity),2)),
convert(numeric(18,2),round(((redUnitPrice * rehexchangerate)/redquantity),2)),
rehExportDate, convert(numeric(18,2),redcostprice * rehdepexrate) dcostprice,
convert(numeric(18,2),redcostprice  * rehexchangerate) ccostprice
from losExportHeader lih, losExportDetail lid
where rehExportID = redExportID and rehcancelled=0 and rehtype =''i''
and rehshopid = redshopid and round(((redUnitPrice )/redquantity),2) < redcostprice
and rehproforma=0 and redquantity <> 0'
GO
/****** Object:  View [dbo].[vwInterdivBillSettlementNo]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInterdivBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Created By : VinothMurugan V.
--Date   : 14/10/2010
--Purpose  : Showing Inter division bills is paid
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwInterdivBillSettlementNo] AS
select companyid, vendorid, max(setdate) setdate,
max(refno) refno, InterdivBillID, Sum(PaidAmount) PaidAmount
from (select vh.companyid, vh.vendorid, vh.vsdate setdate, vh.vsno refno, vd.InterdivBillID,
SettlementAmount PaidAmount
from vendorsettlementheader vh,
vendorsettlementdetail vd
where vh.companyid = vd.companyid
and vh.vsid = vd.vsid
and vd.InterdivBillID is not null
and vh.cancelled = 0
union all
select ph.phcompanyid, ph.phvendorid, ph.phpaymentdate setdate,
ph.phpaymentno refno, pd.pdIndevBillsID, pdPaidAmount PaidAmount
from AHQpaymentvoucherheader ph, AHQpaymentvoucherdetails pd
where ph.phcompanyid = pd.pdcompanyid
and ph.phpaymentid = pd.pdpaymentid
and ph.phcancelled = 0
and ph.phvendorid is not null
and pd.pdIndevBillsID is not null  and ph.phConfirmed = 1
) settledaccbills
group by companyid, vendorid, InterdivBillID'
GO
/****** Object:  View [dbo].[vwissuenoteGodown]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwissuenoteGodown]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwissuenoteGodown    Script Date: 18/01/2003 9:45:38 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwissuenoteGodown] as
sELECT aHQIssuenoteHeader.INHissuenoteid, aHQIssuenoteHeader.INHissuenoteNO,
aHQIssuenoteDetail.INDItemID, aHQIssuenoteDetail.INDQty, aHQIssuenoteDetail.INDgoodQtyRequested,
aHQIssueNoteMain.INMIssuenoteID, aHQIssueNoteMain.INMIssuenoteNO, aHQIssueNoteMain.INMIssuedate,
aHQIssueNoteMain.INMRemarks, aGodown.GodownName, aShops.ShopName, aItem.ItemCode,
aItem.ItemDescription,aitem.itemrate, aSize.SizeName, aPackingTypeCapacityDetail.Quantity,
aItemPackingDetail.PackingBarCode, aColor.ColorName,aunit.unitcode
FROM
{ oj ((((((((((aHQIssuenoteHeader aHQIssuenoteHeader INNER JOIN aHQIssueNoteMain aHQIssueNoteMain ON
aHQIssuenoteHeader.INHIssuenotemainID = aHQIssueNoteMain.INMIssuenoteID)
INNER JOIN aGodown aGodown ON
aHQIssuenoteHeader.INHGodownID = aGodown.GodownID)
INNER JOIN aHQIssuenoteDetail aHQIssuenoteDetail ON
aHQIssuenoteHeader.INHIssuenoteID = aHQIssuenoteDetail.INDIssuenoteID))
INNER JOIN aItem aItem ON
aHQIssuenoteDetail.INDItemID = aItem.ItemID)
INNER JOIN aShops aShops ON
aHQIssueNoteMain.INMShopID = aShops.ShopID)
INNER JOIN aItemPackingDetail aItemPackingDetail ON
aItem.ItemID = aItemPackingDetail.ItemID)
INNER JOIN vwitemretailpacking aPackingTypeCapacityDetail ON
aItem.UnitsID = aPackingTypeCapacityDetail.UnitsID and aitem.itemid = aPackingTypeCapacityDetail.itemid and
	aItemPackingDetail.packingtypeid=aPackingTypeCapacityDetail.packingtypeid)
LEFT OUTER JOIN aColor aColor ON
aItem.ColorID = aColor.ColorID)
LEFT OUTER JOIN aSize aSize ON
aItem.SizeID = aSize.SizeID)
left outer join aUnit aUnit on
	aitem.unitsid=aunit.unitid}'
GO
/****** Object:  View [dbo].[vwIssueNote]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwIssueNote]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on   : 12/12/02
-- Modified by  : leo
-- Comments  : v3
-----------------------------------------------------------------
-- Modified on  : 12/06/2003,20/09/2005
-- Modified by  : Kishore, Aneesh [Added unitname to show in RPTissuetoshop.rpt]
-- Comments  : Added columns inhCancelled and inhShopReqno
--     Removed column quantity
--     Removed table vwItemRetailPacking
--             (All on comparison with v2)
--------------------------------------------------------------------------------
-- Modified on : 29/03/2010
-- Modified by : Regin
-- Comments    :
--     Added column grdreqcomments [Item Remarks]
--------------------------------------------------------------------------------
create VIEW [dbo].[vwIssueNote] AS
SELECT
aHQIssuenoteHeader.INHissuenoteid, aHQIssuenoteHeader.INHissuenoteNO, aHQIssuenoteDetail.INDItemID, aHQIssuenoteDetail.INDQty,
aHQIssuenoteDetail.INDgoodQtyRequested, aHQIssueNoteMain.INMIssuenoteID, aHQIssueNoteMain.INMIssuenoteNO,
aHQIssueNoteMain.INMIssuedate, aHQIssueNoteMain.INMRemarks,
aGodown.GodownName,
aShops.ShopName,
mosGoodsRequestHeader.GRHrequestNO,
aItem.ItemCode, aItem.ItemDescription,aitem.itemrate,
aSize.SizeName,
aItemPackingDetail.PackingBarCode,
aColor.ColorName,aunit.unitcode,aunit.unitname, inhCancelled, inhShopReqno, grdreqcomments
FROM
{ oj ((((((((((aHQIssuenoteHeader aHQIssuenoteHeader INNER JOIN aHQIssueNoteMain aHQIssueNoteMain ON
aHQIssuenoteHeader.INHIssuenotemainID = aHQIssueNoteMain.INMIssuenoteID)
INNER JOIN aGodown aGodown ON
aHQIssuenoteHeader.INHGodownID = aGodown.GodownID)
INNER JOIN aHQIssuenoteDetail aHQIssuenoteDetail ON
aHQIssuenoteHeader.INHIssuenoteID = aHQIssuenoteDetail.INDIssuenoteID)
INNER JOIN mosGoodsRequestHeader mosGoodsRequestHeader ON
aHQIssueNoteMain.INMRequestID = mosGoodsRequestHeader.GRHrequestID AND
aHQIssueNoteMain.INMShopID = mosGoodsRequestHeader.GRHshopID
inner join mosGoodsRequestDetail on GRHshopID=GRDshopID and GRHrequestID=GRDrequestID
		and INDItemID=GRDitemID)
INNER JOIN aItem aItem ON
aHQIssuenoteDetail.INDItemID = aItem.ItemID)
INNER JOIN aShops aShops ON
aHQIssueNoteMain.INMShopID = aShops.ShopID)
INNER JOIN aItemPackingDetail aItemPackingDetail ON
aItem.ItemID = aItemPackingDetail.ItemID)
INNER JOIN
Adminv2.dbo.aPackingTypeCapacityDetail b ON
aItemPackingDetail.packingtypeid = b.packingtypeid AND
aItem.UnitsId = b.UnitsId ANd
b.Quantity = 1
)
LEFT OUTER JOIN aColor aColor ON
aItem.ColorID = aColor.ColorID)
LEFT OUTER JOIN aSize aSize ON
aItem.SizeID = aSize.SizeID)
left outer join aUnit aUnit on
aitem.unitsid=aunit.unitid}'
GO
/****** Object:  View [dbo].[vwShopSplInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplInvoiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified on 	: 26/11/2003
-- Modified by		: Kishore
-- Comments		: Added SettledAmt column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwShopSplInvoiceSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.losSpInvoiceId
invoiceid, cd.shopid, cd.SettlementAmount SettledAmt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.losSpInvoiceId is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.posspinvoiceid invoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.posspinvoiceid is not null) settledaccinvoices
group by companyid, customerid, shopid, invoiceid'
GO
/****** Object:  View [dbo].[vwinvoices]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoices]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[VwItemSalesGrouped]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VwItemSalesGrouped]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created On  : 01/05/2008
-- Created By  : Shinu
-- Comments    : Created for a new Report  [rptSalesAndStock]
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Create View [dbo].[VwItemSalesGrouped] as
select ItemID,ShopID,sum(Qty)Qty,soldDate from VwItemDetailedSales group By ItemID,ShopID,soldDate
--spSalesAndStock 19,''20080501'',''20080501'''
GO
/****** Object:  StoredProcedure [dbo].[spSalesPersonInvandSettled]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSalesPersonInvandSettled]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created by : Nidheesh P V
--Created on :12/11/2010
--Comments : To show the details regarding POS Invoices and settlement against a Sales Person
--spSalesPersonInvandSettled1 1,1,''20100101'',''20101120''
--Alter by : Aadyakumar.D.V
--Altered on :18/03/2011
--Comments :report want to show individual sale persons report also,so new parameter is added as @userid
--spSalesPersonInvandSettled1 1,1,''20100101'',''20101120'',0
CREATE proc [dbo].[spSalesPersonInvandSettled](
@intCmpId as int,
@IntDeptId as int,
@Fromdate as varchar(12),
@Todate as varchar(12),
@userid as int)
as
begin
set nocount on
if exists(select type,* from sysobjects where type=''u'' and name = ''tempSettled'')
begin
drop table tempSettled
end
select distinct InvoiceId,ShopId,sum(SettledAmount)over (partition by InvoiceId,ShopId)SettledAmount
into tempSettled
from
(
select distinct rd.posinvoiceid[InvoiceId],rd.shopid[ShopId],
convert(numeric(18,2),sum(rh.Amount*rh.depexrate)over (partition by rd.posinvoiceid,rd.shopid))[SettledAmount]
--convert(numeric(18,2),sum(rh.Amount*rh.exchangerate)over (partition by rd.posinvoiceid,rd.shopid)) creceipts
from receiptvoucherheader rh inner join receiptvoucherdetails rd
on rh.ReceiptID=rd.ReceiptID and rh.CompanyID=rd.CompanyID and Cancelled=0
where rd.posinvoiceid is not null --and rd.posinvoiceid=2578
and rh.CompanyID=@intCmpId and (rh.DepartmentID=@IntDeptId or @IntDeptId=0)
and ReceiptDate>=@Fromdate and ReceiptDate<=@Todate
union all
select cd.losinvoiceid,cd.shopid,cd.SettlementAmount[depAmount]
from customersettlementheader ch inner join
customersettlementdetail cd on ch.CSID=cd.CSID and ch.CompanyID=cd.CompanyID and ch.Cancelled=0
where cd.losinvoiceid is not null --and cd.losinvoiceid=2578 --and cd.shopid=4
and ch.CompanyID=@intCmpId and (ch.DepartmentID=@IntDeptId or @IntDeptId=0)
and CSDATE>=@Fromdate and CSDATE<=@Todate
)v
-----------------------------------------------------------------------------------
if @userid=0
begin
select ihCompanyId,ihShopID,ihsalespersonid,isnull(Spername,''GENERAL'') salesperson,
ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ts.SettledAmount,
convert(numeric(18,2),(ihInvoiceAmount*ihdepexrate))DepInvAmount
--convert(numeric(18,2),(ihInvoiceAmount*ihexchangerate))ComInvAmount
from losinvoiceheader ih
inner join tempSettled ts on ih.ihInvoiceID=ts.InvoiceId and ih.ihShopID=ts.ShopId
left outer join asalespersonmaster on ihsalespersonid=Sperid
where ihtype =''i'' and ihcancelled=0
and ihCompanyId=@intCmpId and (ihDepartmentID=@IntDeptId or @IntDeptId=0)
and ihInvoiceDate>=@Fromdate and ihInvoiceDate<=@Todate
end
else
begin
select ihCompanyId,ihShopID,ihsalespersonid,isnull(Spername,''GENERAL'') salesperson,
ihInvoiceID,ihInvoiceNo,ihInvoiceDate,ts.SettledAmount,
convert(numeric(18,2),(ihInvoiceAmount*ihdepexrate))DepInvAmount
--convert(numeric(18,2),(ihInvoiceAmount*ihexchangerate))ComInvAmount
from losinvoiceheader ih
inner join tempSettled ts on ih.ihInvoiceID=ts.InvoiceId and ih.ihShopID=ts.ShopId
left outer join asalespersonmaster on ihsalespersonid=Sperid
where ihtype =''i'' and ihcancelled=0
and ihCompanyId=@intCmpId and (ihDepartmentID=@IntDeptId or @IntDeptId=0)
and ihInvoiceDate>=@Fromdate and ihInvoiceDate<=@Todate and  ihsalespersonid=@userid
end
--and sperid is not null
drop table tempSettled
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwSupplierLedger]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSupplierLedger]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
/****** Object:  View [dbo].[vwTotalTax]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotalTax]'))
EXEC dbo.sp_executesql @statement = N'
CREATE  view [dbo].[vwTotalTax]
-- Modified by  : Jyothish S R
-- Date         : 03/11/2011
-- d-specialinvoice
-- e Exchange
-- c goods Return
---p pos
---s Shop service
--sbi service booking invoices
---lp Local purchase
As
select companyid,departmentid,shopid,poshBillNo,billdate,amount,camount,damount,isnull(vw.TaxPercentage,0) as TaxPercentage,TaxAmount,CTaxAmount,DTaxAmount,transtype,''SALES'' as Type ,''SALES'' as  TrType,vw.posdItemTaxCategory,isnull(TaxType,0)TaxType
from vwCollectedSalesTax vw left outer join aTaxCategoryMaster on aTaxCategoryMaster.TaxId=vw.posdItemTaxCategory --where  --billdate between ''20111001'' and ''20111005''
union all
select companyid,departmentid,shopid ,IhInvoiceNo,billdate,amount,camount,damount,vw.TaxPercentage,TaxAmount,CTaxAmount,DTaxAmount,case when transtype=''c'' then ''goods return'' else
case when transtype=''d'' then ''special invoice return'' else transtype end  end transtype  ,''SALES'' as Type ,''SALESRETURN'' as  TrType,vw.idItemTaxCategory,isnull(TaxType,0) from vwRefundedSalesTax vw left outer join aTaxCategoryMaster on aTaxCategoryMaster.TaxId=vw.idItemTaxCategory --where --billdate between ''20111001'' and ''2
union all
select 1 as companyid,(select DepartmentID  from  ashops where ashops.ShopID= dt.lpdShopID )DepartmentID,dt.lpdShopID,lphBillNo,lphBillDate, sum(lpdItemUnitPrice+isnull(lpdItemTaxAmount,0))  as Amount, sum(lpdItemUnitPrice+isnull(lpdItemTaxAmount,0))*lphExchangeRate  as CAmount ,
sum(lpdItemUnitPrice+isnull(lpdItemTaxAmount,0))*lphDepExRate dAmount ,isnull(lpdItemTaxPercentage,0) as lpdItemTaxPercentage ,sum(isnull(lpdItemTaxAmount,0))  as TaxAmount, sum(isnull(lpdItemTaxAmount,0))*lphExchangeRate  as CTaxAmount ,
sum(lpdItemUnitPrice+isnull(lpdItemTaxAmount,0))*lphDepExRate dTaxAmount ,''local purchase'' as transtype ,''PURCHASE'' as Type ,''LocalPURCHASE'' as  TrType , isnull(dt.lpdItemTaxCategory,0),isnull(TaxType,0) from loslocalpurchaseheader h inner join LosLocalPurchaseDetail dt on
h.lphShopID=dt.lpdShopID and h.lphBillID=dt.lpdBillID
left outer join aTaxCategoryMaster on aTaxCategoryMaster.TaxId=dt.lpdItemTaxCategory where lphCancelled=0   --and lphBillDate between ''20111001'' and ''20111005''
group by lphExchangeRate,lphDepExRate,dt.lpdShopID,lphBillNo,lphBillDate,lpdItemTaxPercentage  ,dt.lpdItemTaxCategory,TaxType'
GO
/****** Object:  View [dbo].[vwDailySalesCollectionGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwDailySalesCollectionDetGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDetGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwDailySalesCollectionDet]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollectionDet]'))
EXEC dbo.sp_executesql @statement = N'
---Created BY :Shinu
---Created ON :13/01/2008
---Comments   :For Sales And Collection Detailed Report
----------------------------------------------------------------------------------------------
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 30/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
-----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollectionDet] AS
select companyid,departmentid, shopid, billdate,
convert(numeric(18, 2), sum(cashsales)) cashsales,
convert(numeric(18, 2), sum(dcashsales)) dcashsales,
convert(numeric(18, 2), sum(ccashsales)) ccashsales,
convert(numeric(18, 2), sum(receipts)) receipts,
convert(numeric(18, 2), sum(dreceipts)) dreceipts,
convert(numeric(18, 2), sum(creceipts)) creceipts,
convert(numeric(18, 2), sum(payments)) payments ,
convert(numeric(18, 2), sum(dpayments)) dpayments ,
convert(numeric(18, 2), sum(cpayments)) cpayments ,
convert(numeric(18, 2), sum(creditsales)) creditsales,
convert(numeric(18, 2), sum(dcreditsales)) dcreditsales,
convert(numeric(18, 2), sum(ccreditsales)) ccreditsales,
convert(numeric(18, 2), sum(creditcard)) as creditcard,
convert(numeric(18, 2), sum(dcreditcard)) as dcreditcard,
convert(numeric(18, 2), sum(ccreditcard)) as ccreditcard,
convert(numeric(18, 2), sum(debitcard)) as debitcard,
convert(numeric(18, 2), sum(ddebitcard)) as ddebitcard,
convert(numeric(18, 2), sum(cdebitcard)) as cdebitcard,
convert(numeric(18, 2), sum(localpurchase)) as localpurchase,
convert(numeric(18, 2), sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18, 2), sum(clocalpurchase)) as clocalpurchase,
convert(numeric(18, 2), sum(Exchange)) as Exchange,
convert(numeric(18, 2), sum(dExchange)) as dExchange,
convert(numeric(18, 2), sum(cExchange)) as cExchange,
convert(numeric(18, 2), sum(GoodsReturn)) as GoodsReturn,
convert(numeric(18, 2), sum(dGoodsReturn)) as dGoodsReturn,
convert(numeric(18, 2), sum(cGoodsReturn)) as cGoodsReturn
--RefNo-2 start -------------------
,convert(numeric(18, 2), sum(PdChequeSales)) PdChequeSales,
convert(numeric(18, 2), sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18, 2), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------
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 ---------------------------------------------
from vwCAshSalesDet 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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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
--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
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,2),sum(rd.AmountReceived)) receipts,
convert(numeric(18,2),sum(rd.AmountReceived )) dreceipts,
convert(numeric(18,2),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
--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,2),sum(Amount)) receipts,
convert(numeric(18,2),sum(Amount * depexrate)) dreceipts,
convert(numeric(18,2),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
--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,2),sum(phAmount)) as payments,
convert(numeric(18,2),sum(phAmount* phdepexrate)) as dpayments,
convert(numeric(18,2),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
--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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),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
--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
--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
--RefNo-2 ends -------------------
from vwCAshSalesDet 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
/****** Object:  View [dbo].[vwDailySalesCollection_shopwiseGSTSeparately]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection_shopwiseGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwDailySalesCollection_shopwise]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection_shopwise]'))
EXEC dbo.sp_executesql @statement = N'
--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)
----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollection_shopwise] AS
select companyid,departmentid, shopid, billdate,
convert(numeric(18, 2), sum(cashsales)) cashsales,
convert(numeric(18, 2), sum(dcashsales)) dcashsales,
convert(numeric(18, 2), sum(ccashsales)) ccashsales,
convert(numeric(18, 2), sum(receipts)) receipts,
convert(numeric(18, 2), sum(dreceipts)) dreceipts,
convert(numeric(18, 2), sum(creceipts)) creceipts,
convert(numeric(18, 2), sum(payments)) payments ,
convert(numeric(18, 2), sum(dpayments)) dpayments ,
convert(numeric(18, 2), sum(cpayments)) cpayments ,
convert(numeric(18, 2), sum(creditsales)) creditsales,
convert(numeric(18, 2), sum(dcreditsales)) dcreditsales,
convert(numeric(18, 2), sum(ccreditsales)) ccreditsales,
convert(numeric(18, 2), sum(creditcard)) as creditcard,
convert(numeric(18, 2), sum(dcreditcard)) as dcreditcard,
convert(numeric(18, 2), sum(ccreditcard)) as ccreditcard,
convert(numeric(18, 2), sum(debitcard)) as debitcard,
convert(numeric(18, 2), sum(ddebitcard)) as ddebitcard,
convert(numeric(18, 2), sum(cdebitcard)) as cdebitcard,
convert(numeric(18, 2), sum(localpurchase)) as localpurchase,
convert(numeric(18, 2), sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18, 2), sum(clocalpurchase)) as clocalpurchase
--RefNo-2 start -------------------
,convert(numeric(18, 2), sum(PdChequeSales)) PdChequeSales,
convert(numeric(18, 2), sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18, 2), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------
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 ---------------------------------------------
from vwCashSales 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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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 -------------------
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-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,2),sum(rd.AmountReceived)) receipts,
--convert(numeric(18,2),sum(rd.AmountReceived )) dreceipts,
--convert(numeric(18,2),sum(rd.AmountReceived )) creceipts,
------------------ Benzigar code -------------------------------------------
convert(numeric(18,2),sum(rh.customeramount)) receipts,
convert(numeric(18,2),sum(rh.Amount*rh.depexrate )) dreceipts,
convert(numeric(18,2),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,2),sum(rd.AmountReceived)) receipts,
----convert(numeric(18,2),sum(rd.AmountReceived*rh.depexrate)) dreceipts,
----convert(numeric(18,2),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,2),sum(Amount)) receipts,
convert(numeric(18,2),sum(Amount * depexrate)) dreceipts,
convert(numeric(18,2),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,2),sum(phAmount)) as payments,
convert(numeric(18,2),sum(phAmount* phdepexrate)) as dpayments,
convert(numeric(18,2),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 -------------------
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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),sum(lphbillamount*lphexchangerate)) as clocalpurchase
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,
0.0 as cPdChequeSales
--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) summary
group by companyid ,departmentid, shopid, billdate'
GO
/****** Object:  View [dbo].[vwbookservicesettlements]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservicesettlements]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwbookservicesettlements    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwbookservicesettlements    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwbookservicesettlements    Script Date: 31/07/2002 2:00:32 PM ******/
CREATE view [dbo].[vwbookservicesettlements] as
select st.companyid, st.shopid, st.serviceinvoiceid, st.customerid, 0.0 as invoiceamount,
max(receiptdate) receiptdate, sum(settledamt) settledamt
from(select rh.companyid, rd.shopid, Posserviceinvoiceid serviceinvoiceid, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived) settledamt from
receiptvoucherheader rh, receiptvoucherdetails rd where rh.companyid=rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled = 0 and rd.posserviceinvoiceid is not null
group by rh.companyid, rd.shopid, rd.posserviceinvoiceid, rh.customerid
union all
select ch.companyid, cd.shopid, losserinvoiceid, ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt from
customersettlementheader ch, customersettlementdetail cd where ch.companyid = cd.companyid
and ch.csid = cd.csid and ch.cancelled = 0 and cd.losserinvoiceid is not null
group by ch.companyid, cd.shopid, cd.losserinvoiceid, ch.customerid) st
group by st.companyid, st.shopid, st.serviceinvoiceid, st.customerid'
GO
/****** Object:  View [dbo].[vwBookServiceSettlementNo]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwBookServiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified by    :    Kishore
-- Modified on    :    26/11/2003
-- Comments       :    Added settledAmt column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwBookServiceSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) settledamt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.losserinvoiceid
invoiceid, cd.shopid, cd.SettlementAmount SettledAmt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.losserinvoiceid is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.Posserviceinvoiceid invoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.Posserviceinvoiceid is not null) settledaccinvoices
group by companyid, customerid, shopid,  invoiceid'
GO
/****** Object:  View [dbo].[vwDebitNoteSettlementNo]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebitNoteSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- Modified on    : 26/11/2003
-- Modified by    : Kishore
-- Comments       : Added SettledAmt
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDebitNoteSettlementNo] AS
select companyid, customerid, max(setdate) setdate, max(refno) refno,
dcnid, sum(settledamt ) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno,
cd.dcnid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.dcnid is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.dcnid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.dcnid is not null) settledaccinvoices
group by companyid, customerid, dcnid'
GO
/****** Object:  View [dbo].[vwSalesImportProdWiseGSTSeparately]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesImportProdWiseGSTSeparately]'))
EXEC dbo.sp_executesql @statement = N'
-- 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 [dbo].[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
/****** Object:  View [dbo].[vwSalesImportProdWise]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesImportProdWise]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwSalesImportProdWise] 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
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
FROM vwSalesMarginAndPerc 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
FROM vwPurchaseBillDetail 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
/****** Object:  View [dbo].[vwSellingPrice]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSellingPrice]'))
EXEC dbo.sp_executesql @statement = N'
--Created by : Bijesh.B
--Date       : 19-03-2012
--Ticket id  : ILS-809156
CREATE view [dbo].[vwSellingPrice] as
select ddDespatchID,itemid,PackingTypeid,sellingPrice as SellPrice
from losshopitemshipmentdetail Hdr
inner join MEiDespatchToShopDetail Dtl on hdr.itemid=dtl.ddItemID
	and hdr.PackingTypeid = dtl.ddpackingtypeid'
GO
/****** Object:  View [dbo].[vwPOBillCostingDespatchArrival]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPOBillCostingDespatchArrival]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwPOBillCostingDespatchArrival] AS
select a.*,pbhBillID,pbhBillNo,pbhBillDate,pbhRemarks,chCostingID,chCostingNo,chCostingDate,chRemarks,
	dhDespatchNoteID,dhDespatchNoteNo,dnmDespatchNoteDate,dnmRemarks,ahArrivalID,Location,LocationID,
	LocationName,ahArrivalNo,ahArrivalDate,ahRemarks from vwRequestQuotationPurchase a
Left Outer Join
(select  pbhPoID,pbhBillID,pbhBillNo,pbhBillDate,pbhRemarks,chCostingID,chCostingNo,chCostingDate,chRemarks,
	dhDespatchNoteID,dhDespatchNoteNo,dnmDespatchNoteDate,dnmRemarks,ahArrivalID,Location,LocationID,
	LocationName,ahArrivalNo,ahArrivalDate,ahRemarks From losppurchaseBillHeader
Left Outer Join loacostingHeader ON chBillID=pbhBillID and chCancelled=0
Left Outer Join
	(select  dnmBillID,dhDespatchNoteID,dhDespatchNoteNo,dnmDespatchNoteDate,dnmRemarks,ahArrivalID,
		 LocationID,LocationName,ahArrivalNo,ahArrivalDate,ahRemarks,Location From
	(select dnmBillID,dhDespatchNoteID,dhDespatchNoteNo,dnmDespatchNoteDate,dhGodownID,dhShopID,dnmRemarks from ahqDespatchnoteMain
		Inner Join ahqDespatchnoteHeader ON dhDespatchNoteMainID=dnmDespatchNoteID)Despatch
	Left Outer Join
	(select ahArrivalID,ahLocalGodownID LocationID,GodownName LocationName,ahArrivalNo,
		ahArrivalDate,ahDespatchNoteID,ahRemarks,''G'' Location From  LOiArrivalHeader
	Left Outer Join  aGodown ON ahLocalGodownID=GodownID where ahArrivalType=''H'' and ahCancelled=0
	Union All
	select gahArrivalId,gahShopID,ShopName,gahArrivalNo,gahArrivalDate,gahHQDespatchID,gahRemarks,''S'' From losGoodsArrivalToShopHeader
	Left Outer Join aShops ON gahShopID=ShopID Where isnull(gahHQDespatchID,0) <>0 and gahCancelled=0 )Arrivals
	ON dhDespatchNoteID=ahDespatchNoteID)DespatchArrival
ON pbhBillID=dnmBillID
where pbhCancelled=0)BillCostingDespatchArrival
ON pohPoID=pbhPoID'
GO
/****** Object:  View [dbo].[vwshipmentwisegodownstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwisegodownstock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentwisegodownstock    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwshipmentwisegodownstock]
as
select gsgodownid, gs.gsitemid, gs.gsshipmentid, gs.gsstock, gs.gsopeningstock,
gs.gsbadstock, gs.gsopeningbadstock, sh.shipcost, a.itemcategoryid from
vwshipmentcostprice sh, moigodownstock gs, aitem a where gs.gsitemid=sh.itemid
and gs.gsshipmentid=sh.shipmentid and a.itemid=gs.gsitemid and
(gs.gsstock <> 0 or gs.gsbadstock <> 0 )'
GO
/****** Object:  View [dbo].[vwsalesSumYearWise]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesSumYearWise]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Prasanth Joseph
--Created On : 08-07-2009
--Created For : Year Wise Item Sales
------------------------------------
Create view [dbo].[vwsalesSumYearWise] as
select sum(camount)camount ,sum(CostPrice)CostPrice,syear from vwItemDetailedSales
group by syear'
GO
/****** Object:  View [dbo].[vwShopAccInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopAccInvoiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 	        : 26/11/2003
-- Modified by		: Kishore
-- Comments		: Added SettedAmt column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopAccInvoiceSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
accinvoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.losaccinvoiceid
accinvoiceid, cd.shopid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.losaccinvoiceid is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.posaccountsinvoiceid accinvoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.posaccountsinvoiceid is not null) settledaccinvoices
group by companyid, customerid, shopid, accinvoiceid'
GO
/****** Object:  View [dbo].[vwCreditorAge]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditorAge]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwCreditorAge    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 26/10/2002
--Modified by 		: leo
--created as second batch 0n 09/11/2002 by hariharan from fi-es10
--verified by leo
CREATE view [dbo].[vwCreditorAge] as
-- 1. Head quaters purchase bill
select b.pbhCompanyID companyid, null as shopid, b.pbhDepartmentID departmentid,
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks, pbhvendorRefNo referenceno,
b.pbhbilldate, b.pbhDueDateforPayment duedate,  case when isnull(max(pvd.PaidAmount),0) > 0 then
max(pvd.settleddate) when isnull(max(sd.paidamount),0)  > 0 then max(sd.settleddate) else null end settleddate,
b.pbhBillAmount, isnull(max(pvd.PaidAmount),0) + isnull(max(sd.paidamount),0)  as PaidAmount,
''0 - 30'' as Due, ''fpb'' as type, b.updatetime
from LOspPurchaseBillHeader b left outer join vwHQPBillPaymentDetails  pvd
on b.pbhBillID = pvd.pdBillsID and b.pbhCompanyID = pvd.pdCompanyID
left outer join vwhqpbillsettlementdetails sd on b.pbhbillid = sd.pbhbillid and
b.pbhcompanyid = sd.companyid
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and
(getdate() - b.pbhBillDate between 0 and 30)
group by b.pbhCompanyID, b.pbhDepartmentID,b.pbhBillID,  b.pbhVendorID,  b.pbhbillno,
b.pbhremarks, b.pbhvendorrefno, b.pbhbilldate, b.updatetime, b.pbhduedateforpayment,
b.pbhBillAmount
union all
select b.pbhCompanyID companyid, null as shopid, b.pbhDepartmentID departmentid,
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks, pbhvendorRefNo referenceno,
b.pbhbilldate, b.pbhDueDateforPayment duedate,  case when isnull(max(pvd.PaidAmount),0) > 0 then
max(pvd.settleddate) when isnull(max(sd.paidamount),0)  > 0 then max(sd.settleddate) else null end settleddate,
b.pbhBillAmount, isnull(max(pvd.PaidAmount),0) + isnull(max(sd.paidamount),0)  as PaidAmount,
''31 - 60'' as Due, ''fpb'' as type, b.updatetime
from LOspPurchaseBillHeader b left outer join vwHQPBillPaymentDetails  pvd
on b.pbhBillID = pvd.pdBillsID and b.pbhCompanyID = pvd.pdCompanyID
left outer join vwhqpbillsettlementdetails sd on b.pbhbillid = sd.pbhbillid and
b.pbhcompanyid = sd.companyid
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and
(getdate() - b.pbhBillDate between 31 and 60)
group by b.pbhCompanyID, b.pbhDepartmentID,b.pbhBillID,  b.pbhVendorID,  b.pbhbillno,
b.pbhremarks, b.pbhvendorrefno, b.pbhbilldate, b.updatetime, b.pbhduedateforpayment,
b.pbhBillAmount
union all
select b.pbhCompanyID companyid, null as shopid, b.pbhDepartmentID departmentid,
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks, pbhvendorRefNo referenceno,
b.pbhbilldate, b.pbhDueDateforPayment duedate,  case when isnull(max(pvd.PaidAmount),0) > 0 then
max(pvd.settleddate) when isnull(max(sd.paidamount),0)  > 0 then max(sd.settleddate) else null end settleddate,
b.pbhBillAmount, isnull(max(pvd.PaidAmount),0) + isnull(max(sd.paidamount),0)  as PaidAmount,
''61 - 90'' as Due, ''fpb'' as type, b.updatetime
from LOspPurchaseBillHeader b left outer join vwHQPBillPaymentDetails  pvd
on b.pbhBillID = pvd.pdBillsID and b.pbhCompanyID = pvd.pdCompanyID
left outer join vwhqpbillsettlementdetails sd on b.pbhbillid = sd.pbhbillid and
b.pbhcompanyid = sd.companyid
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and
(getdate() - b.pbhBillDate between 61 and 90)
group by b.pbhCompanyID, b.pbhDepartmentID,b.pbhBillID,  b.pbhVendorID,  b.pbhbillno,
b.pbhremarks, b.pbhvendorrefno, b.pbhbilldate, b.updatetime, b.pbhduedateforpayment,
b.pbhBillAmount
union all
select b.pbhCompanyID companyid, null as shopid, b.pbhDepartmentID departmentid,
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks, pbhvendorRefNo referenceno,
b.pbhbilldate, b.pbhDueDateforPayment duedate,  case when isnull(max(pvd.PaidAmount),0) > 0 then
max(pvd.settleddate) when isnull(max(sd.paidamount),0)  > 0 then max(sd.settleddate) else null end settleddate,
b.pbhBillAmount, isnull(max(pvd.PaidAmount),0) + isnull(max(sd.paidamount),0)  as PaidAmount,
'' > 90'' as Due, ''fpb'' as type, b.updatetime
from LOspPurchaseBillHeader b left outer join vwHQPBillPaymentDetails  pvd
on b.pbhBillID = pvd.pdBillsID and b.pbhCompanyID = pvd.pdCompanyID
left outer join vwhqpbillsettlementdetails sd on b.pbhbillid = sd.pbhbillid and
b.pbhcompanyid = sd.companyid
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and
(getdate() - b.pbhBillDate > 90)
group by b.pbhCompanyID, b.pbhDepartmentID,b.pbhBillID,  b.pbhVendorID,  b.pbhbillno,
b.pbhremarks, b.pbhvendorrefno, b.pbhbilldate, b.updatetime, b.pbhduedateforpayment,
b.pbhBillAmount
-- 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, case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(psd.paidamount),0)  > 0 then max(psd.settleddate) else null end settleddate,
sum(lpdItemUnitPrice) billamount,
isnull(max(psd.PaidAmount),0) + isnull(max(pmt.paidamount),0)  as PaidAmount,
''0 - 30'' as Due, ''lpb'' as type, ph.updatetime
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd
left outer join vwhqposbillsettlementdetails psd on
pd.lpdshopid = psd.shopid and pd.lpdbillid = psd.lphbillid
left outer join vwposBillsettlementpay pmt on
pd.lpdshopid = pmt.pdshopid  and pd.lpdbillid = pmt.pdposlpbillid
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and
(getdate() - ph.lphBillDate between 0 and 30)
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID,
ph.lphVendorID,ph.lphbillno, ph.lphremarks, ph.lphvendorbillno,
ph.lphbilldate, ph.updatetime, ph.lphduedateforpayment
union all
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,
ph.lphbilldate, lphDueDateforPayment, case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(psd.paidamount),0)  > 0 then max(psd.settleddate) else null end settleddate,
sum( lpdItemUnitPrice) billamount,
isnull(max(psd.PaidAmount),0) + isnull(max(pmt.paidamount),0)  as PaidAmount,
''31 - 60'' as Due, ''lpb'' as type, ph.updatetime
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd
left outer join vwhqposbillsettlementdetails psd on
pd.lpdshopid = psd.shopid and pd.lpdbillid = psd.lphbillid
left outer join vwposBillsettlementpay pmt on
pd.lpdshopid = pmt.pdshopid  and pd.lpdbillid = pmt.pdposlpbillid
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and
(getdate() - ph.lphBillDate between 31 and 60)
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID,
ph.lphVendorID,ph.lphbillno, ph.lphremarks, ph.lphvendorbillno,
ph.lphbilldate, ph.updatetime, ph.lphduedateforpayment
union all
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,
ph.lphbilldate, lphDueDateforPayment, case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(psd.paidamount),0)  > 0 then max(psd.settleddate) else null end settleddate,
sum(lpdItemUnitPrice) billamount,
isnull(max(psd.PaidAmount),0) + isnull(max(pmt.paidamount),0)  as PaidAmount,
''61 - 90'' as Due, ''lpb'' as type, ph.updatetime
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd
left outer join vwhqposbillsettlementdetails psd on
pd.lpdshopid = psd.shopid and pd.lpdbillid = psd.lphbillid
left outer join vwposBillsettlementpay pmt on
pd.lpdshopid = pmt.pdshopid  and pd.lpdbillid = pmt.pdposlpbillid
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and
(getdate() - ph.lphBillDate between 61 and 90)
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID,
ph.lphVendorID,ph.lphbillno, ph.lphremarks, ph.lphvendorbillno,
ph.lphbilldate, ph.updatetime, ph.lphduedateforpayment
union all
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,
ph.lphbilldate, lphDueDateforPayment, case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(psd.paidamount),0)  > 0 then max(psd.settleddate) else null end settleddate,
sum(lpdItemUnitPrice) billamount,
isnull(max(psd.PaidAmount),0) + isnull(max(pmt.paidamount),0)  as PaidAmount,
'' > 90'' as Due, ''lpb'' as type, ph.updatetime
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd
left outer join vwhqposbillsettlementdetails psd on
pd.lpdshopid = psd.shopid and pd.lpdbillid = psd.lphbillid
left outer join vwposBillsettlementpay pmt on
pd.lpdshopid = pmt.pdshopid  and pd.lpdbillid = pmt.pdposlpbillid
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and
(getdate() - ph.lphBillDate > 90)
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID,
ph.lphVendorID,ph.lphbillno, ph.lphremarks, ph.lphvendorbillno,
ph.lphbilldate, ph.updatetime, ph.lphduedateforpayment
union all
-- 3.accounts bill
select b.CompanyID, null as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno, b.remarks,
b.ReferenceNo, b.billdate,
dateadd(dd,b.dueperiod,b.billdate), case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(vs.paidamount),0) > 0 then max(vs.settleddate) else null end settleddate,sum(bd.amount) billamount,
isnull(max(vs.PaidAmount),0) + isnull(max(pmt.paidamount),0) as PaidAmount,
''0 - 30'' as Due , ''accb'' as type, b.updatetime
from billsdebitdetails bd, bills b
left outer join vwaccBillsettlementpay pmt on
b.companyid = pmt.pdcompanyid and b.billsid = pmt.pdaccbillsid
left outer join vwaccbillvs vs on
b.companyid = vs.companyid and b.billsid = vs.billid
where b.companyid = bd.companyid and b.billsid = bd.billsid and
b.cancelled = 0 and b.cashpurchase = 0 and (getdate() - b.BillDate between 0 and 30)
group by b.CompanyID, b.DepartmentID, b.BillsID, b.VendorID, b.billsno, b.remarks,
b.referenceno, b.billdate, b.updatetime, b.dueperiod
union all
select b.CompanyID, null as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno, b.remarks,
b.ReferenceNo, b.billdate,
dateadd(dd,b.dueperiod,b.billdate), case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(vs.paidamount),0) > 0 then max(vs.settleddate) else null end settleddate,sum(bd.amount) billamount,
isnull(max(vs.PaidAmount),0) + isnull(max(pmt.paidamount),0) as PaidAmount,
''31 - 60'' as Due , ''accb'' as type, b.updatetime
from billsdebitdetails bd, bills b
left outer join vwaccBillsettlementpay pmt on
b.companyid = pmt.pdcompanyid and b.billsid = pmt.pdaccbillsid
left outer join vwaccbillvs vs on
b.companyid = vs.companyid and b.billsid = vs.billid
where b.companyid = bd.companyid and b.billsid = bd.billsid and
b.cancelled = 0 and b.cashpurchase = 0 and (getdate() - b.BillDate between 31 and 60)
group by b.CompanyID, b.DepartmentID, b.BillsID, b.VendorID, b.billsno, b.remarks,
b.referenceno, b.billdate, b.updatetime, b.dueperiod
union all
select b.CompanyID, null as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno, b.remarks,
b.ReferenceNo, b.billdate,
dateadd(dd,b.dueperiod,b.billdate), case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(vs.paidamount),0) > 0 then max(vs.settleddate) else null end settleddate,sum(bd.amount) billamount,
isnull(max(vs.PaidAmount),0) + isnull(max(pmt.paidamount),0) as PaidAmount,
''61 - 90'' as Due , ''accb'' as type,
b.updatetime
from billsdebitdetails bd, bills b
left outer join vwaccBillsettlementpay pmt on
b.companyid = pmt.pdcompanyid and b.billsid = pmt.pdaccbillsid
left outer join vwaccbillvs vs on
b.companyid = vs.companyid and b.billsid = vs.billid
where b.companyid = bd.companyid and b.billsid = bd.billsid and
b.cancelled = 0 and b.cashpurchase = 0 and (getdate() - b.BillDate between 61 and 90)
group by b.CompanyID, b.DepartmentID, b.BillsID, b.VendorID, b.billsno, b.remarks,
b.referenceno, b.billdate, b.updatetime, b.dueperiod
union all
select b.CompanyID, null as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno, b.remarks,
b.ReferenceNo, b.billdate,
dateadd(dd,b.dueperiod,b.billdate), case when isnull(max(pmt.PaidAmount),0) > 0 then max(pmt.settleddate)
when isnull(max(vs.paidamount),0) > 0 then max(vs.settleddate) else null end settleddate,sum(bd.amount) billamount,
isnull(max(vs.PaidAmount),0) + isnull(max(pmt.paidamount),0) as PaidAmount,
'' > 90'' as Due , ''accb'' as type,
b.updatetime
from billsdebitdetails bd, bills b
left outer join vwaccBillsettlementpay pmt on
b.companyid = pmt.pdcompanyid and b.billsid = pmt.pdaccbillsid
left outer join vwaccbillvs vs on
b.companyid = vs.companyid and b.billsid = vs.billid
where b.companyid = bd.companyid and b.billsid = bd.billsid and
b.cancelled = 0 and b.cashpurchase = 0 and (getdate() - b.BillDate > 90)
group by b.CompanyID, b.DepartmentID, b.BillsID, b.VendorID, b.billsno, b.remarks,
b.referenceno, b.billdate, b.updatetime, b.dueperiod
union all
-- 4.credit note
SELECT dcn.DCNCompanyid, null as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno,
dcn.DCNDate, dcn.dcndate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.vsdate)
else null end settleddate,
DCNAmount, isnull(max(sd.amtsettled),0),
''0 - 30''  as Due, ''cn'' as type, dcn.updatetime
FROM debitcreditnote dcn
left outer join vwHQCNSettlementDetails SD on dcn.dcnCompanyID=SD.CompanyID and
dcn.dcniD =SD.dcnID
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0
and (getdate() - dcn.dcnDate between 0 and 30)
GROUP BY dcn.dcncompanyid,dcn.dcndepartmentid,  dcn.dcnid, dcn.dcnvendorid,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.dcndate, dcn.updatetime,
dcn.dcnamount
union all
SELECT dcn.DCNCompanyid, null as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno,
dcn.DCNDate, dcn.dcndate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.vsdate)
else null end settleddate,
DCNAmount, isnull(max(sd.amtsettled),0),
''31 - 60''  as Due, ''cn'' as type, dcn.updatetime
FROM debitcreditnote dcn
left outer join vwHQCNSettlementDetails SD on dcn.dcnCompanyID=SD.CompanyID and
dcn.dcniD =SD.dcnID
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0
and (getdate() - dcn.dcnDate between 31 and 60)
GROUP BY dcn.dcncompanyid,dcn.dcndepartmentid,  dcn.dcnid, dcn.dcnvendorid,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.dcndate, dcn.updatetime,
dcn.dcnamount
union all
SELECT dcn.DCNCompanyid, null as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno,
dcn.DCNDate, dcn.dcndate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.vsdate)
else null end settleddate,
DCNAmount, isnull(max(sd.amtsettled),0),
''61 - 90''  as Due, ''cn'' as type, dcn.updatetime
FROM debitcreditnote dcn
left outer join vwHQCNSettlementDetails SD on dcn.dcnCompanyID=SD.CompanyID and
dcn.dcniD =SD.dcnID
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0
and (getdate() - dcn.dcnDate between 61 and 90)
GROUP BY dcn.dcncompanyid,dcn.dcndepartmentid,  dcn.dcnid, dcn.dcnvendorid,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.dcndate, dcn.updatetime,
dcn.dcnamount
union all
SELECT dcn.DCNCompanyid, null as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno,
dcn.DCNDate, dcn.dcndate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.vsdate)
else null end settleddate,
DCNAmount, isnull(max(sd.amtsettled),0),
'' > 90''  as Due, ''cn'' as type, dcn.updatetime
FROM debitcreditnote dcn
left outer join vwHQCNSettlementDetails SD on dcn.dcnCompanyID=SD.CompanyID and
dcn.dcniD =SD.dcnID
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0
and (getdate() - dcn.dcnDate > 90)
GROUP BY dcn.dcncompanyid,dcn.dcndepartmentid,  dcn.dcnid, dcn.dcnvendorid,
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.dcndate, dcn.updatetime,
dcn.dcnamount
union all
-- receipt from supplier''s considered as bills
select rh.companyid, null shopid, rh.departmentid, rh.receiptid, rh.vendorid,
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate  , null settleddate,
rh.customeramount, 0.0 settledamt , ''0 - 30'' due,  ''rf'' type, rh.updatetime
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null
and (getdate() - rh.receiptdate between 0 and 30)
union all
select rh.companyid, null shopid, rh.departmentid, rh.receiptid, rh.vendorid,
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate , null settleddate,
rh.customeramount, 0.0 settledamt , ''31 - 60'' due,  ''rf'' type, rh.updatetime
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null
and (getdate() - rh.receiptdate between 31 and 60)
union all
select rh.companyid, null shopid, rh.departmentid, rh.receiptid, rh.vendorid,
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate , null settleddate,
rh.customeramount, 0.0 settledamt , ''61 - 90'' due,  ''rf'' type, rh.updatetime
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null
and (getdate() - rh.receiptdate between 61 and 90)
union all
select rh.companyid, null shopid, rh.departmentid, rh.receiptid, rh.vendorid,
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate , null settleddate,
rh.customeramount, 0.0 settledamt , '' > 90'' due,  ''rf'' type, rh.updatetime
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null
and (getdate() - rh.receiptdate > 90)
union all
-- to have some result always from this view
select 1, null shopid, null, null, vendorid, null, null, null, null, null , null settleddate,
0, 0.0 settledamt , '' > 90'' due,  ''dum'' type, null from avendormaster'
GO
/****** Object:  View [dbo].[vwShopPurchaseBillsPaid]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopPurchaseBillsPaid]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopPurchaseBillsPaid    Script Date: 18/01/2003 9:45:41 PM ******/
/****** Object:  View dbo.vwShopPurchaseBillsPaid    Script Date: 14/09/2002 12:48:12 AM ******/
/****** Object:  View dbo.vwShopPurchaseBillsPaid    Script Date: 31/07/2002 2:00:33 PM ******/
CREATE view [dbo].[vwShopPurchaseBillsPaid] as
select vwb.lphcompanyid, vwb.lphshopid as shopid, vwb.lphDepartmentid,
vwb.lphbillid, vwb.lphbillno, vwb.lphvendorbillno,
vwb.lphbilldate, vwb.lphduedate, vwb.lphvendorid, vwb.lphamount,
(isnull(vwpmt.paidamount,0) + isnull(vwvp.paidamount,0))  paidamount ,
"LB" Type from vwshoppurchaseBills vwb
left outer join vwshoppurchasePayments vwpmt
on vwb.lphcompanyid=vwpmt.phcompanyid and
vwb.lphbillid=vwpmt.pdposlpbillid
and vwb.lphshopid= vwpmt.pdshopid
left outer join vwLPBillVendrPayments vwvp on
vwb.lphcompanyid=vwvp.companyid and vwb.lphbillid=vwvp.lphbillid
and vwvp.shopid=vwb.lphshopid'
GO
/****** Object:  View [dbo].[vwshipmentwiseshopstock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwiseshopstock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentwiseshopstock    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 11/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwshipmentwiseshopstock]
as
select shopid, ss.itemid, ss.shipmentid, ss.stock, ss.openingstock,
ss.badstock, ss.openingbadstock, sh.shipcost ,a.itemcategoryid  from
vwshipmentcostprice sh, mosshopstock ss, aitem a where ss.itemid=sh.itemid
and ss.shipmentid=sh.shipmentid and a.itemid = ss.itemid
and (ss.stock <> 0  or ss.badstock <> 0 )'
GO
/****** Object:  View [dbo].[vwHQPurchaseBillsPaid]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQPurchaseBillsPaid]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 18/01/2003 9:45:41 PM ******/
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 31/07/2002 2:00:33 PM ******/
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 20/11/2001 9:59:10 AM ******/
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 17/11/2001 9:22:08 PM ******/
/****** Object:  View dbo.vwHQPurchaseBillsPaid    Script Date: 16/06/2001 15:36:35 ******/
CREATE view [dbo].[vwHQPurchaseBillsPaid] as
select vwb.pbhcompanyid, 0 as shopid, vwb.pbhbillid, vwb.pbhdepartmentid, vwb.pbhbillno, vwb.pbhvendorrefno, vwb.pbhbilldate,
vwb.pbhduedate, vwb.pbhvendorid, vwb.pbhamount, isnull(vwpmt.paidamount,0) +isnull(vwvp.paidamount,0) paidamount ,
"PB" Type from vwhqpurchaseBills vwb left outer join vwhqpurchasePayments vwpmt
on vwb.pbhcompanyid=vwpmt.phcompanyid and
vwb.pbhbillid=vwpmt.pdbillsid
left outer join vwHQPBillVendrPayments vwvp on
vwb.pbhcompanyid=vwvp.companyid and vwb.pbhbillid=vwvp.pbhbillid'
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemsold]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomeritemsold]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[spcustomeritemsold] @intshopid as int, @intcustomerid as int, @intitemid as int,
@strfromdate as varchar(8), @strtodate as varchar(8) as
begin
	if @strfromdate =''''
	select ihinvoicedate, ihinvoiceno, sp.spername, quantity, amount, customs from
	vwCustomerSalesByitem vw left outer join asalespersonmaster sp on vw.ihsalespersonid =
	sp.sperid  where vw.ihshopid = @intshopid and vw.iditemid = @intitemid
	and vw.ihinvoicedate <= @strtodate and ihcustomerid=@intcustomerid
	else
	select ihinvoicedate, ihinvoiceno, sp.spername, quantity, amount, customs from
	vwCustomerSalesByitem vw left outer join asalespersonmaster sp on vw.ihsalespersonid
	= sp.sperid where vw.ihshopid = @intshopid and vw.iditemid = @intitemid
	and vw.ihinvoicedate >= @strfromdate and vw.ihinvoicedate <= @strtodate
	and ihcustomerid=@intcustomerid
end' 
END
GO
/****** Object:  View [dbo].[vwavgmonthlysale]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwavgmonthlysale]'))
EXEC dbo.sp_executesql @statement = N'
--------------DB 5--------------------------------------------------------------------------------------------------
---Created By  : prasanth joseph
Create view [dbo].[vwavgmonthlysale] as
select avg(qty) avgqty,itemid,syear from
(select sum(qty) qty,itemid,syear,smonth from vwItemDetailedSalesForecastment --where itemid=11222 --and syear=''2007''
group by smonth,itemid ,syear)A group by itemid ,syear'
GO
/****** Object:  StoredProcedure [dbo].[spRemineVendordueDate]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spRemineVendordueDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------
--Created by : VinothMurugan V.
--Date   : 02/10/2010
--Purpose    : For remine the vendor bills
-----------------------------------------------------------------------
--exec spRemineVendordueDate ''20100726''
CREATE procedure [dbo].[spRemineVendordueDate](@packageDate as varchar(100))
as
begin
set @packageDate = convert(datetime,@packageDate,120)
--declare @packageDate as datetime
--set @packageDate = ''20100720''
select max(a.billamount) billamount, sum(a.paidamount) paidamount , a.vendorID ,
a.shopid,a.departmentid,a.billsid,a.type, a.billsno,a.billdate,
a.remarks,a.referenceno,a.currencyname,a.vendorname,a.symbol,
creditoraccid,b.AccountDesc,a.duedate ,a.ReminderDate from
(
SELECT vwbills.companyid, vwbills.shopid, vwbills.departmentid,vwbills.billsid,vwbills.vendorID,
vwbills.billsno,vwbills.remarks, vwbills.referenceno,vwbills.billdate, vwbills.duedate,
vwbills.billamount,vwbills.type,
isnull(vwpayments.PaidAmount,0) paidamount,aVendorMaster.VendorName,
aCurrencyMaster.CurrencyName, aCurrencyMaster.Symbol,creditoraccid,
dateadd(day,-vwbills.RecurrenceDuePeriod,vwbills.duedate) ReminderDate
FROM
(
(
(
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)duedate, sum(bd.amount)
billamount, ''accb'' as type, b.RecurrenceDuePeriod
from billsdebitdetails bd, bills b
where b.companyid = bd.companyid and b.billsid = bd.billsid and
b.cancelled = 0 and b.cashpurchase = 0 and b.autogenerate = 1
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,
b.remarks, b.ReferenceNo, b.billdate, b.dueperiod, b.DepartmentID,b.RecurrenceDuePeriod
) vwbills
INNER JOIN aVendorMaster ON vwbills.vendorID = aVendorMaster.VendorID
)
LEFT OUTER JOIN  vwpayments ON  vwbills.companyid = vwpayments.companyid
AND vwbills.billsid = vwpayments.billsid AND vwbills.vendorID = vwpayments.vendorid
AND vwbills.shopid = vwpayments.shopid and vwbills.type = vwpayments.type
)
INNER JOIN aCurrencyMaster aCurrencyMaster ON aVendorMaster.CurrencyID = aCurrencyMaster.CurrencyID AND
aVendorMaster.CompanyID = aCurrencyMaster.CompanyID
)
a ,aAccountMaster b
--where a.CreditorAccID = b.AccountID and a.billdate<=@packageDate and bills.autogenerate = 1
where a.CreditorAccID = b.AccountID and a.ReminderDate<=@packageDate
group by a.vendorID , a.shopid,a.departmentid,a.billsid,a.type,a.billsno,a.billdate,
a.remarks,a.referenceno,a.currencyname,a.vendorname,a.symbol ,creditoraccid,b.AccountDesc,a.duedate,a.ReminderDate--,bills.RecurrenceDuePeriod
having max(a.billamount) <> sum(a.paidamount)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownStock]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateGodownStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified By	: Venkitesh
--Modified Date	: 17/09/2003
--COmments	: Given insertion query to moigodownstock if the item have no entry in stock
--Verified by 	    : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
CREATE proc [dbo].[SpUpdateGodownStock](@despatchid int,
@Godownid int,@process char(1)) as
declare
@cur_despatchid int,
@cur_godownid int,
@cur_itemid int,
@cur_itembadqty numeric(18,3),
@cur_itemgoodqty numeric(18,3),
@intcount int
set nocount on
set @intcount=0
declare cursor_Detail  cursor for
	select dddespatchid, ddgodownid, dditemid, dditembadqty,
	dditemgoodqty from MeiDespatchtoshopdetail
	where dddespatchid = @despatchid and ddgodownid = @Godownid
open cursor_Detail
fetch next from cursor_Detail into
@cur_despatchid, @cur_godownid, @cur_itemid,
@cur_itembadqty, @cur_itemgoodqty
while @@fetch_status = 0
begin
	--added by venki forinserting empty row if itemcount=0
			select @intCount = count(*) from moigodownStock
			where gsitemid = @cur_Itemid and gsgodownid= @godownid
			if @intCount =0
			Begin
				insert moigodownStock (gsgodownID,gsStockDate, gsShipmentID, gsItemID,
				gsOpeningStock, gsStock, gsOpeningBadStock, gsBadStock)
				Select @godownid, getdate(), 1, @cur_itemid, 0, 0, 0, 0
			End
			--
	if @process = ''R''
		update moigodownstock set gsstock = gsstock + @cur_itemgoodqty
		where gsitemid = @cur_itemid
		and gsgodownid = @cur_godownid
	if @process = ''F''
	begin
		update moigodownstock set gsstock = gsstock - @cur_itemgoodqty		
		where gsitemid = @cur_itemid and gsgodownid = @cur_godownid
	end
	fetch next from cursor_Detail into
	@cur_despatchid, @cur_godownid, @cur_itemid,
	@cur_itembadqty, @cur_itemgoodqty
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlShopRecover]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopRecover]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified on      : 13/01/2003
-- Modified by      : Hariharan R
-- Comment          : Added code to insert dep amount and to convert amount
-- verified by hariharan
--------------------------------------
-- Modified on      : 10/06/2003
-- Modified by      : Kishore
-- Comments         : recovery transaction sp modified to take the stock transfer account  (On comparison with v2)
--------------------------------------
-- Modified on      : 19/07/2003
-- Modified by      : R Harikrishnan
-- Comments         : The stock transfer account ID posting corrected.
--------------------------------------
-- Ref No			: 1
-- Modified on      : 15/02/2011
-- Modified by      : MANUNADH.U
-- Comments         : Correct the Posting of those recovery in which the corresponding Arrival is HQ Arrival.
--					: If so, post into stockwriteoffAccId instead of stocktransfercontrolacc
--------------------------------------
CREATE PROCEDURE [dbo].[spUlShopRecover] @intCompanyId as int, @intShopId as int as
begin
Declare @intJournalId as int,@intJournalDetailId as int,@intsrId as int,@intFinancialId as int,
	@strsrNo as varchar(50),@dtsrDate as datetime,@strRemarks as varchar(500),@intDepartmentId as int,
	@numSrAmt as numeric(18,2),@intCompanyCurId as int,@intInventoryAccId as int,@intswoAccId as int,
	@intrecoveryAccId 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),@intStockTransferAccId as int
	,@strTransNo as varchar(50),@intTransCount as int--<<Ref No:1>>
set @numDepExRate = 0.0
set @numConExRate = 0.0
set @intCurrencyId = 0
set @strExRates = ''''
set @numAccExRate = 0.0
set @numTransEr = 0.0
set @numAaccAmt = 0.0
set @strTransNo = ''''
--get the companyCurrencyId
SELECT @intCompanyCurId = CurrencyId FROM acompanymaster WHERE CompanyId = @intCompanyId
select @intswoAccId = stockwriteoffAccId from ashops where ShopId = @intShopId
select @intInventoryAccId = InventoryId, @intrecoveryAccId = futureint,
	@strzerorate = substring(isnull(futurevc,''''),1,1),@intStockTransferAccId = stocktransfercontrolacc
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 srcur cursor for
	SELECT srId, rtrim(s.shopname) + ''_'' + rtrim(convert(varchar(50),srId)),srdate, ''system'', updatetime,
	  srDepartmentId,srConExRate, srDepExRate, srExchangeRates,srtransno --<<Ref No:1>>
	FROM losStockRecovery r, ashops s
	WHERE s.ShopId = r.srShopId and srShopId = @intShopId and srposted =0
open srcur
	fetch next FROM  srcur into @intsrId, @strsrno, @dtsrDate, @strRemarks, @dtutime,@intDepartmentId, @numConExRate,
		@numDepExRate,@strExRates,@strTransNo  --<<Ref No:1>>
	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 @dtsrDate 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 losstockrecovery, aitem
	  where srId = @intsrId and srShopId = @intShopId and srItemId = itemId
		and ( srcostprice = null or srcostprice =0) and (itemrate=0 or itemrate is null)
	
	  --<<Ref No:1>> Check whether arrive from HQ or not
	  set @intTransCount=0
	  select @intTransCount = count(*) from LOsgoodsarrivaltoshopheader
	  where gahGodownDespatchID is null and gahDespatchedGodownID is null and gahhqdespatchid is not null
		and gahCancelled=0 and gahArrivalNo=@strTransNo
	  --<<Ref No:1>>
	  -- to allow to proceed if allow zero rate condition given - hari 020905
	  if @strzerorate = ''z''
		begin
			set @intfailcount=0
		end
	  if @intfailcount = 0
		begin -- to update the item rate to the gadcostprice
		  update  losstockrecovery set srcostprice = itemrate from aitem
		  where ( srcostprice =null or srcostprice =0) and srId = @intsrId
			and srShopId = @intShopId and srItemId = itemId
		  --getting the total amount with qty and item cost price
		  select @numSrAmt = isnull(sum((sraddStock - srdedstock)* srcostprice),0)
		  from losStockRecovery where srShopId = @intShopId and srId = @intsrId
		  if (@numSrAmt <> 0)
			begin
			  insert into moaJournalHeader (JournalId, CompanyId, JournalDate,
				referenceno, remarks, financialId, Type, CurrencyId,chequedate, updatetime )
			  values (@intJournalId, @intCompanyId, @dtsrDate, @strsrno,
				@strRemarks, @intFinancialId, ''posrec'', @intcompanycurId, @dtsrDate, @dtutime )
			
			  set @intJournalDetailId = 1
			  if (@numSrAmt > 0)
				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,
					abs(@numSrAmt) * @numConExRate,abs(@numSrAmt),abs(@numSrAmt) * @numDepExRate,@intdepartmentId)
				  set @intJournalDetailId = @intJournalDetailId + 1
				  -- for converting the amount --->
				  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intStockTransferAccId
				  exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output
				  exec spConvertCurrency @numTransEr, @numAccExRate,@numSrAmt,@numAaccAmt output
				  --<<Ref No:1>>
				  ---- credit the stock writeoff acc Id
				  --if @intTransCount=0
					 -- insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEdit, AccountId, Amount,
						--actualamount,DepAmount, departmentId)
					 -- values(@intJournalId, @intjournalDetailId,@intCompanyId, 1,@intStockTransferAccId,
						--abs(@numSrAmt) * @numConExRate,abs(@numAaccAmt),abs(@numSrAmt) * @numDepExRate, @intDepartmentId )
				  if @intTransCount=0
					 insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEdit, AccountId, Amount,
						actualamount,DepAmount, departmentId)
					 values(@intJournalId, @intjournalDetailId,@intCompanyId, 1,@intStockTransferAccId,
						abs(@numSrAmt) * @numConExRate,abs(@numAaccAmt),abs(@numSrAmt) * @numDepExRate, @intDepartmentId )
				  else
					 insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEdit, AccountId, Amount,
						actualamount,DepAmount, departmentId)
					 values(@intJournalId, @intjournalDetailId,@intCompanyId, 1,@intswoAccId,
						abs(@numSrAmt) * @numConExRate,abs(@numAaccAmt),abs(@numSrAmt) * @numDepExRate, @intDepartmentId )
				  --<<Ref No:1>>
				end -- end for more addtion
			  if (@numSrAmt < 0)
				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,
					abs(@numSrAmt) * @numConExRate, abs(@numSrAmt),abs(@numSrAmt) * @numDepExRate,@intdepartmentId)
				  set @intJournalDetailId = @intJournalDetailId + 1
				  -- for converting the amount --->
				  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intStockTransferAccId
				  exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output
				  set @numSrAmt = abs(@numSrAmt)
				  exec spConvertCurrency @numTransEr, @numAccExRate,@numSrAmt,@numAaccAmt output
				
				  -- credit the stock writeoff acc Id
				  --<<Ref No:1>>
				  -- insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEDit,accountId,Amount,
					--actualamount, DepAmount, departmentId)
				  -- values (@intJournalId, @intjournalDetailId,@intCompanyId, 0,@intStockTransferAccId,
				  --   abs(@numSrAmt) * @numConExRate,@numaAccAmt,abs(@numSrAmt) * @numDepExRate,@intdepartmentId )
				  if @intTransCount=0
					  insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEDit,accountId,Amount,
						actualamount, DepAmount, departmentId)
					  values (@intJournalId, @intjournalDetailId,@intCompanyId, 0,@intStockTransferAccId,
						abs(@numSrAmt) * @numConExRate,@numaAccAmt,abs(@numSrAmt) * @numDepExRate,@intdepartmentId )
				  else
					 insert into moaJournalDetails (JournalId,journaldetailId, CompanyId,JournalCrEDit,accountId,Amount,
						actualamount, DepAmount, departmentId)
					  values (@intJournalId, @intjournalDetailId,@intCompanyId, 0,@intswoAccId,
						abs(@numSrAmt) * @numConExRate,@numaAccAmt,abs(@numSrAmt) * @numDepExRate,@intdepartmentId )
				  --<<Ref No:1>>
				end -- end for more addtion
			  end
			update losStockRecovery set srposted = 1 WHERE srId = @intsrId and srShopId = @intShopId
			set @intJournalId = @intJournalId + 1
		  end -- for item rate =0 check
		fetch next FROM  srcur into @intsrId, @strsrno, @dtsrDate, @strRemarks,@dtutime, @intDepartmentId,
			@numConExRate, @numDepExRate, @strExRates ,@strTransNo  --<<Ref No:1>>
	  end -- CUR END
	Close srcur
	Deallocate srcur
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUnsettledAccBills]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUnsettledAccBills]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--created on 	: 05/05/03
--created by 	: leo
CREATE proc [dbo].[spUnsettledAccBills] @intcompanyid as int, @intdepartmentid as int,
@intvendorid as int, @strcurdate as varchar(8) as
begin
declare @intdueperiod as int
select @intdueperiod = alertbeforedays from asettings where companyid = @intcompanyid
if @intvendorid =0
select b.billsno [Bill No], b.pbhbilldate [Bill Date], b.duedate [Due Date], max(ven.vendorname)
[Vendor Name], convert(decimal,pbhbillamount) [Bill Amount], max(c.symbol ) [Symbol]
from avendormaster ven, acurrencymaster c, vwbills b left outer join vwHQAccBillPaidDetails p on b.billsid = p.billsid
left outer join vwaccbillvs v on b.companyid = v.companyid and b.billsid = v.billid
where ven.vendorid =b.pbhvendorid and ven.currencyid = c.currencyid and  b.type =''accb'' and
b.departmentid = @intdepartmentid and b.companyid = @intcompanyid
and (datediff(d, @strcurdate, b.duedate) between 0 and @intdueperiod)
group by b.companyid, b.billsid, b.billsno, b.pbhbilldate, b.duedate, b.pbhvendorid, pbhbillamount
having (pbhbillamount > sum(isnull(p.pdpaidamount,0.0)) + sum(isnull(v.paidamount,0.0)))
else
select b.billsno [Bill No], b.pbhbilldate [Bill Date], b.duedate [Due Date], max(ven.vendorname)
[Vendor Name], convert(decimal,pbhbillamount) [Bill Amount], max(c.symbol ) [Symbol]
from avendormaster ven, acurrencymaster c, vwbills b left outer join vwHQAccBillPaidDetails p on b.billsid = p.billsid
left outer join vwaccbillvs v on b.companyid = v.companyid and b.billsid = v.billid
where ven.vendorid =b.pbhvendorid and ven.currencyid = c.currencyid and  b.type =''accb''
and b.departmentid = @intdepartmentid and b.companyid = @intcompanyid and b.pbhvendorid = @intvendorid
and (datediff(d, @strcurdate, b.duedate) between 0 and @intdueperiod)
group by b.companyid, b.billsid, b.billsno, b.pbhbilldate, b.duedate, b.pbhvendorid, pbhbillamount
having (pbhbillamount > sum(isnull(p.pdpaidamount,0.0)) + sum(isnull(v.paidamount,0.0)))
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUlInvDespToShop]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlInvDespToShop]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
/****** Object:  Stored Procedure dbo.spULInvdesptoshop    Script Date: 18/01/2003 9:45:48 PM ******/
-- created on  : 17/07/2002
-- created by   : leo
----------------------------------
-- Modified on  : 02/01/2003
-- Modified by  : Kishore
-- Commentd     : Inserted DepAmount and added amount convertion
----------------------------------
--RefNo-1
-- Modified on  : 09/12/2009
-- Modified by  : Yogesh
-- Commentd     : To prevent posting of non-confirmed transactions
----------------------------------
CREATE proc [dbo].[spUlInvDespToShop] @intCompanyID as int, @intGodownId as int as
begin
Declare
@intJournalId as int,
@intJournalDetailId as int,
@intsdid as int,
@intFinancialID as int,
@strsdNo as varchar(50),
@dtsdDate as datetime,
@strRemarks as varchar(500),
@intDepartmentId as int,
@numSdAmt as numeric(18,2),
@intCompanyCurID as int,
@intInventoryAccId as int,
@intStockTransferAccId 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)
--get the companyCurrencyID
SELECT @intCompanyCurId = CurrencyId
FROM aCompanyMaster
WHERE CompanyId = @intCompanyId
select @intInventoryAccId = InventoryID,
@intStockTransferAccId = stocktransfercontrolacc,
@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 sdcur cursor for
SELECT dhDespatchId, dhdespatchno, dhdespatchdate, dhRemarks,
updatetime,dhDepartmentId, dhConExRate, dhDepExRate, dhExchangeRates
FROM meiDespatchToShopHeader
WHERE dhCancelled = 0
and dhGodownId = @intGodownId and dhPosted =0
and dhTransFinished=1--To post only confirmed transactions(RefNo-1)
open sdcur
fetch next FROM  sdcur into @intsdid, @strsdno, @dtsdDate,
@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 @dtsdDate 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 meiDespatchToShopDetail , aItem where
ddDespatchId = @intsdid and ddGodownId = @intGodownId and ddItemId = ItemId
and (ddCostedPrice=null or ddcostedprice=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 check hari 011213
begin
-- to update the item rate to the gadcostprice
update meiDespatchToShopDetail set ddCostedPrice = itemrate
from aItem where ( ddCostedPrice = null or ddCostedPrice = 0)
and ddDespatchId = @intsdid
and ddGodownId = @intGodownId and ddItemId = ItemId
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,
referenceno, remarks, financialID, Type, CurrencyID,chequedate,updatetime)
values (@intJournalID, @intCompanyID, @dtsdDate, @strsdno,
@strRemarks, @intFinancialID, ''invdts'', @intcompanycurID, @dtsdDate, @dtutime  )
set @intJournalDetailID = 1
-- getting the total amount with qty and item cost price
select @numSdAmt = isnull(sum(ddItemGoodQty * ddCostedPrice),0)
from meiDespatchToShopDetail
where ddGodownId = @intGodownId
and ddDespatchId = @intsdid
-- for converting the amount --->
select @intCurrencyId = CurrencyId
from aAccountMaster
where AccountId = @intStockTransferAccId
exec spReturnExRate @intCurrencyId, @strExRates,
@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,
@numSdAmt,
@numAaccAmt output
-- debiting hte stock writeoff accid
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountId, Amount, ActualAmount,
DepAmount, DepartmentId)
values (@intJournalID, @intjournalDetailID,
@intCompanyID, 0, @intStockTransferAccId,
@numSdAmt * @numConExRate, @numAaccAmt,
@numSdAmt * @numDepExRate,
@intDepartmentId )
set @intJournalDetailID = @intJournalDetailID +1
-- credit the inventory acc id
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,
JournalCrEDit, AccountId, Amount, ActualAmount,
DepAmount, DepartmentId)
values
(@intJournalID, @intjournalDetailID, @intCompanyID, 1,
@intInventoryAccId, @numSdAmt * @numConExRate, @numSdAmt,
@numSdAmt * @numDepExRate, @intDepartmentId)
update meiDespatchToShopHeader set dhPosted = 1
WHERE dhDespatchId = @intsdID and
dhGodownId = @intGodownId
set @intJournalID = @intJournalID + 1
end -- for item rate check hari 011213
fetch next FROM  sdcur into @intsdiD, @strsdno, @dtsdDate, @strRemarks,
@dtutime, @intDepartmentId, @numConExRate,
@numDepExRate, @strExRates
end -- CUR END
Close sdcur
Deallocate sdcur
end' 
END
GO
/****** Object:  View [dbo].[vwApartmentBillSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwApartmentBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- Created on 	        : 23/01/2004
-- Created by		: Hariharan
-- Comments		: For getting latest settlement details of Apartment Bills in Manam
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwApartmentBillSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.RoomBillID
invoiceid, cd.shopid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.RoomBillID  is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.RoomBillID  invoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.RoomBillID is not null) settledaccinvoices
group by companyid, customerid, shopid,  invoiceid'
GO
/****** Object:  View [dbo].[vwariivaltoshoppendinglist]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwariivaltoshoppendinglist]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwariivaltoshoppendinglist] as
select  dh.dhDespatchId as ''despid'',dh.dhDespatchNo as ''despno'',dh.dhDespatchDate  as ''despdate'',''Godown'' as ''From1'',
cast(datediff(n,left (dh.dhDespatchDate,12)+right(dh.dhDespatchTime,7),getdate())/60 as varchar(20))+ '' Hrs:''+cast(datediff(n,left (dh.dhDespatchDate,12)+right(dh.dhDespatchTime,7),getdate())-60*(datediff(n,left (dh.dhDespatchDate,12)+right(dh.dhDespatchTime,7),getdate())/60) as varchar(20)) + ''Mts''  as ''ElapsedTime'',
case dh.dhTransFinished when 0 then ''No'' else ''Yes''end as Conformed,dh.dhgodownid as ''Id''
from meiDespatchToShopHeader dh where dh.dhshopid= 6 and dh.dhgodownid=1 and dh.dhselected = 0 and
dh.dhcancelled=0 and dh.dhtransfinished=1 and
dh.dhnoofdetails=(select count(*) from meidespatchtoshopdetail dd where dd.dddespatchid=dh.dhdespatchid and dd.ddgodownid = dh.dhgodownid )
union
select dhDespatchNoteID as ''despid'',dhDespatchNoteNo as ''despno'',dnm.dnmDespatchNoteDate as ''despdate'',''Hq'' as ''From1'',
cast(datediff(n,left (dnm.dnmDespatchNoteDate,12)+right(dntime,7),getdate())/60 as varchar(20))+ '' Hrs:''+cast(datediff(n,left (dnm.dnmDespatchNoteDate,12)+right(dntime,7),getdate())-60*(datediff(n,left (dnm.dnmDespatchNoteDate,12)+right(dntime,7),getdate())/60) as varchar(20)) + ''Mts''  as ''ElapsedTime'',
case dhTransfinished when 0 then ''No'' else ''Yes''end as Conformed,0 as ''Id''
from aHQDespatchNoteHeader dnh,aHQDespatchNoteMain dnm
where dhShopID=6 and dhcancelled =0 and dhSelected=0 and  dnm.dnmDespatchNoteID=dnh.dhDespatchNoteMainID
and dhNoofDetails=(Select count(*) from ahqDespatchNoteDetails dd where dd.dddespatchnoteid=dnh.DhDespatchNoteid)'
GO
/****** Object:  View [dbo].[vwadvancepaidCreditsAmounts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidCreditsAmounts]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwadvancepaidCreditsAmounts    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments		: v3
CREATE view [dbo].[vwadvancepaidCreditsAmounts] as
select DCNCompanyID, DCNID, DCNCustomerId, sum(advanceamt) rptamt,
sum(settlementamt) settledamt from
(select rh.DCNCompanyID, rh.DCNID, rh.DCNCustomerId, DCNAmount advanceamt,
0.0 as settlementamt from debitcreditnote rh, vwadvancepaidCredits vw
where rh.DCNCompanyID = vw.DCNcompanyid and rh.DCNID = vw.DCNID and
rh.DCNcancelled = 0 and rh.DCNDebit = 0
union all
select ch.companyid, ch.dcnid, ch.customerid,0.0 advanceamt,
sum(cd.SettlementAmount) settlementamt from
customersettlementheader ch, customersettlementdetail cd, vwadvancepaidCredits vw
where vw.DCNcompanyid = ch.companyid and vw.DCNID = ch.dcnid and
ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled =0
group by ch.companyid, ch.dcnid, ch.customerid) temp1
group by DCNcompanyid, DCNID, DCNcustomerid'
GO
/****** Object:  View [dbo].[vwaccountinvsettledamount]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwaccountinvsettledamount]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwaccountinvsettledamount    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwaccountinvsettledamount    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwaccountinvsettledamount    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwaccountinvsettledamount    Script Date: 20/11/2001 9:59:07 AM ******/
/****** Object:  View dbo.vwaccountinvsettledamount    Script Date: 17/11/2001 9:21:56 PM ******/
CREATE view [dbo].[vwaccountinvsettledamount] as
select companyid, accid, sum(settledamt) settledamt from
(select rh.companyid, rd.hqaccountsinvoiceid accid, sum(rd.amountreceived) settledamt from
receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
hqaccountsinvoiceid is not null
group by rh.companyid, rd.hqaccountsinvoiceid
union all
select csh.companyid, csd.accinvoiceid accid, sum(settlementamount) settledamt from
customersettlementheader csh, customersettlementdetail csd where csh.companyid = csd.companyid
and csh.csid = csd.csid and csd.accinvoiceid is not null and cancelled = 0
group by csh.companyid, csd.accinvoiceid) one
group by companyid, accid'
GO
/****** Object:  View [dbo].[vwAccInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAccInvoiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified by    : Kishore
-- Modified on    : 26/11/2003
-- Comments       : Added SettledAmt column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwAccInvoiceSettlementNo] AS
select companyid, customerid, max(setdate) setdate, max(refno) refno,
accinvoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate,
ch.csno refno, cd.accinvoiceid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.accinvoiceid is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate,
rh.receiptno refno, rd.hqaccountsinvoiceid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.hqaccountsinvoiceid is not null) settledaccinvoices
group by companyid, customerid, accinvoiceid'
GO
/****** Object:  View [dbo].[vw_Report_service_SupplierLedger]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_service_SupplierLedger]'))
EXEC dbo.sp_executesql @statement = N'
----
-- 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 [dbo].[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
/****** Object:  View [dbo].[vwUtitilityBillSettlementNo]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUtitilityBillSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
-- Created on 	        : 23/01/2004
-- Created by		: Hariharan
-- Comments		: For getting latest settlement details of Utility Bills in Manam
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwUtitilityBillSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.UtilityBillID
invoiceid, cd.shopid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.UtilityBillID is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.UtilityBillID invoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.UtilityBillID is not null) settledaccinvoices
group by companyid, customerid, shopid,  invoiceid'
GO
/****** Object:  View [dbo].[vwspecialreturninvoicetosettle]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialreturninvoicetosettle]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 09/12/02
--Modified by  : leo
--Comments  : v3
--modified on :14-08-09
--modified by :Nidheesh
--comments : added (ihNoofOCDetails<>0 or) to to include RBD
--added (ihNoofOCDetails=0 and) to avoid RBD
----------------------------------------------------------------
-- Modified By : Benzigar S D
-- Modified On : 17/11/2009
-- Comment     : Changed sum(isnull(SettlementAmount,0)) settledamt to isnull(SettlementAmount,0) settledamt
--             : Because sum is already taken
CREATE  view   [dbo].[vwspecialreturninvoicetosettle] as
select ihcompanyid, ihinvoiceid,ihshopid,ihcustomerid, ihinvoiceno, ihinvoicedate,
min(d.idquantity) as returnedinvid,
abs(sum(isnull(d1.idunitprice,0))-sum(isnull(d.idunitprice,0))) returnamount,
isnull(SettlementAmount,0) settledamt, ihexchangerate, ihdepexrate
from losspecialinvoiceheader h left outer join losspecialinvoicedetail d on
h.ihinvoiceid = d.idinvoiceid and h.ihshopid = d.idshopid and (ihNoofOCDetails<>0 or d.idratetype=1)
left outer join losspecialinvoicedetail d1 on
h.ihinvoiceid = d1.idinvoiceid and h.ihshopid = d1.idshopid and ihNoofOCDetails=0 and d1.idratetype=0
left outer join (select h.shopid, h.losdcnid,
sum(isnull(SettlementAmount,0)) SettlementAmount from customersettlementheader h,
customersettlementdetail d where h.CSID=d.CSID and h.cancelled=0  group by h.shopid, h.losdcnid)
csh on ihshopid = csh.shopid  and ihinvoiceid = csh.losdcnid
where ihcancelled=0 and ihcashinvoice =0 and ihtransfinished=1
group by ihcompanyid,ihinvoiceid, ihshopid,ihcustomerid, ihinvoiceno, ihinvoicedate,
ihexchangerate, ihdepexrate,SettlementAmount
having sum(isnull(d.idunitprice,0))-sum(isnull(d1.idunitprice,0)) >0'
GO
/****** Object:  View [dbo].[vwadvancepaidreceiptsamounts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidreceiptsamounts]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 31/03/2003, 13/03/2004
--Modified by 		: R Harikrishnan, Hariharan
--Comments		: v3
--			: Added multi Customer Option
CREATE View [dbo].[vwadvancepaidreceiptsamounts]
as
select
	companyid, receiptid, customerid, sum(advanceamt) rptamt, sum(settlementamt) settledamt
from
	(
		select
			rh.receiptid, rh.companyid,rh.customerid, customeramount advanceamt,
			0.0 as settlementamt
		from
			receiptvoucherheader rh, vwadvancepaidreceipts vw
		where
			rh.companyid = vw.companyid and rh.receiptid = vw.receiptid and
			rh.cancelled = 0 and rh.customerid is not null
		union all
		
		select
			rh.receiptid, rh.companyid,rd.customerid, sum(rd.CustomerAmount) advanceamt,
			0.0 as settlementamt
		from
			receiptvoucherheader rh, vwadvancepaidreceipts vw,
			ReceiptVoucherCustomerDetails rd
		where
			rh.companyid = vw.companyid and rh.receiptid = vw.receiptid and
			rd.customerid=vw.customerid and
			rh.companyid = rd.companyid and rh.receiptid = rd.receiptid and
			rh.cancelled = 0 and rh.receiptcustomerid is not null
			
		group by
			rh.receiptid, rh.companyid,rd.customerid
		union all
		select
			ch.receiptid, ch.companyid, ch.customerid,0.0 advanceamt,
			sum(cd.SettlementAmount) settlementamt
		from
			customersettlementheader ch, customersettlementdetail cd,
			vwadvancepaidreceipts vw
		where
			vw.companyid = ch.companyid and vw.receiptid = ch.receiptid and
			ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled =0
			and ch.CustomerId = vw.CustomerId
		group by
			ch.receiptid, ch.companyid, ch.customerid
	) temp1
group by
	companyid, receiptid, customerid'
GO
/****** Object:  View [dbo].[vwadvancepaidpaymentsamounts]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidpaymentsamounts]'))
EXEC dbo.sp_executesql @statement = N'
-- View
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--
/****** Object:  View dbo.vwadvancepaidpaymentsamounts    Script Date: 17/11/2001 9:21:57 PM ******/
--verified by leo
--modified by venki 020903 (added multiple vendors also )
---------------------------------------------------------------------
--Modified By : VinothMurugan V.
--Date		  : 14/10/2010
--purpose	  : Adding Confirm bit.
--RefNo-01
---------------------------------------------------------------------
CREATE    view [dbo].[vwadvancepaidpaymentsamounts] as
select phcompanyid companyid, phpaymentid paymentid, phvendorid vendorid,
sum(advanceamt) Pmtamt, sum(settlementamt) settledamt from
(select ph.phpaymentid, ph.phcompanyid, vw.vendorid phvendorid, vw.amount advanceamt,
0.0 as settlementamt from ahqpaymentvoucherheader ph, vwadvancepaidpayments vw
where ph.phcompanyid = vw.companyid and ph.phpaymentid = vw.paymentid and ph.phcancelled = 0
and vw.vendorid is not null  and ph.phConfirmed = 1 --RefNo-01
union all
select vh.paymentid, vh.companyid, vh.vendorid,0.0 advanceamt, sum(vd.SettlementAmount) settlementamt from
vendorsettlementheader vh, vendorsettlementdetail vd, vwadvancepaidpayments vw
where vw.companyid = vh.companyid and vw.paymentid = vh.paymentid and
vh.companyid = vd.companyid and vh.vsid = vd.vsid and vh.cancelled =0
group by vh.companyid, vh.paymentid,  vh.vendorid ) temp1
group by phcompanyid, phpaymentid, phvendorid'
GO
/****** Object:  View [dbo].[vwhqdrcrinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqdrcrinvandrecamount]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwhqdrcrinvandrecamount] as
select dcncompanyid, 0 shopid, dcnid, dcndepartmentid,refno,  dcnno,
dcndate, dcndate duedate, dcnCustomerID, dcnamount,
isnull(rsetamt,0) + isnull(csetamt,0) settled, ''HDEBIT'' Type from debitcreditnote dcn
left outer join  (select rd.dcnid rdcnid, sum(rd.AmountReceived) rsetamt ,rh.ReferenceNo refno from
receiptvoucherdetails rd, receiptvoucherheader rh where rh.companyid = rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled =0 and rd.dcnid is not null group by rd.dcnid,rh.ReferenceNo) rsettled
on dcn.dcnid = rdcnid
left outer join
(select  csd.dcnid cdcnid, sum(csd.SettlementAmount) csetamt from
customersettlementdetail csd, customersettlementheader csh where csd.companyid = csh.companyid
and csd.csid = csh.csid and csh.cancelled =0 and csd.dcnid is not null group by csd.dcnid ) csettled on
dcn.dcnid = cdcnid where dcnCancelled =0 and dcncustomerid is not null and dcndebit =1 group by
dcncompanyid, dcnid, dcndepartmentid,  dcnno, dcndate, dcnCustomerID, dcnamount, rsetamt, csetamt,refno'
GO
/****** Object:  View [dbo].[vwHQDNSettlementDetails]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQDNSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwHQDNSettlementDetails    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwHQDNSettlementDetails    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwHQDNSettlementDetails    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwHQDNSettlementDetails    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwHQDNSettlementDetails    Script Date: 17/11/2001 9:22:00 PM ******/
-- last modified : 28/10/2001
-- modified by   : leo
CREATE view [dbo].[vwHQDNSettlementDetails] as
SELECT csd.CompanyID, csd.dcnid , max(csh.csdate) csdate,
null departmentid, sum(isnull(csd.settlementamount,0)) as Amtsettled
FROM customersettlementdetail csd
left outer join customersettlementHeader csh
on csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID
WHERE csh.Cancelled = 0 and csh.customerid is not null and csd.dcnid is not null
GROUP BY csd.CompanyID, csd.dcnid'
GO
/****** Object:  View [dbo].[vwHQAccPaidBills]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQAccPaidBills]'))
EXEC dbo.sp_executesql @statement = N'
-- View
/****** Object:  View dbo.vwHQAccPaidBills    Script Date: 18/01/2003 9:45:41 PM ******/
--Modified By  : VinothMurugan V.
--Date     : 13/10/2010
--Purpose    : Adding inter divisional bills
CREATE view [dbo].[vwHQAccPaidBills] as
select vwb.companyid, null as shopid, vwb.billsid, vwb.billsno, vwb.referenceno, vwb.billdate,
vwb.duedate, vwb.departmentid, vwb.vendorid, vwb.billamount,
(isnull(vwpmt.paidamount,0) + isnull(vwvp.paidamount,0)) paidamount ,
--"AB" Type
vwb.type
from vwHQAccBills vwb left outer join vwHQAccPayments vwpmt
on vwb.companyid=vwpmt.phcompanyid and
vwb.billsid=vwpmt.pdaccbillsid
left outer join vwAccVendrPayments vwvp on vwb.companyid=vwvp.companyid
and vwb.billsid=vwvp.billid  --and  vwb.type =''AB''
union all
select vwb.companyid, null as shopid, vwb.billsid, vwb.billsno, vwb.referenceno, vwb.billdate,
vwb.duedate, vwb.departmentid, vwb.vendorid, vwb.billamount,
(isnull(vwpmt.paidamount,0) + isnull(vwvp.paidamount,0)) paidamount ,
--"AB" Type
vwb.type
from vwHQAccinterdevBills vwb left outer join vwHQAccinterdevbillPayments vwpmt
on vwb.companyid=vwpmt.phcompanyid and
vwb.billsid=vwpmt.pdIndevBillsID
left outer join vwAccVendrPayments vwvp on vwb.companyid=vwvp.companyid
and vwb.billsid=vwvp.InterdivBillID  --and  vwb.type =''IDB''
--previouse code
-- /****** Object:  View dbo.vwHQAccPaidBills    Script Date: 18/01/2003 9:45:41 PM ******/
--CREATE view vwHQAccPaidBills as
--select vwb.companyid, null as shopid, vwb.billsid, vwb.billsno, vwb.referenceno, vwb.billdate,
--vwb.duedate, vwb.departmentid, vwb.vendorid, vwb.billamount, (isnull(vwpmt.paidamount,0) + isnull(vwvp.paidamount,0)) paidamount ,
--"AB" Type from vwHQAccBills vwb left outer join vwHQAccPayments vwpmt
--on vwb.companyid=vwpmt.phcompanyid and
--vwb.billsid=vwpmt.pdaccbillsid
--left outer join vwAccVendrPayments vwvp on vwb.companyid=vwvp.companyid
--and vwb.billsid=vwvp.billid
--'
GO
/****** Object:  View [dbo].[vwhqpaymentinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwhqpaymentinvandrecamount]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwhqpaymentinvandrecamount] as
select ph.phcompanyid, 0 shopid, ph.phpaymentid, ph.phdepartmentid,  ph.phpaymentno, ph.phpaymentdate,
ph.phpaymentdate duedate, ph.phCustomerID, ph.phcustomeramount,ph.phcbreferenceno refno,
isnull(rsetamt,0) + isnull(csetamt,0) settled, ''PAYMENT'' Type from ahqpaymentvoucherheader ph
left outer join  (select rd.phpaymentid rpaymentid, sum(rd.AmountReceived) rsetamt from
receiptvoucherdetails rd, receiptvoucherheader rh where rh.companyid = rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled =0 and rd.phpaymentid is not null group by rd.phpaymentid) rsettled
on ph.phpaymentid = rpaymentid
left outer join
(select  csd.paymentid cpaymentid, sum(csd.SettlementAmount) csetamt from
customersettlementdetail csd, customersettlementheader csh where csd.companyid = csh.companyid
and csd.csid = csh.csid and csh.cancelled =0 and csd.paymentid is not null group by csd.paymentid ) csettled on
ph.phpaymentid = cpaymentid where ph.phCancelled =0 and ph.phcustomerid is not null group by
ph.phcompanyid, ph.phpaymentid, ph.phdepartmentid,  ph.phpaymentno, ph.phpaymentdate,
ph.phCustomerID, ph.phcustomeramount, rsetamt, csetamt,ph.phcbreferenceno'
GO
/****** Object:  View [dbo].[vwgoodsreturnamount]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgoodsreturnamount]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------
--Ref.No:1
-- Modified By : AADYAKUMAR D V
-- Modified On : 16/02/2012
-- Comment     : Added GrnhGoodsreturnnoteDate
----------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwgoodsreturnamount] as
select sum(isnull(GRNDunitprice,0)) goodsreturnamt ,isnull(SettlementAmount,0) settledamt,
GrnhGoodsreturnnoteID,GrnhCustomerID,GrnCompanyID,GrnhGoodsreturnnoteNO,grnhshopid,
csh.CSID,csh.CSNO,
gdh.GrnhGoodsreturnnoteDate  --Ref.No:1
from
losgoodsreturnnoteheader gdh left outer join losgoodsreturnnotedetail gdd on
gdh.GrnhGoodsreturnnoteID=gdd.GRNDReturnNoteID and gdh.grnhshopid = gdd.grndshopid
left outer  join customersettlementheader csh on gdh.GrnhGoodsreturnnoteID=csh.losGoodsreturnnoteID
and gdh.grnhshopid = csh.shopid  and csh.Cancelled=0 left outer join
(select CSID, isnull(SettlementAmount,0) SettlementAmount from
customersettlementdetail  ) csd on csh.CSID=csd.CSID where GrnhCancel=0
group by GrnhGoodsreturnnoteID,GrnhCustomerID,GrnCompanyID,GrnhGoodsreturnnoteNO,grnhshopid,
csh.csid,csh.CSID,csh.CSNO,SettlementAmount,
gdh.GrnhGoodsreturnnoteDate --Ref.No:1'
GO
/****** Object:  View [dbo].[vwRecSettlementDetails]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRecSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwRecSettlementDetails    Script Date: 18/01/2003 9:45:40 PM ******/
/****** Object:  View dbo.vwRecSettlementDetails    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwRecSettlementDetails    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwRecSettlementDetails    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwRecSettlementDetails    Script Date: 17/11/2001 9:22:03 PM ******/
-- last modified : 28/10/2001
-- modified by   : leo
CREATE view [dbo].[vwRecSettlementDetails] as
SELECT csd.CompanyID, null departmentid, max(csh.CSDATE) csdate, csd.accInvoiceID as InvoiceID,
sum(isnull(csd.settlementamount,0)) as Amtsettled
fROM accountsinvoiceheader ah, customersettlementdetail csd
left outer join customersettlementHeader csh
on csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID
wHERE ah.companyid = csd.companyid and ah.invoiceid = csd.accinvoiceid and
csh.Cancelled = 0 and csd.accInvoiceID is not null
GROUP BY csd.CompanyID, csd.accInvoiceID'
GO
/****** Object:  View [dbo].[vwpurchasebilltracking]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwpurchasebilltracking]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwpurchasebilltracking] as
select pb.pbhbillid,pb.pbhbillno,
pb.pbhbilldate,av.vendorname,pb.pbhVendorBillNo,po.pohpono,pb.pbhBillAmount,
case pb.pbhcancelled  when 1 then ''Yes'' when 0 then ''No'' end Cancelled,
case pb.pbhposted when 1 then ''Yes'' when 0 then ''No'' end as Posted,
vw.QuotationNo,vw.HQRequestNo,vw.ShopRequetNO,po.pohDepartmentid,pb.pbhCompanyId,pb.pbhVendorID from lospPurchaseBillHeader pb,
avendormaster av,lopurchaseorderheader po,vwpurchasetransflow vw where pb.pbhbillid<>0
and  av.vendorid=pb.pbhVendorID and pb.pbhPOID=vw.pohpoid and pb.pbhPOID=po.pohpoid'
GO
/****** Object:  View [dbo].[vwreexportsettlements]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportsettlements]'))
EXEC dbo.sp_executesql @statement = N'
--Created by  : Hariharan
--Created Date: 03/12/2002
CREATE view [dbo].[vwreexportsettlements] as
select st.companyid, st.shopid, st.invoiceid, st.customerid, 0.0 as invoiceamount,
max(receiptdate) receiptdate, sum(settledamt) settledamt, max(refno) refno
from(select rh.companyid, rd.shopid, rd.posexportid invoiceid, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived) settledamt,
max(receiptno) refno from
receiptvoucherheader rh, receiptvoucherdetails rd where rh.companyid=rd.companyid and
rh.receiptid = rd.receiptid and rh.cancelled = 0 and rd.posexportid is not null
group by rh.companyid, rd.shopid, rd.posexportid, rh.customerid, receiptno
union all
select ch.companyid, cd.shopid, losexportid, ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt, csno refno from
customersettlementheader ch, customersettlementdetail cd where ch.companyid = cd.companyid
and ch.csid = cd.csid and ch.cancelled = 0 and cd.losexportid is not null
group by ch.companyid, cd.shopid, cd.losexportid, ch.customerid, csno) st
group by st.companyid, st.shopid, st.invoiceid, st.customerid'
GO
/****** Object:  View [dbo].[vwRequestIssueDesptachArrival]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwRequestIssueDesptachArrival]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwRequestIssueDesptachArrival] As
Select grhRequestID,grhShopID,ReqShopName,grhRequestNo,grhRequestDate,grhRemarks,
	inhIssueNoteID,Location,inhIssueNoteNo,inhIssueDate,inmRemarks,
	dhDespatchID,dhGodownID,GodownName,dhDespatchNo,dhDespatchDate,dhRemarks,
	gahArrivalID,gahShopID,ArrShopName,gahArrivalNo,gahArrivalDate,gahRemarks From
	(Select grhRequestID,grhShopID,ShopName ReqShopName,grhRequestNo,grhRequestDate,grhRemarks From mosGoodsRequestHeader  Left Outer Join
	aShops ON grhShopID=ShopID Where GRHCancel=0 And grhRequestType=''G'')Request
	Left Outer Join
	(Select inhIssueNoteID,inmRequestID,inmShopId,Location,inhIssueNoteNo,inhIssueDate,inmRemarks,dhDespatchID,dhGodownID,
	GodownName,dhDespatchNo,dhDespatchDate,dhRemarks,gahArrivalID,gahShopID,ArrShopName,gahArrivalNo,gahArrivalDate,gahRemarks From
	(Select inmIssueNoteID,inmIssueNoteNo,inmIssueDate,inmRequestID,inmShopId,inhIssueNoteID,inhIssueNoteNo,
	inhIssueDate,inhGodownID,inhToShopID,''HQ'' Location,inmRemarks
	From ahqIssueNoteMain Left Outer Join aHqIssueNoteHeader ON
	inmIssueNoteID = inhIssueNoteMainID And inhCancelled=0
	Where inmCancel=0)IssueNote
	Left Outer Join
	(Select dhIssueNoteID,dhDespatchID,dhGodownID,GodownName,dhDespatchNo,dhDespatchDate,dhRemarks,
			gahArrivalID,gahShopID,ArrShopName,gahArrivalNo,gahArrivalDate,gahRemarks From
		(select dhDespatchID,dhDespatchNo,dhGodownID,GodownName,dhDespatchDate,dhShopID,dhIssueNoteID,dhRemarks
		from meiDespatchToShopHeader Left Outer Join aGodown ON dhGodownID=GodownID and dhCancelled=0)Despatch
	Left Outer Join
		(select gahArrivalID,gahShopID,ShopName ArrShopName,gahArrivalNo,gahArrivalDate,gahGodownDespatchID,gahDespatchedGodownID
		,gahRemarks from losGoodsArrivalToShopHeader Left Outer Join aShops ON gahShopID=ShopID and gahCancelled=0)Arrival
	ON dhDespatchID=gahGodownDespatchID And dhGodownID= gahDespatchedGodownID)DespachArrival
	On dhIssueNoteID=inhIssueNoteID and inhGodownID=dhGodownID)IssueDesptachArrival
On grhRequestID=inmRequestID And grhShopID=inmShopId'
GO
/****** Object:  View [dbo].[vwShopSplSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSplSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopSplSettlementDetails    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwShopSplSettlementDetails] as
SELECT csd.CompanyID, csd.shopid, csd.losspInvoiceID as InvoiceID, max(csh.csdate) csdate,
null departmentid, sum(isnull(csd.settlementamount,0)) as Amtsettled
FROM customersettlementdetail csd
left outer join customersettlementHeader csh
on csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID
WHERE csh.Cancelled = 0 and csd.losspInvoiceID is not null
GROUP BY csd.CompanyID, csd.shopid, csd.losspInvoiceID'
GO
/****** Object:  View [dbo].[vwShopInvSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopInvSettlementDetails    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwShopInvSettlementDetails] as
SELECT csd.CompanyID, csd.shopid, csd.losInvoiceID as InvoiceID, null departmentid,
max(csh.csdate) csdate, sum(isnull(csd.settlementamount,0)) as Amtsettled
FROM customersettlementdetail csd left outer join customersettlementHeader csh
on csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID
WHERE csh.Cancelled = 0 and csd.losInvoiceID is not null
GROUP BY csd.CompanyID, csd.shopid, csd.losInvoiceID'
GO
/****** Object:  View [dbo].[vwShopInvoiceSettlementNo]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopInvoiceSettlementNo]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Modified on 	        : 26/11/2003
-- Modified by		: Kishore
-- Comments		: Added SettledAmt column
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwShopInvoiceSettlementNo] AS
select companyid, customerid, shopid, max(setdate) setdate, max(refno) refno,
invoiceid, sum(settledamt) SettledAmt
from
(select ch.companyid, ch.customerid, ch.csdate setdate, ch.csno refno, cd.losinvoiceid
invoiceid, cd.shopid, cd.SettlementAmount settledamt
from customersettlementheader ch, customersettlementdetail cd
where ch.companyid = cd.companyid
and ch.csid = cd.csid
and cd.losinvoiceid is not null
and ch.cancelled = 0
union all
select rh.companyid, rh.customerid, rh.receiptdate setdate, rh.receiptno refno,
rd.posinvoiceid invoiceid, rd.shopid, AmountReceived
from receiptvoucherheader rh, receiptvoucherdetails rd
where rh.companyid = rd.companyid
and rh.receiptid = rd.receiptid
and rh.cancelled = 0
and rh.customerid is not null
and rd.posinvoiceid is not null) settledaccinvoices
group by companyid, customerid, shopid,  invoiceid'
GO
/****** Object:  View [dbo].[vwshopdrcrinvandrecamount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopdrcrinvandrecamount]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view  [dbo].[vwshopdrcrinvandrecamount] as
select sdcn.losdcncompanyid, sdcn.losdcnshopid, sdcn.losdcnid, sdcn.losdcndepartmentid,
sdcn.losdcnno, sdcn.losdcndate, sdcn.losdcndate duedate, sdcn.losDCNCustomerID, refno,
sdcn.losdcnamount, isnull(rsetamt,0) + isnull(csetamt,0) settled, ''SDEBIT'' Type,
sdcn.losdcnamount * losexchangerate cdcnamount, sdcn.losdcnamount * losdepexrate
ddcnamount from  losdebitcreditnote sdcn left outer join
(select rd.shopid rshopid, rd.losdcnid rdcnid, sum(rd.AmountReceived) rsetamt ,rh.ReferenceNo refno from receiptvoucherdetails rd,
receiptvoucherheader rh where rh.companyid = rd.companyid and rh.receiptid = rd.receiptid
and rh.cancelled =0 and losdcnid is not null group by rd.shopid, rd.losdcnid,rh.ReferenceNo) rsettled on losdcnshopid = rshopid
and losdcnid = rdcnid
left outer join
(select csd.shopid cshopid, csd.losdcnid cdcnid, sum(csd.SettlementAmount) csetamt from
customersettlementdetail csd, customersettlementheader csh where csd.companyid = csh.companyid
and csd.csid = csh.csid and csh.cancelled =0 and csd.losdcnid is not null group by csd.shopid, csd.losdcnid ) csettled on
losdcnshopid = cshopid and losdcnid = cdcnid
where sdcn.losDCNCancelled =0 and losdcnDebit=1  group by
sdcn.losdcncompanyid, sdcn.losdcnshopid, sdcn.losdcnid, sdcn.losdcndepartmentid,
sdcn.losdcnno, sdcn.losdcndate, sdcn.losdcndate, sdcn.losDCNCustomerID, sdcn.losdcnamount,
rsetamt, csetamt, losexchangerate, losdepexrate,refno'
GO
/****** Object:  View [dbo].[vwsettlements]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsettlements]'))
EXEC dbo.sp_executesql @statement = N'
--MODIFIED ON   : 01/08/2003, 04/09/2003, 23/01/2004, 09/03/2004, 11/05/2004,25/02/2010,25/03/2010,11/10/2010
--MODIFIED BY  : R HARIKRISHNAN, HARIHARAN,PRASANTH JOSEPH,NIDHEESH P V JYOTHISH SR
--COMMENTS  : CORRECTED THE ALLIGNMENT
--   : ADDED ROOM BILL & UTILITY BILL FOR MANAAM
--   : CORRECTED ROOM BILL & UTILITY BILL QUERIES FOR MANAAM
--   : MODIFIED TO ADD RE-EXPORT DETAILS
--   : SHOPID INCLUDED FROM CUSTOMERSETTLEMENTDETAIL FOR MANAM BILLS
--   : SHOPID INCLUDED FROM CUSTOMERSETTLEMENTDETAIL FOR SERVICE MODULE BILLS
--   : ADDED FINE SETTLEMNT DETAILS. Type for Fine Transaction is ''FINE''
--   : MODIFIED FINE TYPE.
---  : FAND SHOP IS ADDED
-----------------------------------------------------------------
CREATE VIEW [dbo].[vwsettlements] as
select
rh.customerid,rh.ReceiptNo,rh.companyid ,rd.HQaccountsinvoiceid invoiceid,
0 shopid, rh.ReceiptDate settleddate, rh.departmentid, amountreceived settledamt,
''AI'' AS Type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0
and rd.HQaccountsinvoiceid is not null
union all
-----------FANDB
select CustomerID,ReceiptNo,rt.CompanyID,fandbInvoiceID,shopid,ReceiptDate,
DepartmentID,AmountReceived,''fandb'' type   from ReceiptVoucherHeader rh
inner join  Receiptvoucherdetails  rt on
rh.ReceiptID=rt.ReceiptID where  Cancelled=0 and isnull(fandbInvoiceID,0)<>0
union all
select drcustomerid,drNo ,drCompanyid,drdfandbInvoiceID,drShopid,DrDate,s.DepartmentID, drdsettledamount settledamount , ''fandb'' type
from LosDummyReceiptHeader lh
inner join LosDummyReceiptdetail  lt on lh.drShopid=lt.drdShopID and lt.drdid=lh.drId
inner join ashops s on s.ShopID=drShopid
where  drcancelled=0 and isnull(drdfandbInvoiceID,0)>0
---------------------
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.accInvoiceID as InvoiceID, 0 shopid,
csh.CSDATE csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''AI'' AS Type
FROM
customersettlementdetail csd, customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.accInvoiceID is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.posaccountsinvoiceid, rd.shopid,
rh.receiptdate receiptdate, rh.departmentid, amountreceived settledamt,
''PSI'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and
rh.cancelled = 0 and rd.posaccountsinvoiceid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.losaccInvoiceID as InvoiceID, CSD.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''PSI'' as type
FROM
customersettlementdetail csd ,customersettlementHeader csh                  WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losaccInvoiceID is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.posinvoiceid, rd.shopid,
rh.receiptdate receiptdate, rh.departmentid, amountreceived settledamt,
''PCI'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.posinvoiceid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.losInvoiceID InvoiceID, csd.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''PCI'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losInvoiceID is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.posspinvoiceid, rd.shopid,
rh.receiptdate receiptdate, rh.departmentid, amountreceived settledamt,
''PDI'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.posspinvoiceid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.losspInvoiceID InvoiceID, csd.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''PDI'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losspInvoiceID is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.dcnid, 0, rh.receiptdate receiptdate,
rh.departmentid, amountreceived settledamt, ''DCN'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.dcnid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.dcnID InvoiceID, 0, csh.csdate csdate,
csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled, ''DCN'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.dcnid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.paymentID InvoiceID, 0, csh.csdate csdate,
csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled, ''rf'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.paymentid is not null
union all
SELECT
rh.customerid, rh.receiptNO, rh.CompanyID, rd.phpaymentID InvoiceID, 0,
rh.receiptdate csdate, rh.departmentid, isnull(rd.amountreceived,0) as Amtsettled,
''rf'' as type
FROM
receiptvoucherdetails rd , receiptvoucherheader rh
WHERE
rh.receiptid = rd.receiptid and
rd.CompanyID = rh.CompanyID and rh.Cancelled = 0 and rd.phpaymentid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.losdcnID InvoiceID, csd.shopid, csh.csdate csdate,
csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled, ''sdcn'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losdcnid is not null
union all
SELECT
rh.customerid, rh.receiptNO, rh.CompanyID, rd.losdcnid InvoiceID, rd.shopid,
rh.receiptdate csdate, rh.departmentid, isnull(rd.amountreceived,0) as Amtsettled,
''sdcn'' as type
FROM
receiptvoucherdetails rd , receiptvoucherheader rh
WHERE
rh.receiptid = rd.receiptid and rd.CompanyID = rh.CompanyID and rh.Cancelled = 0 and
rd.losdcnid is not null
union all
SELECT
csh.customerid, csh.CSNO, csd.CompanyID, csd.losserinvoiceid InvoiceID, csd.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''sbi'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losserinvoiceid is not null
union all
SELECT
rh.customerid, rh.receiptNO, rh.CompanyID, rd.Posserviceinvoiceid InvoiceID, rd.shopid,
rh.receiptdate csdate, rh.departmentid, isnull(rd.amountreceived,0) as Amtsettled,
''sbi'' as type
FROM
receiptvoucherdetails rd , receiptvoucherheader rh
WHERE
rh.receiptid = rd.receiptid and rd.CompanyID = rh.CompanyID and rh.Cancelled = 0 and
rd.Posserviceinvoiceid is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.RoomBillID, rd.shopid,
rh.receiptdate receiptdate, rh.departmentid, amountreceived settledamt,
''RBI'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.RoomBillID is not null
UNION ALL
SELECT
csh.customerid, csh.CSNO, csd.CompanyID, csd.RoomBillID InvoiceID, csd.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''RBI'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.RoomBillID is not null
UNION ALL
select
rh.customerid,rh.ReceiptNo,rh.companyid, rd.UtilityBillID, rd.shopid,
rh.receiptdate receiptdate, rh.departmentid, amountreceived settledamt,
''UTB'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0 and
rd.UtilityBillID is not null
UNION ALL
SELECT
csh.customerid, csh.CSNO, csd.CompanyID, csd.UtilityBillID InvoiceID, csd.shopid,
csh.csdate csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''UTB'' as type
FROM
customersettlementdetail csd , customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.UtilityBillID is not null
union all
select
rh.customerid,rh.ReceiptNo,rh.companyid ,rd.posexportid invoiceid,
rd.shopid, rh.ReceiptDate settleddate, rh.departmentid, amountreceived settledamt,
''RE'' as type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0
and rd.posexportid is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.losexportid as InvoiceID, csd.shopid shopid,
csh.CSDATE csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''RE'' as type
FROM
customersettlementdetail csd, customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.losexportid is not null
union all
---Fine Charge Setting Details-------------------------------------
select
rh.customerid,rh.ReceiptNo,rh.companyid ,rd.fineid invoiceid,
0 shopid, rh.ReceiptDate settleddate, rh.departmentid, amountreceived settledamt,
''FINE'' AS Type
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and rh.cancelled = 0
and rd.fineid  is not null
union all
SELECT
csh.customerid,csh.CSNO,csd.CompanyID, csd.fineid as InvoiceID, 0 shopid,
csh.CSDATE csdate, csh.departmentid, isnull(csd.settlementamount,0) as Amtsettled,
''FINE'' AS Type
FROM
customersettlementdetail csd, customersettlementHeader csh
WHERE
csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID and
csh.Cancelled = 0 and csd.fineid  is not null'
GO
/****** Object:  StoredProcedure [dbo].[spInventoryforcat_adv]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryforcat_adv]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spInventoryforcat_adv 1,0,''27'',''250'',''20100110''
/*
CREATED BY  : NIDHEESH P V
CREATED ON  : 15-02-2010
CREATED FOR : NEED TO GET ADVANCE INVENTORY FORCAT REPORT. RHIS PROCEDURE WILL RETURN LAST 30DAYS SALES PLUS QUATERILY AVARAGE SALES PLUS EXTRA.
USAGE     :
*/
-------------------------------------
CREATE PROCEDURE [dbo].[spInventoryforcat_adv]
(
@CompanyID AS INT,
@DepartmentID AS INT,
@strCategoryID AS VARCHAR(500),
@strItemID AS VARCHAR(500),
@Date AS varchar(10)
)
AS
SET NOCOUNT ON
BEGIN
declare
@dtDate as datetime,
@startdate as datetime,
@enddate as datetime,
@STR as varchar(max),
@STR1 as varchar(max)
--set @dtDate= convert(datetime,@Date)
set @dtDate = cast (@Date as datetime)
--print @dtDate
select @STR1=''a.ItemDescription,a.Part_code,a.itemcode,d.dname,c.CategoryNameDescription,v.* from ( select vw.Itemid,sum(VW.PreviousMonth)PreMonthSum,
sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,''
SELECT @STR1=ISNULL(@STR1,'''')+''SUM(''+''DAY''+CONVERT(VARCHAR,DAY(TDATE))+'')''+ ''DAY'' + CONVERT(VARCHAR,DAY(TDATE)) + '','' + CONVERT(VARCHAR,DAY(TDATE))+ ''H'' + CONVERT(VARCHAR,DAY(TDATE)) + '','' FROM  fnMakeDateTable(@dtDate,1)
SELECT @STR1=SUBSTRING(@STR1,1,LEN(@STR1)-1)+'' From (''
select @STR=''Select Itemid,sum(PreviousMonth)PreviousMonth,sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,
sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,''
SELECT @STR=ISNULL(@STR,'''')+''
CASE WHEN DAY(StockDate)=''+ CONVERT(VARCHAR,DAY(TDATE))+'' THEN SUM(AsonSale) END ''+''''''''+ ''DAY'' + CONVERT(VARCHAR,DAY(TDATE))+''''''''+ '' ,''  FROM  fnMakeDateTable(@dtDate,1)
SELECT @STR=SUBSTRING(@STR,1,LEN(@STR)-1)
CREATE TABLE #ItemDetail
(
ItemID INT,
CompanyID INT,
DepartmentID INT,
SHOPID INT,
CategoryID INT,
Description VARCHAR(200),
BinLocation VARCHAR(50),
StockDate DATETIME,
SlNo INT,
AsonSale NUMERIC(18,2),
PreviousMonth NUMERIC(18,2),
Last3MonthAvg NUMERIC(18,2),
Last6MonthAvg NUMERIC(18,2),
Last12MonthAvg NUMERIC(18,2),
Last24MonthAvg NUMERIC(18,2)
)
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,StockDate,SlNo,AsonSale)
SELECT posdItemID,CompanyID,DepartmentID,poshShopId,Tdate,SlNo,sum(isnull(Quantity,0)) Qty FROM fnMakeDateTable(@dtDate,1) left outer join
vwSalesAnalysisByItem on  TDate=poshBillDate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''')--AND posdItemID=@strItemID
inner join ashops on poshShopId=ShopID  and CompanyID=@CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)
group by posdItemID,poshShopId,Tdate,SlNo,DepartmentID ,CompanyID
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,PreviousMonth)
select posdItemID,CompanyID,DepartmentID,poshShopId,sum(isnull(Quantity,0))Qty from vwSalesAnalysisByItem v
inner join ashops on poshShopId=ShopID  and CompanyID= @CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)
where year(poshBillDate)=YEAR(DATEADD(m, -1, @dtDate))and month(poshBillDate)=MONTH(DATEADD(m, -1, @dtDate)) AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''')--and posdItemID=@strItemID
group by posdItemID,poshShopId,DepartmentID,CompanyID
---Lst3monthsAvg----
set @startdate= dateadd(m,-3,@dtDate)
set @enddate= dateadd(m,-1,@dtDate)
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last3MonthAvg)
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/3)Qty from vwSalesAnalysisByItem v
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''') --and posdItemID=@strItemID
group by posdItemID,poshShopId,DepartmentID,CompanyID
---Lst6monthsAvg----
set @startdate= dateadd(m,-6,@dtDate)
set @enddate= dateadd(m,-1,@dtDate)
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last6MonthAvg)
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/6)Qty from vwSalesAnalysisByItem v
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''') --and posdItemID=@strItemID
group by posdItemID,poshShopId,DepartmentID,CompanyID
---Lst12monthsAvg----
set @startdate= dateadd(m,-12,@dtDate)
set @enddate= dateadd(m,-1,@dtDate)
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last12MonthAvg)
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/12)Qty from vwSalesAnalysisByItem v
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''') --and posdItemID=@strItemID
group by posdItemID,poshShopId,DepartmentID,CompanyID
---Lst24monthsAvg----
set @startdate= dateadd(m,-24,@dtDate)
set @enddate= dateadd(m,-1,@dtDate)
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last24MonthAvg)
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/24)Qty from vwSalesAnalysisByItem v
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,'','')) or @strCategoryID='''') --and posdItemID=@strItemID
group by posdItemID,poshShopId,DepartmentID,CompanyID
exec(
''SELECT ''+ @STR1+@STR +  '' FROM #ItemDetail GROUP BY Itemid,StockDate,PreviousMonth )vw where itemid is not null Group by vw.Itemid)v
inner join aitem a on v.ItemID=a.ItemID inner join aitemcategory c on c.ItemCategoryID=a.ItemCategoryID inner join adistributormaster d on d.did=a.did'')
SET NOCOUNT OFF
end
----------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDayendReportUserWise]    Script Date: 10/06/2012 14:17: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].[spDayendReportUserWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ===========================================================
-- Author		:	MANUNADH. U
-- Create date	:	03/03/2011
-- Description	:	For populating UserWise Reports
-- ===========================================================
create proc [dbo].[spDayendReportUserWise]
(
	@TransDate as datetime, @Shopid as int
)
AS
BEGIN
	Declare @dtTransDate as datetime
	set @dtTransDate = convert(datetime,@TransDate,101)
	
	SELECT U.UserID,U.UserName,vw.Billid, vw.BillNo, vw.shopid,vw.billdate, vw.amount,--C.CounterName,
	A.AccountDesc--isnull(A.AccountDesc,'''')
	FROM LOUsers U
		INNER JOIN vwDailySalesUserWise vw ON U.UserID = vw.poshuserid
		left outer JOIN aAccountMaster A ON vw.accountid = A.AccountID
		--left outer JOIN aCounterMaster C ON vw.counterid = C.CounterId
WHERE
		vw.shopid =@Shopid AND vw.billdate >= @TransDate AND vw.billdate <= @TransDate
	ORDER BY
		U.UserID asc,A.AccountDesc ASC,vw.Billid ASC
END' 
END
GO
/****** Object:  View [dbo].[vwcashsalestruncated]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcashsalestruncated]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcashsalestruncated    Script Date: 18/01/2003 9:45:39 PM ******/
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
------------------------------------------------------------------------------------------
-- RefNo        : RefNo-1
-- Modified by  : Bijesh.B
-- Date         : 19/08/2011
-- Ticket Id    : JSZ-828136 (SHEESHA)
-- Description  : Need UserWise selection for Cash Denomination interface
--              : UserID column included
------------------------------------------------------------------------------------------
CREATE view [dbo].[vwcashsalestruncated] as
select vs.companyid, vs.shopid, billdate, accountid,
amount actamount, damount, camount, cash ,transtype, vs.departmentid,vs.userid
from vwcashsales vs'
GO
/****** Object:  StoredProcedure [dbo].[spLeadTimeForPurchase]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spLeadTimeForPurchase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------
-- Created by    : Kishore
-- Created on    : 27/11/2003
-- Comments      : Created to display lead time details
--                 Used in rptLeadTimeForPurchase.rpt
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spLeadTimeForPurchase] (@intBillId as int, @intItemId as int = 0) AS
BEGIN
Declare @dtDate as DateTime
Declare @intPoId as int
Declare @dtPoDate as DateTime
Declare @intQuotationId as int
Declare @intRefId as int
Declare @strType as Varchar(1)
Declare @intRequestId as int
Declare @intDespatchId as int
Declare @curTransactionId as int
Declare @curTransactionDate as DateTime
Declare @intCount as int
Declare @dtPrevDate as DateTime
Declare @intDateDiff as int
Declare @strRequestDeptName as Varchar(50)
Declare @strImportsDeptName as Varchar(50)
Declare @strFinanceDeptName as Varchar(50)
Declare @bitGodown as bit
Declare @strBillNo as Varchar(50)
Declare @strSupplierName as Varchar(100)
Declare @intQuotationCount as int
Declare @intShopRequestShopId as int
Declare @intShopRequestId as int
Declare @strDepartment as Varchar(100)
Set NoCount On
-- if billid and item id is zero, raise an error
If @intBillId = 0 And @intItemId = 0
Begin
RaisError(''Either @intBillId or @intItemId must be a non-zero value'', 16, 1)
End
Else If @intBillId = 0 -- if billid is zero, get last bill id of the item
Begin
SELECT TOP 1 @intBillId = pbhBillId
FROM lospPurchaseBillHeader pbh, lospPurchaseBillDetail pbd
WHERE pbhBillId = pbdBillId
AND pbdItemId = @intItemId
AND pbhCancelled = 0
ORDER BY pbhBillDate DESC
End
-- create temporary table
CREATE TABLE #LeadTime(
TransactionId          int PRIMARY KEY,
TransactionName        Varchar(200) UNIQUE,
RequestDepartment      Varchar(50),
ImportsDepartment      Varchar(50),
Supplier               Varchar(50),
FinanceDepartment      Varchar(50),
Godown                 Varchar(50),
Shop                   Varchar(50),
TransactionDate        DateTime)
-- get purchase bill date, bill no, supplier name etc.
Set @dtDate = ''19800101''
SELECT @dtDate = pbhShipArrivalDate, @strBillNo = pbhBillNo,
@strSupplierName = VendorName, @strDepartment = d.DepartmentName
FROM lospPurchaseBillHeader pbh, aVendorMaster v, aDepartmentMaster d
WHERE pbhVendorId = v.VendorId
AND pbhDepartmentId = d.DepartmentId
AND pbhBillId = @intBillId
AND pbhCancelled = 0
-- insert purchase bill date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(8, ''Port of loading - arrival to Malé port'', '''', '''', @dtDate, '''',
'''', '''', @dtDate)
End
-- get laid bill date
Set @dtDate = ''19800101''
SELECT @dtDate = pohBofLadDate, @intPoId = pohPoId, @dtPoDate = pohPoDate,
@strImportsDeptName = d.DepartmentName
FROM loPurchaseOrderHeader poh, aDepartmentMaster d
WHERE pohPoId = (SELECT pbhPoId FROM lospPurchaseBillHeader
WHERE pbhBillId = @intBillId
AND pbhCancelled = 0)
AND pohDepartmentId = d.DepartmentId
AND pohType = ''P''
-- insert laid bill date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(7, ''Despatch of goods'', '''', '''', @dtDate, '''',
'''', '''', @dtDate)
End
-- get advance date
Set @dtDate = ''19800101''
SELECT @dtDate = phPaymentDate, @strFinanceDeptName = d.DepartmentName
FROM aHqPaymentVoucherHeader ph, aDepartmentMaster d
WHERE phDepartmentId = d.DepartmentId
AND phPohId = @intPoId
AND phCancelled = 0
-- insert advance date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(6, ''Arranging fund'', '''', '''', '''', @dtDate,
'''', '''', @dtDate)
End
If @dtPoDate <> ''19800101''
Begin
-- insert po date
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(4, ''Process P/O'', '''', @dtPoDate, '''', '''', '''', '''', @dtPoDate)
End
-- get last quotation date
Set @dtDate = ''19800101''
SELECT @dtDate = pohPoDate, @intQuotationId = pohPoId
FROM loPurchaseOrderHeader
WHERE  LEFT(pohType, 1) = ''Q''
AND  pohPoId = (SELECT pohQuotationId FROM loPurchaseOrderHeader
WHERE pohPoId = @intPoId
AND pohType = ''P'')
-- insert quotation date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(3, ''Receiving quotation'', '''', '''', @dtDate, '''', '''', '''', @dtDate)
End
-- get first quotation no.
-- quotations can be generated referring other quotations
-- in that case, we want to get the first quotation id to get request no
Set @intRefId = @intQuotationId
Set @intQuotationCount = 0
-- get the count of other quotation based on this quoation
SELECT @intQuotationCount = COUNT(*) FROM loPurchaseOrderHeader
WHERE PohPoId = @intRefId -- changed on 13/12/2003
AND Left(pohType, 1) = ''Q''
AND pohCancel = 0
AND pohQuotationId IS NOT NULL
WHILE @intQuotationCount <> 0
Begin
SELECT @intRefId = pohQuotationId
FROM loPurchaseOrderHeader
WHERE pohPoId = @intRefId
AND Left(pohType, 1) = ''Q''
AND pohCancel = 0
AND pohQuotationId IS NOT NULL
SELECT @intQuotationCount = COUNT(*) FROM loPurchaseOrderHeader
WHERE PohPoId = @intRefId
AND Left(pohType, 1) = ''Q''
AND pohQuotationId IS NOT NULL
AND pohCancel = 0
End
-- check the ref id exists in any request
Set @intRequestId = 0
Set @dtDate = ''19800101''
Set @intRequestId = @intRefId
-- now get the request date
IF @intRequestId <> 0 AND @intRequestId IS NOT NULL
Begin
SELECT @dtDate = pohPoDate, @intShopRequestId = pohRequestId,
@intShopRequestShopId = pohShopId
FROM loPurchaseOrderHeader
WHERE pohType = ''R''
AND pohpoid = @intRequestId
AND pohCancel = 0
If @dtDate <> ''19800101''
Begin
-- insert quotation date
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(2, ''Inquiring supplier'', '''', @dtDate, '''', '''', '''', '''', @dtDate)
End
End
Else
Begin
SELECT @intShopRequestShopId = pohShopId, @intShopRequestId = pohRequestId
FROM loPurchaseOrderHeader
WHERE Left(pohType, 1) = ''Q''
AND pohpoid = @intRefId
AND pohCancel = 0
End
-- if it is from a shop request
If @intShopRequestId <> 0 And @intShopRequestShopId IS NOT NULL
Begin
Set @dtDate = ''19800101''
SELECT @dtDate = grhRequestDate
FROM mosGoodsRequestHeader
WHERE grhShopId = @intShopRequestShopId
AND grhRequestId = @intShopRequestId
If @dtDate <> ''19800101''
Begin
-- insert shop request date
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(1, ''Order request'', @dtDate, '''', '''', '''', '''', '''', @dtDate)
End
End
-- get payment date of custom duty payment
Set @dtDate = ''19800101''
SELECT @dtDate = phPaymentDate FROM aHqPaymentVoucherHeader
WHERE phLcPayment = ''CDP''
AND phCancelled = 0
AND phPohId = @intPoId
SELECT @dtDate = phPaymentDate
FROM aHqPaymentVoucherHeader ph, aHqPaymentVoucherDebitDetails pdd
WHERE phPaymentId = pddPaymentId
AND phLcPayment = ''CDP''
AND phCancelled = 0
AND pddHqPoId = @intPoId
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(9, ''Customs Clearance'', '''', @dtDate, '''', '''', '''', '''', @dtDate)
End
-- get costing date
Set @dtDate = ''19800101''
SELECT @dtDate = chCostingDate
FROM loaCostingHeader
WHERE chBillId = @intBillId
AND chCancelled = 0
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(10, ''Costing'', '''', @dtDate, '''', '''', '''', '''', @dtDate)
End
-- get date of despatch to shop/godown
-- get the shop id too, if the despatch is to a shop
Set @dtDate = ''19800101''
SELECT @dtDate = dnmDespatchNoteDate, @intDespatchId = dhDespatchnoteId, --dnmDespatchNoteId,
@bitGodown = CASE ISNULL(dhGodownId, 0) WHEN 0 THEN 0 ELSE 1 END
FROM aHQDespatchNoteMain dnm, aHqDespatchNoteHeader dh LEFT OUTER JOIN aShops s
ON dhShopId = s.ShopId
WHERE dnmDespatchNoteID = dhDespatchNoteMainId
AND dnmBillId = @intBillId
AND dnmCancelled = 0
-- insert godown despatcht to shop date
If @dtDate <> ''19800101''
Begin
-- if it is despatch to shop, store date in shop column
If @bitGodown = 0
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(11, ''Despatch to Shop'', '''', @dtDate, '''', '''', '''', '''', @dtDate)
End
Else    -- other wise store date in godown field
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(11, ''Despatch to Godown'', '''', @dtDate, '''', '''', '''', '''', @dtDate)
End
End
-- if it is despatch to godown, take godown arrival
if @bitGodown = 1
Begin
-- get godown arrival date
Set @dtDate = ''19800101''
SELECT @dtDate = MIN(ahArrivalDate)
FROM loiArrivalHeader ah, aGodown g, aHQDespatchNoteMain dnm,
aHqDespatchNoteHeader dh
WHERE ahDespatchNoteId = dhDespatchnoteID
AND dnmDespatchNoteID = dhDespatchNoteMainId
AND ahLocalGodownId = g.GodownId
AND dnmBillId = @intBillId
AND ahCancelled = 0
-- insert godown Arrival date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(12, ''Godown Receive'', '''', '''', '''', '''', @dtDate, '''', @dtDate)
End
End
Else    --    otherwise take shop arrival
Begin
-- get shop arrival date
Set @dtDate = ''19800101''
SELECT  @dtDate = MIN(gahArrivalDate)
FROM LOsGoodsArrivaltoShopHeader gah, aShops s,
aHQDespatchNoteMain dnm, aHqDespatchNoteHeader dh
WHERE dnmDespatchNoteID = dhDespatchNoteMainId
AND dnmBillId = @intBillId
AND gahShopid = s.ShopId
AND gahCancelled = 0
AND gahhqdespatchid = dhDespatchnoteID
-- insert shop Arrival date
If @dtDate <> ''19800101''
Begin
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment,
ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop, TransactionDate)
VALUES
(12, ''Shop Receive'', '''', '''', '''', '''', '''', @dtDate, @dtDate)
End
End
-- Now replace the dates with leading time (in days)
DECLARE curLead CURSOR FOR
SELECT TransactionId, TransactionDate FROM #LeadTime
ORDER BY TransactionId
OPEN curLead
FETCH NEXT FROM curLead INTO @curTransactionId, @curTransactionDate
Set @intCount = 0
Set @dtPrevDate = ''19800101''
WHILE @@Fetch_status = 0
Begin
-- avoid if transaction id is zero, becos zero is for titles
If @curTransactionId <> 0
Begin
If @dtPrevDate = ''19800101''
Begin
Set @intDateDiff = 1
End
Else
Begin
Set @intDateDiff = DateDiff(d, @dtPrevDate, @curTransactionDate)
End
-- replace the date with no. of days
UPDATE #LeadTime
SET RequestDepartment = CASE
WHEN RequestDepartment = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END,
ImportsDepartment = CASE
WHEN ImportsDepartment = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END,
Supplier = CASE
WHEN Supplier = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END,
FinanceDepartment = CASE
WHEN FinanceDepartment = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END,
Godown = CASE
WHEN Godown = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END,
Shop = CASE
WHEN Shop = '''' THEN ''''
ELSE CAST(@intDateDiff as varchar(5)) END
WHERE TransactionId = @curTransactionId
Set @dtPrevDate = @curTransactionDate
End
Set @intCount = @intCount + 1
FETCH NEXT FROM curLead INTO @curTransactionId, @curTransactionDate
End
-- insert titles as first row
INSERT INTO #LeadTime
(TransactionId, TransactionName, RequestDepartment, ImportsDepartment, Supplier,
FinanceDepartment, Godown, Shop)
VALUES
(0, '''', ''Requested Dept'',
''Imports Dept'', ''Supplier'',
''Finance Dept'', ''Godown'', ''Shop'')
-- display records
SELECT @intBillId BillId, @strBillNo BillNo, @strSupplierName SupplierName, *,
@strDepartment DepartmentName
FROM #LeadTime ORDER BY TransactionId
DROP TABLE #LeadTime
Set NoCount Off
End
-----------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwdespatchtoshop]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwdespatchtoshop]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 12/12/02, 03/02/2004
--Modified by  : leo, Hariharan
--Comments  : v3
--   : Summing up of qty due to more sellingprices blocked grouping with Qty
CREATE view [dbo].[vwdespatchtoshop] as
select inmissuenoteno, inhissuenoteno, dhDespatchNo, dhdespatchid, dhgodownid,
dhdespatchdate, d.ddItemID,isnull(INDQty,0) INDQty, ddItemGoodQty
ddItemGoodQty,a.itemdescription, shopname, dhVehicleNo, dhremarks, godownname,
max(ddcostedprice) costprice, max(sellingprice) sellingprice, inhshopreqno shopreqno,PackingTypeName from
meidespatchtoshopheader h left outer join ahqissuenoteheader  on inhissuenoteid= dhissuenoteid
and inhgodownid=dhgodownid left outer join ahqissuenotemain on inhissuenotemainid=inmissuenoteid
left outer join meidespatchtoshopdetail d on dhDespatchID=d.ddDespatchID  and dhgodownid=d.ddgodownid
left outer join  ahqissuenotedetail on dditemid=inditemid and ddgodownid=indgodownid and
ddshipmentid=indshipmentid and dhissuenoteid=indissuenoteid
left outer join vwitemdescription a on a.itemid=d.ddItemID
left outer join vwshopitemshipmentdetailpu sd on dditemid = sd.itemid and ddshopid = sd.shopid
left outer join  aPackingType ap on d.ddpackingtypeid = ap.PackingTypeID,
ashops s, agodown g where dhshopid=s.shopid and dhShopID=d.ddShopID and dhgodownid=g.godownid
group by inmissuenoteno, inhissuenoteno, inhshopreqno, dhdespatchid, dhgodownid, dhDespatchNo,
dhdespatchdate, d.ddItemID, a.itemdescription, dhvehicleno, shopname, dhremarks,
godownname, INDQty, ddItemGoodQty, PackingTypeName'
GO
/****** Object:  View [dbo].[vwDespatchOutQty]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchOutQty]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 14/09/2002 12:48:08 AM ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 31/07/2002 2:00:30 PM ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 20/11/2001 9:59:03 AM ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 17/11/2001 9:21:43 PM ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 16/06/2001 15:36:33 ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 09/03/2001 02:32:27 ******/
/****** Object:  View dbo.vwDespatchOutQty    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwDespatchOutQty] as
select ddGodownID,ddItemID,sum(dditemgoodqty) as despatchQty,dhDespatchDate from meidespatchtoshopdetail,
meidespatchtoshopheader where ddDespatchID=dhDespatchID and ddGodownID=dhGodownID and dhCancelled=0
group by ddGodownID,dhDespatchDate,ddItemID'
GO
/****** Object:  View [dbo].[vwDespatchArrival]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDespatchArrival]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwDespatchArrival] as
Select dhDespatchID,dhGodownID,GodownName,dhDespatchNo,dhDespatchDate,dhRemarks,
			gahArrivalID,gahShopID,ArrShopName,gahArrivalNo,gahArrivalDate,gahRemarks From
		(select dhDespatchID,dhDespatchNo,dhGodownID,GodownName,dhDespatchDate,dhShopID,dhIssueNoteID,dhRemarks
		from meiDespatchToShopHeader Left Outer Join aGodown ON dhGodownID=GodownID and dhCancelled=0)Despatch
	Left Outer Join
		(select gahArrivalID,gahShopID,ShopName ArrShopName,gahArrivalNo,gahArrivalDate,gahGodownDespatchID,gahDespatchedGodownID
		,gahRemarks from losGoodsArrivalToShopHeader Left Outer Join aShops ON gahShopID=ShopID and gahCancelled=0)Arrival
	ON dhDespatchID=gahGodownDespatchID And dhGodownID= gahDespatchedGodownID
where  dhIssueNoteId is null'
GO
/****** Object:  View [dbo].[vwDailySalesCollection]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDailySalesCollection]'))
EXEC dbo.sp_executesql @statement = N'
--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
----------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDailySalesCollection] AS
select companyid,departmentid, shopid, billdate,
convert(numeric(18, 2), sum(cashsales)) cashsales,
convert(numeric(18, 2), sum(dcashsales)) dcashsales,
convert(numeric(18, 2), sum(ccashsales)) ccashsales,
convert(numeric(18, 2), sum(receipts)) receipts,
convert(numeric(18, 2), sum(dreceipts)) dreceipts,
convert(numeric(18, 2), sum(creceipts)) creceipts,
convert(numeric(18, 2), sum(payments)) payments ,
convert(numeric(18, 2), sum(dpayments)) dpayments ,
convert(numeric(18, 2), sum(cpayments)) cpayments ,
convert(numeric(18, 2), sum(creditsales)) creditsales,
convert(numeric(18, 2), sum(dcreditsales)) dcreditsales,
convert(numeric(18, 2), sum(ccreditsales)) ccreditsales,
convert(numeric(18, 2), sum(creditcard)) as creditcard,
convert(numeric(18, 2), sum(dcreditcard)) as dcreditcard,
convert(numeric(18, 2), sum(ccreditcard)) as ccreditcard,
convert(numeric(18, 2), sum(debitcard)) as debitcard,
convert(numeric(18, 2), sum(ddebitcard)) as ddebitcard,
convert(numeric(18, 2), sum(cdebitcard)) as cdebitcard,
convert(numeric(18, 2), sum(localpurchase)) as localpurchase,
convert(numeric(18, 2), sum(dlocalpurchase)) as dlocalpurchase,
convert(numeric(18, 2), sum(clocalpurchase)) as clocalpurchase
--RefNo-2 start -------------------
,convert(numeric(18, 2), sum(PdChequeSales)) PdChequeSales,
convert(numeric(18, 2), sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18, 2), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------
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 ---------------------------------------------
from vwCashSales 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,2),sum(drAmount)) receipts,
convert(numeric(18,2),sum(drAmount* drdepexrate)) dreceipts,
convert(numeric(18,2),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 -------------------
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
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,2),sum(rd.AmountReceived)) receipts,
--convert(numeric(18,2),sum(rd.AmountReceived )) dreceipts,
--convert(numeric(18,2),sum(rd.AmountReceived )) creceipts,
--RefNo-4  --------------------------start--------------------------------------
------------------ Benzigar code -------------------------------------------
--convert(numeric(18,2),sum(rh.customeramount)) receipts,
--convert(numeric(18,2),sum(rh.Amount*rh.depexrate )) dreceipts,
--convert(numeric(18,2),sum(rh.Amount*rh.exchangerate)) creceipts,
convert(numeric(18,2),sum(rd.amountreceived)) receipts,
convert(numeric(18,2),sum(rd.amountreceived*rh.depexrate )) dreceipts,
convert(numeric(18,2),sum(rd.amountreceived*rh.exchangerate)) creceipts,
-------------------------------------------------------------
--RefNo-4  ---------------------------end---------------------------------------
-- Corrected receipt amount calculation. Old code commented above. (RefNo-1)
--convert(numeric(18,2),sum(rd.AmountReceived)) receipts,
--convert(numeric(18,2),sum(rd.AmountReceived*rh.depexrate)) dreceipts,
--convert(numeric(18,2),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 end -------------------
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,2),sum(Amount)) receipts,
convert(numeric(18,2),sum(Amount * depexrate)) dreceipts,
convert(numeric(18,2),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 end -------------------
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,2),sum(phAmount)) as payments,
convert(numeric(18,2),sum(phAmount* phdepexrate)) as dpayments,
convert(numeric(18,2),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 end -------------------
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,2),sum(lphbillamount)) as localpurchase,
convert(numeric(18,2),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,
convert(numeric(18,2),sum(lphbillamount*lphexchangerate)) as clocalpurchase
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,
0.0 as cPdChequeSales
--RefNo-2 end -------------------
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'
GO
/****** Object:  View [dbo].[vwCustomerSettlementDetails]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
-------------------------------------------------------------------------------------------------------------------------
-- Created on      : 06/07/2007
-- Created by      : Shinu
-- Comments        : For Taking Reference Nos For Customer Settlement in Detail Table
-------------------------------------------------------------------------------------------------------------------------
-- Modified on      :
-- Modified by      :
-- Comments         :
-------------------------------------------------------------------------------------------------------------------------
create VIEW [dbo].[vwCustomerSettlementDetails] AS
-- 1: For Opening Invoice and Service Invoices in HQ
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	AIH.InvoiceNo SettlementNo,''HQ Invoices'' Type
FROM CustomerSettlementDetail CSD
INNER JOIN   AccountsInvoiceHeader AIH ON CSD.AccInvoiceID = AIH.InvoiceID
UNION ALL
-- 2: For HQ Debit Credit Notes
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	DCN.DCNNo,''HQ DCN''
FROM CustomerSettlementDetail CSD
INNER JOIN   DebitCreditNote DCN ON CSD.dcnid = DCN.DCNId
UNION ALL
-- 3: For Shop Accounts Invoice
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LAIH.aiInvoiceNo,''Shop Acc Inv''
FROM CustomerSettlementDetail CSD
INNER JOIN   LOsAccountsInvoiceHeader LAIH ON CSD.shopid = LAIH.aiShopID AND CSD.LosAccInvoiceID = LAIH.aiInvoiceID
UNION ALL
-- 4: For Shop Special Invoice
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LSIP.IhInvoiceNo,''Shop Spl Inv''
FROM CustomerSettlementDetail CSD
INNER JOIN   losSpecialInvoiceHeader LSIP ON CSD.shopid = LSIP.IhShopID AND CSD.LosAccInvoiceID = LSIP.IhInvoiceID
UNION ALL
-- 5: For Shop Credit Invoices
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LIH.ihInvoiceNo,''Shop Inv''
FROM CustomerSettlementDetail CSD
INNER JOIN   LOsInvoiceHeader LIH ON CSD.shopid = LIH.ihShopID AND CSD.losinvoiceid = LIH.ihInvoiceID
UNION ALL
-- 6: For Shop debut credit Notes
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LDCN.losDCNNo,''Shop DCN''
FROM CustomerSettlementDetail CSD
INNER JOIN   losDebitCreditNote LDCN ON CSD.shopid = LDCN.losDCNShopid AND CSD.losdcnid = LDCN.losDCNId
UNION ALL
--7: For Shop Service Invoice Header
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LSIH.serinvNo,''Shop Ser Inv''
FROM CustomerSettlementDetail CSD
INNER JOIN   LosServiceInvHeader LSIH ON CSD.shopid = LSIH.serinvhshopid AND CSD.losserinvoiceid = LSIH.serinvhid
UNION ALL
--8: For Hq Payments
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	PV.phPaymentNo,''HQ Payments''
FROM CustomerSettlementDetail CSD
INNER JOIN   aHQPaymentVoucherHeader PV ON CSD.paymentid = PV.phPaymentID
UNION ALL
--9: For Export
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LEH.rehExportNo,''Export''
FROM CustomerSettlementDetail CSD
INNER JOIN   losExportHeader LEH ON CSD.shopid = LEH.rehShopID AND CSD.losexportid = LEH.rehExportID
UNION ALL
--10: For Apartment Billing
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LABH.abhBillNo,''Apartment''
FROM CustomerSettlementDetail CSD
INNER JOIN   losApartmentBillHeader LABH ON CSD.RoomBillID = LABH.abhBillId AND CSD.shopid = LABH.abhSHopID
UNION ALL
--11: For Utility Billing
SELECT 	CSD.CSID,CSD.CSDetailID,CSD.CompanyID,CSD.ShopId,CSD.InvoiceAmount,CSD.SettlementAmount ,
	LTSBH.tbhBillNo,''Utility''
FROM CustomerSettlementDetail CSD
INNER JOIN   losTenantServiceBillHeader LTSBH ON CSD.UtilityBillID = LTSBH.tbhBillId AND CSD.shopid = LTSBH.tbhShopId'
GO
/****** Object:  View [dbo].[vwCashInflow]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCashInflow]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwCashInflow    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 20/11/2001 9:59:05 AM ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 17/11/2001 9:21:53 PM ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 16/06/2001 15:36:33 ******/
/****** Object:  View dbo.vwCashInflow    Script Date: 09/03/2001 02:32:26 ******/
CREATE view [dbo].[vwCashInflow] as
select companyid, shopid, billdate as transdate, sum(addamount)-sum(dedamount) as totalamount from vwcashtallied group by companyid,shopid,billdate'
GO
/****** Object:  StoredProcedure [dbo].[spEditGodownStock]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spEditGodownStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 18/01/2003 9:45:48 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 03/10/2002 5:06:59 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 14/09/2002 12:48:17 AM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 31/07/2002 2:00:38 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 20/11/2001 9:59:17 AM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 17/11/2001 9:22:32 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 16/06/2001 15:36:39 ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 09/03/2001 02:32:30 ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 12/05/00 1:40:17 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 11/13/00 3:01:57 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 10/17/00 2:19:51 PM ******/
/****** Object:  Stored Procedure dbo.spEditGodownStock    Script Date: 10/7/00 11:07:58 AM ******/
CREATE procedure [dbo].[spEditGodownStock]
(@FromDate smalldatetime,@DespatchId integer,@Itemid integer,@GodownID integer,@ShipmentID integer,@GoodQty numeric,@BadQty numeric)
as
declare
@tmpItemid integer,
@tmpStockDate smalldatetime,
@tmpOpeningGoodStock numeric,
@tmpClosingGoodStock numeric,
@tmpOpeningBadStock numeric,
@tmpClosingBadStock numeric,
@detDespatchID integer,
@detGodownID integer,
@detShipmentID integer,
@detItemID integer,
@detBadQty numeric,
@detGoodQty numeric,
@opGoodStock numeric,
@opBadStock numeric,
@diffGoodStock numeric,
@diffBadStock numeric,
@GoodStockDiff numeric,
@BadStockDiff numeric,
@ClosingGoodStock numeric,
@ClosingBadStock numeric
create table #tmp_DespatchToShopDetail
(ddDespatchid integer null,
ddGodownid integer null,
ddShipmentid integer null,
dditemid integer null,
dditemBadQty numeric null,
dditemGoodQty numeric null)
set nocount on
/* Open a cursor for selecting the records from the MeiDespatchtoShopDetail
table */
/*declare cursor_Despatch scroll cursor fro*/
select @detBadQty = dditembadqty,
@detGoodQty = dditemgoodqty	
from   MeiDespatchtoShopDetail
where  ddDespatchid = @DespatchId and dditemid = @itemid and
ddshipmentid = @shipmentid
/*open cursor_Despatch
fetch next from cursor_Despatch into
@detDespatchID,@detGodownID,@detShipmentID,@detItemID,@detBadQty,@detGoodQty
while @@fetch_status <> -1
begin*/
	declare cursor_Godown scroll cursor for
	select gsitemid,gsstockdate,gsOpeningStock,gsStock,gsOpeningBadStock,
	gsBadStock from MoiGodownStock
	where gsitemid = @Itemid and gsstockdate >= @FromDate
	order by gsitemid,gsShipmentID,gsstockdate
	open cursor_Godown
	fetch next from cursor_Godown into
	@tmpItemid,@tmpStockDate,@tmpOpeningGoodStock,@tmpClosingGoodStock,
	@tmpOpeningBadStock,@tmpClosingBadStock
/*Update (Add) the Closing Good & Bad Stock with the value in the detail table*/
	select @opGoodStock = @tmpOpeningGoodStock + @detGoodQty
	select @opBadStock = @tmpOpeningBadStock + @detBadQty
	update MoiGodownStock set gsstock = @tmpOpeningGoodStock + @detGoodQty,
	gsBadstock = @tmpOpeningBadStock + @detBadQty
	where gsitemid = @tmpItemid and gsstockdate = @tmpStockDate
/*Deleting the particular entry from the DEtail table */
	delete from MeiDespatchtoShopDetail where ddItemid = @tmpItemid
and ddDespatchId = @DespatchId
/*Inserting the new record into the temporary Detail table */
	insert into #tmp_DespatchToShopDetail
	select @DespatchID,@GodownID,@ShipmentID,@ItemID,
	@BadQty,@GoodQty
/*Update(Substract) from the Closing Good & Bad Stock   */
	select @opGoodStock = @opGoodStock - @GoodQty
	select @opBadStock = @opBadStock - @BadQty
	update MoiGodownStock set gsstock = @opGoodStock,
	gsBadstock = @opBadStock
	where gsitemid = @tmpItemid and gsstockdate = @tmpStockDate
/* Go to the next Record */
while @@fetch_status <> -1
begin
	if @@fetch_status <> -2
	begin
		fetch next from cursor_Godown into
		@tmpItemid,@tmpStockDate,@tmpOpeningGoodStock,@tmpClosingGoodStock,
		@tmpOpeningBadStock,@tmpClosingBadStock
		
/* Storing the Stock Difference */
		select @diffGoodStock = @tmpOpeningGoodStock - @tmpClosingGoodStock
		select @diffBadStock = 	@tmpOpeningBadStock -  @tmpClosingBadStock
		select @tmpOpeningGoodStock = @opGoodStock
		select @tmpOpeningBadStock = @opBadStock
		select @GoodStockDiff = @tmpOpeningGoodStock - @diffGoodStock
		select @BadStockDiff = @tmpOpeningBadStock - @diffBadStock
		
		
		if (@GoodStockDiff < 0  or @BadStockDiff < 0 )
		return 0
		select @ClosingGoodStock = @GoodStockDiff
		select @ClosingBadStock = @BadStockDiff
		select @opGoodStock = @ClosingGoodStock
		select @opBadStock = @ClosingBadStock
	end	/* End of IF */
end		/* End of While */
select * into meidespatchtoshopdetail from #tmp_DespatchToShopDetail
return 1
close cursor_Godown
deallocate cursor_Godown' 
END
GO
/****** Object:  View [dbo].[vwItemsinTransaction]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsinTransaction]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwItemsinTransaction    Script Date: 18/01/2003 9:45:42 PM ******/
/****** Object:  View dbo.vwItemsinTransaction    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwItemsinTransaction    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwItemsinTransaction    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwItemsinTransaction    Script Date: 17/11/2001 9:22:02 PM ******/
CREATE view [dbo].[vwItemsinTransaction] as
-- created by hrk for identifing items which are in transaction
select  distinct itemid from
(select  itemid from  vwShopBinCardAudit
union all
select  itemid  from vwgdnBinCard
union all
select  pd.pbdItemID itemid  from LOspPurchaseBillDetail pd, losppurchasebillheader ph
where ph.pbhbillid=pd.pbdbillid and ph.pbhCancelled=0 and ph.pbhbillid<>0
union all
select  cd.cdItemID itemid from loacostingdetail cd, loacostingheader ch where
cd.cdcostingid =ch.chcostingid and chCostingID <> 0 and chCancelled=0
) s'
GO
/****** Object:  View [dbo].[vwDeparmentBinCardAudit]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDeparmentBinCardAudit]'))
EXEC dbo.sp_executesql @statement = N'
--created by jyothish on 06-03-10
--For Muni
--For geting transaction details in company wise Bincardaudit report.
--Without selecting shop or godown of the inventory report Bincardaudit.
Create  VIEW [dbo].[vwDeparmentBinCardAudit] AS
select shopid, itemid, sdate , TransID ,Transno, Transqty, Type, mode,updatetime, Costprice,
DepCostprice,ConCostprice,companybin.DepartmentID
from
(select vws.shopid, itemid, sdate ,TransID ,Transno, Transqty, Type, mode,updatetime, Costprice, DepCostprice,ConCostprice ,s.DepartmentID from vwshopbincardaudit vws , ashops s where s.ShopID=vws.shopid
union
select vwg.godownid, itemid, GDate, Transid, TransNo, TRansqty, Type, mode,updatetime, CostPrice,depcostprice,concostprice,g.DepartmentID from vwgdnbincard vwg, agodown g where vwg.godownid=  g.godownid)companybin'
GO
/****** Object:  View [dbo].[vwCompanyBinCardAudit]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCompanyBinCardAudit]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--created by Abhishek on 06-03-10
--For Muni
--For geting transaction details in company wise Bincardaudit report.
--Without selecting shop or godown of the inventory report Bincardaudit.
CREATE VIEW [dbo].[vwCompanyBinCardAudit] AS
select shopid, itemid, sdate , TransID ,Transno, Transqty,
Type, mode,updatetime, Costprice,
DepCostprice,ConCostprice,DepartmentId
from
(
select vws.shopid, itemid, sdate ,TransID ,Transno, Transqty,
Type, mode,updatetime, Costprice,
DepCostprice,ConCostprice,s.DepartmentID
from vwshopbincardaudit vws,ashops s
where vws.shopid=s.shopid
union
select vwg.godownid, itemid, GDate,Transid,TransNo,TRansqty ,
Type, mode,updatetime, CostPrice,
depcostprice,concostprice,g.DepartmentID
from vwgdnbincard vwg,agodown g
where vwg.godownid=g.godownid
)companybin'
GO
/****** Object:  StoredProcedure [dbo].[spupdatestockproblem]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spupdatestockproblem]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spupdatestockproblem    Script Date: 18/01/2003 9:45:43 PM ******/
--Verified by 	: Hariharan on 04/01/2003
CREATE proc [dbo].[spupdatestockproblem]( @intLocationID as int, @chrLocType as char(1),
@fetchType as char(1))
as
set nocount on
begin
--@intLocationID - shop or godownid
--@chrLocType - ''s'' or ''g''
--@fetchType - ''a'' to fetch all records other wise any character
--to store the bincard stock
create table #bincardstock
(locationid int,
itemdesc varchar(250),
itemid int,
barcode varchar(50),
curstock numeric(18,3))
--to store the actual stock
create table #ActualStock
(locationid int,
itemid int,
systemstock numeric(18,3))
if @chrLocType=''S''
	--if location is shop
	begin
	insert  #bincardstock
	select s.shopid, vw.itemdescription, s.itemid, pk.packingbarcode,
	 (sum(isnull(openingstock,0)) + min(isnull(sbc.quantity,0))) curstock from mosshopstock s
	left outer join
	(select itemid, shopid, sum(Transqty * mode) quantity  from vwshopbincardaudit
	group by itemid, shopid) sbc
	on s.shopid=sbc.shopid and s.itemid=sbc.itemid , vwitemdescription vw, aitempackingdetail pk
	where s.itemid=vw.itemid and s.shopid=@intLocationID and pk.itemid=s.itemid and
	pk.packingtypeid=1 group by
	s.itemid, vw.itemdescription, s.shopid, pk.packingbarcode
	order by vw.itemdescription
	
	insert #ActualStock
	select shopid, itemid, sum(stock) stock from mosshopstock where shopid=@intLocationID
	group by itemid, shopid order by itemid
	
	end
else
	--if location is godown
	begin
	insert  #bincardstock
	select g.gsgodownid, vw.itemdescription, g.gsitemid, pk.packingbarcode, (sum(isnull(gsopeningstock,0)) +
	min(isnull(sbc.quantity,0))) curstock from moigodownstock g
	left outer join
	(select itemid, godownid, sum(Transqty * mode) quantity  from vwgdnbincard
	group by itemid, godownid) sbc
	on g.gsgodownid=sbc.godownid and g.gsitemid=sbc.itemid , vwitemdescription vw,
	aitempackingdetail pk
	where g.gsitemid=vw.itemid and g.gsgodownid=@intLocationID and pk.itemid=g.gsitemid
	and pk.packingtypeid=1 group by
	g.gsitemid,vw.itemdescription, g.gsgodownid , pk.packingbarcode
	order by vw.itemdescription
	
	insert #ActualStock
	select gsgodownid, gsitemid, sum(gsstock) stock from moigodownstock where
	gsgodownid=@intLocationID group by gsitemid, gsgodownid order by gsitemid
	
	end
	--TO FETCH ALL RECORDS GIVE ''a'' other wise any character to give distinct stock items
	if @fetchtype=''a''
	
	select bin.*, ast.systemstock from #bincardstock bin, #actualstock ast where
	bin.locationid=ast.locationid and bin.itemid=ast.itemid
	else		
	--SELECTS THE ITEMS WHICH HAS STOCK PROBLEM
	select bin.*, ast.systemstock from #bincardstock bin, #actualstock ast where
	bin.locationid=ast.locationid and bin.itemid=ast.itemid and
	bin.curstock<>ast.systemstock
	drop table #bincardstock
	drop table #actualstock
set nocount off
end' 
END
GO
/****** Object:  View [dbo].[vwGdnBinCardSummary]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardSummary]'))
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwGdnBinCardSummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 03-08-2010
-- Description :
--    This view was created based on vwGdnBinCard
--    Summary Date filtering was added additionally.
--    Group By clause was removed to improve performance.
--    This view is used to compute item stock in Transactions Summary method.
-- ===============================================
CREATE VIEW [dbo].[vwGdnBinCardSummary] AS
--arrival from hq
select ad.adgodownid Godownid, ad.aditemid ItemId, ah.ahArrivaldate GDate,
NULL TransId, NULL TransNo,
ad.adReceivedQty * pk.quantity * counts TransQty ,
''Shipment Arrival'' as [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,
NULL DepCostPrice, NULL ConCostPrice
from  loiarrivalheader ah, loiarrivaldetail ad,
aitem ai, aPackingTypeCapacityDetail pk, aunit u
where ah.ahcancelled=0 and ah.ahtransfinished=1 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 ai.unitsid = u.unitid
and ah.ahArrivaldate>''20100803''
union all
--Transfer in from shop or godown
select  gal.asdGodownID, gal.asdItemId, ah.ahArrivaldate, NULL,
NULL, gal.asdReceivedGoodQty, ''Transfer In'', 1 mode, NULL, NULL, NULL, NULL
from loiarrivalheader ah, loiArrivalShipmentDetail gal
where ah.aharrivalid = gal.asdArrivalID and
ah.ahlocalgodownid = gal.asdGodownId and ah.ahcancelled = 0 and ah.ahtransfinished = 1
and ah.ahArrivaldate>''20100803''
union all
--recovery add
select sr.srgodownid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.sraddstock), ''Recovery Plus'', 1 mode, NULL, NULL, NULL, NULL
from loistockrecovery sr
where sr.srdate>''20100803''
group by sr.srgodownid, sr.srid, sr.srdate,  sr.sritemid
having isnull(sum(sr.sraddstock),0) >0
union all
--itemsplitting adding
select isdgodownid, isditemid, ishdate, NULL, NULL, isdqty,
''Splitting Add'', 1 as mode, NULL, NULL, NULL, NULL
from LoiItemSplitDetail sd Left Outer Join (Select scfhItemSplitId,
scfhGodownId, scfdItemId, scfdCostprice
From loaItemSplitCostingDetail scfd, loaItemSplitCostingHeader scfh
Where scfhId = scfdId
And scfhCancelled = 0) scf
On sd.isdItemId = scf.scfdItemID
And sd.isdId = scf.scfhItemSplitId
And sd.isdGodownId = scf.scfhGodownid, LoiItemSplitheader sh, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=
sh.ishgodownid and sh.ishcancelled=0 and sd.isdIteMId = i.itemId
and ishdate>''20100803''
union all
--write off
select wd.wdGodownid RGId, wd.wditemid RItemID, wh.whDate RDate,
NULL, NULL, wd.wdWriteoffQty, ''Write Off'', -1 mode, NULL, NULL, NULL, NULL
from loiwriteoffheader wh, loiwriteoffdetail wd
where wh.whid=wd.wdid and wh.whgodownid=wd.wdgodownid and wh.whcancelled=0
and wh.whDate>''20100803''
union all
--Deapatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, NULL, NULL,
dd.dditemgoodqty, ''Despatch To Shop'', -1 mode, NULL, NULL, NULL, NULL
from meidespatchtoshopheader dh, meidespatchtoshopdetail dd
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0
and dhtransfinished = 1 --added for new concept (hari 021019)
and dh.dhDespatchDate>''20100803''
union all
-- special despatch to shop
select dd.ddgodownid, dd.dditemid, dh.dhDespatchDate, NULL, NULL,
dd.dditemgoodqty, ''Special Despatch'', -1 mode, NULL, NULL, NULL, NULL
from meispecialdespatchtoshopheader dh, meispecialdespatchtoshopdetail dd
where dh.dhdespatchid=dd.dddespatchid and dh.dhgodownid=dd.ddgodownid and dh.dhcancelled=0
and dh.dhDespatchDate>''20100803''
union all
--Transferout
select gtdGodownid, gtditemid, gthDespatchDate, NULL, NULL,
gtdItemGoodQty, ''Transfer Out'', -1 mode, NULL, NULL, NULL, NULL
from meigodowntransferheader, meigodowntransferdetail
where gthdespatchid = gtddespatchid
and gthFromGodownid = gtdgodownid
and gthCancelled = 0
and gthtransfinished = 1 --added for new concept (hari 021019)
and gthDespatchDate>''20100803''
union all
--recovery minus
select sr.srgodownid, sr.sritemid, sr.srdate, NULL, NULL,
sum(sr.srdedstock), ''Recovery Minus'' as type, -1 mode, NULL, NULL, NULL, NULL
from loistockrecovery sr
where sr.srdate>''20100803''
group by sr.srgodownid, sr.srid, sr.srdate, sr.sritemid
having isnull(sum(sr.srdedstock),0) >0
union all
--stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock, ''Verification Plus'' as Type, 1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid
and svdVerifiedStock > svdAvailStock
and svhCancelled=0  and left(svhFutureVc, 1) <> ''t''
and svhDate>''20100803''
union all
--stockverification minus
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdAvailStock - svdVerifiedStock, ''Verification Minus'', -1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
and svhCancelled = 0    and left(svhFutureVc, 1) <> ''t''
and svhDate>''20100803''
UNION ALL
--TOTAL stock verification add
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdVerifiedStock-svdAvailStock, ''Verification Plus'', 1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid
and svdVerifiedStock > svdAvailStock
and svhCancelled=0  and left(svhFutureVc, 2) = ''tc''
and svhDate>''20100803''
union all
--ToTAL stockverification minus
select svdGodownid, svdItemid, svhDate, NULL, NULL,
svdAvailStock - svdVerifiedStock, ''Verification Minus'', -1 mode,
NULL, NULL, NULL, NULL
from  loistockverificationheader, loistockverificationdetail
where svhid = svdid and svhgodownid = svdgodownid and svdVerifiedStock < svdAvailStock
and svhCancelled = 0 and left(svhFutureVc, 2) = ''tc'' and svhDate>''20100803''
union all
--itemsplitting minus
select isdgodownid, ishSplititemid, ishdate, NULL, NULL,
isdqty, ''Splitting Ded'', -1 as mode, NULL, NULL, NULL, NULL
from LoiItemSplitDetail sd, LoiItemSplitheader sh
Left Outer Join loaItemSplitCostingHeader scfh
On sh.ishId = scfh.scfhItemSplitId
and sh.ishGodownId = scfh.scfhGodownId, aItem i
where sd.isdid=sh.ishid and sd.isdgodownid=
sh.ishgodownid and sh.ishcancelled=0 and ishSplitItemId =i.ItemId
and ishdate>''20100803''
union all
--Merging minus
select lgdGodownID, lgdItemID, lghDate, NULL, NULL,
sum(lgsdqty), ''Merging Deduct'', -1 as mode, NULL, NULL, NULL, NULL
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid
and md.lgdgodownid = mh.lghgodownid
and lghCancelled = 0 and lghDate>''20100803''
group by lgdGodownID, lgdItemID, lghDate, lghid
Having sum(lgsdqty) <> 0
union all
--Merging Add
select lgdGodownID, lghItemID, lghDate, NULL, NULL,
sum(lgsdqty), ''Merging Add'', 1 as mode, NULL, NULL, NULL, NULL
from loiMergeDetails md, loiMergeHeader mh
where md.lgdid = mh.lghid
and md.lgdgodownid = mh.lghgodownid
and lghCancelled = 0 and lghDate>''20100803''
group by lgdGodownID, lghItemID, lghDate, lghid
Having sum(lgsdqty) <> 0'
GO
/****** Object:  StoredProcedure [dbo].[AdvanceReceiptsNotSettled]    Script Date: 10/06/2012 14:17:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AdvanceReceiptsNotSettled]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created on : 05/05/03
--Created by  : leo
--Modified by  : Hariharan, Hariharan  ,Shinu
--modified Date : 28/08/2003, 28/04/2004,16/06/2007
--Comments : Date passed is checked agaist the receiptdate , Added DepartmentId =0 Condition @sonee
--------------------------------------------------------
--Modified on : 19-03-2010
--Modified By : VINOTHMURUGAN V
--Purpose     : Adding Remarks Column.(h.remarks)
---------------------------------------------------------
CREATE proc [dbo].[AdvanceReceiptsNotSettled] @intcompanyid as int, @intdepartmentid as int,
@intcustomerid as int, @strasondate as varchar(8) as
begin
set nocount on
create table #temp1  (
receiptid  int   null,
receiptno  varchar(100)  null,
receiptdate datetime null,
customerid  int   null,
customername varchar(100) null,
Receiptamt  numeric(18,2)  null,
settledamt numeric(18,2) null,
Remarks   varchar(500) null
)
if @intdepartmentid<>0
Begin
if @intcustomerid = 0
begin
insert into #temp1
select h.receiptid, h.receiptno, h.receiptdate, h.customerid,cm.customername, h.customeramount, 0.0,h.remarks   from receiptvoucherheader h
left outer join receiptvoucherdetails d on
h.companyid = d.companyid and h.receiptid = d.receiptid
left outer join acustomermaster cm on
h.customerid=cm.customerid
left outer join receiptvouchercustomerdetails d1 on
h.companyid = d1.companyid and
h.receiptid = d1.receiptid
where h.companyid =@intcompanyid and h.departmentid = @intdepartmentid and
isnull(h.customerid,0) <> 0 and h.cancelled =0 and d1.receiptid is null
and h.ReceiptDate <= @strasondate
group by h.receiptid, h.receiptno, h.receiptdate,
h.customerid,cm.customername, h.customeramount,h.remarks  having
count(d.receiptid) =0
union all
select h.receiptid, h.receiptno, h.receiptdate, d.customerid,cm.customername,d.CustomerAmount, 0.0,h.remarks  from receiptvoucherheader h ,
receiptvouchercustomerdetails d
left outer join acustomermaster cm on
d.customerid=cm.customerid
where h.companyid = d.companyid and
h.receiptid = d.receiptid and  h.companyid=@intcompanyid
and h.departmentid =@intdepartmentid and h.cancelled =0
and h.ReceiptDate <= @strasondate
end
else
begin
insert into #temp1
select h.receiptid, h.receiptno, h.receiptdate, h.customerid,cm.customername, h.customeramount, 0.0,h.remarks  from receiptvoucherheader h
left outer join receiptvoucherdetails d on
h.companyid = d.companyid and h.receiptid = d.receiptid
left outer join acustomermaster cm on
h.customerid=cm.customerid
left outer join receiptvouchercustomerdetails d1 on
h.companyid = d1.companyid and
h.receiptid = d1.receiptid
where h.companyid =@intcompanyid and h.departmentid = @intdepartmentid and
isnull(h.customerid,0) <> 0 and h.cancelled =0 and d1.receiptid is null
and h.ReceiptDate <= @strasondate and h.customerid = @intcustomerid
group by h.receiptid, h.receiptno, h.receiptdate,
h.customerid,cm.customername, h.customeramount,h.remarks  having
count(d.receiptid) =0
union all
select h.receiptid, h.receiptno, h.receiptdate, d.customerid,cm.customername,d.CustomerAmount, 0.0,h.remarks  from receiptvoucherheader h ,
receiptvouchercustomerdetails d
left outer join acustomermaster cm on
d.customerid=cm.customerid
where h.companyid = d.companyid and
h.receiptid = d.receiptid and  h.companyid=@intcompanyid
and h.departmentid =@intdepartmentid and h.cancelled =0
and h.ReceiptDate <= @strasondate and h.customerid = @intcustomerid
end
update #temp1 set settledamt = settled from (
select csh.receiptid rid, csh.customerid cid, cm.customername,
sum(isnull(SettlementAmount,0.0)) settled from
customersettlementDetail csd,customersettlementheader csh
left outer join acustomermaster cm on
csh.customerid=cm.customerid
where csh.companyid = csd.companyid and csh.csid = csd.csid
and csh.cancelled =0 and csh.companyid = @intcompanyid and csh.departmentid =
@intdepartmentid and isnull(csh.receiptid,0) <> 0 --and csh.csdate <= @strasondate
group by csh.companyid, csh.receiptid, csh.customerid,cm.customername ) a where
#temp1.receiptid = a.rid and #temp1.customerid = a.cid
End
else
Begin
if @intcustomerid = 0
begin
insert into #temp1
select h.receiptid, h.receiptno, h.receiptdate, h.customerid,cm.customername, h.customeramount, 0.0,h.remarks  from receiptvoucherheader h
left outer join receiptvoucherdetails d on
h.companyid = d.companyid and h.receiptid = d.receiptid
left outer join acustomermaster cm on
h.customerid=cm.customerid
left outer join receiptvouchercustomerdetails d1 on
h.companyid = d1.companyid and
h.receiptid = d1.receiptid
where h.companyid =@intcompanyid  and
isnull(h.customerid,0) <> 0 and h.cancelled =0 and d1.receiptid is null
and h.ReceiptDate <= @strasondate
group by h.receiptid, h.receiptno, h.receiptdate,
h.customerid,cm.customername, h.customeramount,h.remarks  having
count(d.receiptid) =0
union all
select h.receiptid, h.receiptno, h.receiptdate, d.customerid,cm.customername,d.CustomerAmount, 0.0,h.remarks  from receiptvoucherheader h ,
receiptvouchercustomerdetails d
left outer join acustomermaster cm on
d.customerid=cm.customerid
where h.companyid = d.companyid and
h.receiptid = d.receiptid and  h.companyid=@intcompanyid
and h.cancelled =0  and h.ReceiptDate <= @strasondate
end
else
begin
insert into #temp1
select h.receiptid, h.receiptno, h.receiptdate, h.customerid,cm.customername, h.customeramount, 0.0,h.remarks  from receiptvoucherheader h
left outer join receiptvoucherdetails d on
h.companyid = d.companyid and h.receiptid = d.receiptid
left outer join acustomermaster cm on
h.customerid=cm.customerid
left outer join receiptvouchercustomerdetails d1 on
h.companyid = d1.companyid and
h.receiptid = d1.receiptid
where h.companyid =@intcompanyid and
isnull(h.customerid,0) <> 0 and h.cancelled =0 and d1.receiptid is null
and h.ReceiptDate <= @strasondate and h.customerid = @intcustomerid
group by h.receiptid, h.receiptno, h.receiptdate,
h.customerid,cm.customername, h.customeramount,h.remarks  having
count(d.receiptid) =0
union all
select h.receiptid, h.receiptno, h.receiptdate, d.customerid,cm.customername,d.CustomerAmount, 0.0,h.remarks  from receiptvoucherheader h ,
receiptvouchercustomerdetails d
left outer join acustomermaster cm on
d.customerid=cm.customerid
where h.companyid = d.companyid and
h.receiptid = d.receiptid and  h.companyid=@intcompanyid
and h.cancelled =0
and h.ReceiptDate <= @strasondate and h.customerid = @intcustomerid
end
update #temp1 set settledamt = settled from (
select csh.receiptid rid, csh.customerid cid, cm.customername,
sum(isnull(SettlementAmount,0.0)) settled from
customersettlementDetail csd,customersettlementheader csh
left outer join acustomermaster cm on
csh.customerid=cm.customerid
where csh.companyid = csd.companyid and csh.csid = csd.csid
and csh.cancelled =0 and csh.companyid = @intcompanyid
and isnull(csh.receiptid,0) <> 0 --and csh.csdate <= @strasondate
group by csh.companyid, csh.receiptid, csh.customerid,cm.customername ) a where
#temp1.receiptid = a.rid and #temp1.customerid = a.cid
END
select * from #temp1 where Receiptamt <> settledamt   order by receiptid
drop table #temp1
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spShipmentWiseItemFlow]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spShipmentWiseItemFlow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spShipmentWiseItemFlow ''20100101'',''20100920'',1
--select * from vwShipmentwiseitem where pbdItemID=1499
--select * from vwSalesAnalysisByItem where posdItemId=1499
--sp_helptext spShipmentWiseItemFlow
--exec spShipmentWiseItemFlow ''20090101'',''20080301'',2
---Created By               : Prasanth joseph
---Created On               : 27-12-2007
---Created For              : To get Shipment wise item Sale
---Modified By              : Nidheesh
---Modified By              : 06-10-09
---comments      : added the calculation for getting sold quantity from OP Quantity
---       :in the else part of the ''@intBalQty'' checking condition
---Modified By              : Nidheesh
---Modified By              : 15-08-09
---comments      : added @ttalsale in the else part
---Modified By              : Sreejith G A
---Modified By              : 20100921
---comments      : Added SalesValue and CostValue colum to the SP.
--				   Added the variables @SalesValue and @CostValue to the #tempData
--				   Added a piece of code which works independetly to calculate the sales and cost value.
--				   this part of code makes use of the PBqty from the cursor.
--				   created a temp table #tempSales for sales details
--				   uses the @PBqty from the cursor to calculate the Sales and Cost Value using a While loop.
CREATE  proc [dbo].[spShipmentWiseItemFlow]
@strfromdate as varchar(200),
@strTodate as varchar(200),
@DepartmentID as int
as
set nocount on
create table #tempData(
PBID  int,
pBNO nvarchar(200),
ShipmentNo nvarchar(200),
BillDate  datetime,
Vendorname  varchar(100),
ItemCode varchar(50),
Itemdescription  varchar(300),
itemid int,
PBQty numeric(18),
DeldQty numeric(18),
SaleBal numeric(20),
OPQTY numeric(20),
OPSalesfromOP numeric(20),
SalesValue numeric(18,2),  ----Sreejith G A
CostValue numeric(18,2))       ----Sreejith G A
---Sreejith G A Start
	create table #tempSales
	(slno int identity, itemid int,
	qty numeric(18,2),
	saledate  datetime,
	dsales numeric(18,2),
	csales numeric(18,2),
	dCost numeric(18,2),
	cCost numeric(18,2),
	checked bit)
	
	declare @intQty as numeric(18,2)
	declare @BalQty as numeric(18,2)
	declare @BalPBQty as numeric(18,2)
	declare @minDate as datetime
	declare @minSlno as int
---Sreejith G A End
declare @strSql as nvarchar(4000),
@PBdate as datetime,
@vendorId as numeric,
@PBQty as numeric,
@PBID as numeric,
@intItemID as int,
@PrBalQty as numeric ,
@intvendor as int  ,
@TotSale as numeric,
@SaleBalQty as numeric,
@DelQty as numeric,
@intBalQty as numeric ,
@openingStock as numeric,
@openingpurchase as numeric,
@openingSale as numeric,
@OPQty as numeric,
@OPSales as numeric ,
@tempOpeningBalnce as numeric ,
		@SalesValue numeric(18,2) ,         ----Sreejith G A
		@CostValue numeric(18,2)            ----Sreejith G A
begin
	 --Sree Start
	 insert into #tempSales
	 select posdItemId,Quantity,poshBillDate,dsalesvalue,csalesvalue,dCostOfSales,cCostOfSales ,0  from vwSalesAnalysisByItem  --- where posdItemId=1499
	 order by posdItemId,poshBillDate
	--Sree End
-------F1
declare opcurt cursor for
select pbhBillID,convert(datetime,pbhBillDate),pbhVendorID,pbdItemId,Qty
from vwShipmentwiseitem where pbhBilldate >=@strfromdate and pbhBilldate <=@strTodate and pbhDepartmentID=@DepartmentID --and pbdItemId =1499
order by pbdItemId,pbhBilldate asc
open opcurt
fetch next from opcurt into @PBID,@PBdate,@vendorId,@intItemID,@PBQty
while @@fetch_status =0
begin
set @intBalQty=-1
		  set @SalesValue=0.00													--Sree Start
		  set @CostValue=0.00
		  set @minDate=null
		  set @minSlno=0
		  set @intQty=0.00
		  set @BalQty=0.00
		  set @BalPBQty=0.00													 --Sree End
select @intBalQty=BalQty from TempItemSaleBal where itemid=@intItemID
if @intBalQty=-1    --------item Is not in tempItemSale
begin
	   set @DelQty=0
	   set @TotSale=0
	   set @PrBalQty=0
	   set @OPQty=0
	   set @openingStock=0
	   set @openingStock=0
	   set @openingpurchase=0
	   set @openingSale=0
	   set @OPSales=0
select @openingStock=sum(openingStock) from MOsShopStock  where itemid= @intItemID
set @openingpurchase=0
/*
select  @openingpurchase= (select case when  sum(d.pbdItemQuantity) IS NULL then 0 else sum(d.pbdItemQuantity) end as SumQty  from lospPurchasebillHeader h inner join
losppurchasebillDetail d on h.pbhBillId=d.pbdBillID where h.pbhBillDate <@PBdate and d.pbdItemID=@intItemID)
set @openingSale=0
select @openingSale=sum(Quantity)from vwSalesAnalysisByItem  where poshBillDate < @PBdate and posdItemid=@intItemID group by posdItemid
*/
select  @openingpurchase=isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwshopbincardaudit where shopid in (select shopid from ashops where departmentid=@DepartmentID) and itemid=@intItemID
and sdate < @PBdate
select  @openingpurchase=@openingpurchase+isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwgdnbincard where godownid in (select GodownID from agodown where departmentid=@DepartmentID) and itemid=@intItemID
and GDate < @PBdate
set @PrBalQty=@openingStock+@openingpurchase     -----@openingSale
if @PrBalQty<-1
begin
set @PrBalQty=0
end
set @OPQty=@PrBalQty
-- select @PrBalQty=
--(select openingStock from MOsShopStock  where itemid=@intItemID +
--(select case when  sum(d.pbdItemQuantity) IS NULL then 0 else sum(d.pbdItemQuantity) end as SumQty  from lospPurchasebillHeader h inner join
--losppurchasebillDetail d on h.pbhBillId=d.pbdBillID where h.pbhBillDate <@PBdate and d.pbdItemID=@intItemID))-
--(select sum(Quantity)from vwSalesAnalysisByItem  where poshBillDate < @PBdate and posdItemid=@intItemID group by posdItemid )
if @PrBalQty>0
begin                                                            -----------F5
set @TotSale=0
select @TotSale= sum(Quantity) from vwSalesAnalysisByItem
where poshBillDate >= @PBdate and posdItemid=@intItemID group by posdItemid
if @PrBalQty>@totSale
begin
set @OPSales=@totSale
set @totSale=0
end
else
					begin
set @totSale=@totSale- @PrBalQty
set @OPSales=@OPQty
end
end                              ------------/F5
else
begin                                                          -------------F9
set @PrBalQty=0
select @TotSale= sum(Quantity)from vwSalesAnalysisByItem
where poshBillDate >= @PBdate and posdItemid=@intItemID group by posdItemid
set @OPSales=0
end        ------------/F9
if @totSale<0 or @totSale is null
begin                                                  -------------F6
set @SaleBalQty=0
set @DelQty=0
end                                                     ------------/F6
else
begin                                                 -----------F7
set @SaleBalQty= @TotSale-@PBQty
if @TotSale>@PBQty
begin
						  set @DelQty=@PBQty
end
else
begin
set @DelQty=@TotSale
set @SaleBalQty=0
end
end                                                       ----------/F7
-- select   @OPQty first, @OPSales   fisttt,@PBID
insert into TempItemSaleBal values(@intItemID,@SaleBalQty)
end                                                                    ----------/F3
else    -------Already item there in TempItemSale
begin                                               ------------F4
set @OPQty =0
set @openingStock=0
select @openingStock=sum(openingStock) from MOsShopStock  where itemid=@intItemID
--select @openingStock
set @openingpurchase=0
--select  @openingSale= (select case when  sum(d.pbdItemQuantity) IS NULL then 0 else sum(d.pbdItemQuantity) end as SumQty  from lospPurchasebillHeader h inner join
--losppurchasebillDetail d on h.pbhBillId=d.pbdBillID where h.pbhBillDate <@PBdate and d.pbdItemID=@intItemID)
select  @openingpurchase=isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwshopbincardaudit where shopid in (select shopid from ashops where departmentid=@DepartmentID) and itemid=@intItemID
and sdate < @PBdate
select  @openingpurchase=@openingpurchase+isnull(sum(isnull(Transqty*mode,0.0)), 0.0)
from vwgdnbincard where godownid in (select GodownID from agodown where departmentid=@DepartmentID) and itemid=@intItemID
and GDate < @PBdate
--set @tempOpeningBalnce=@tempOpeningBalnce+@openingpurchase
set @openingSale=0
				--select @openingSale=sum(Quantity)from vwSalesAnalysisByItem  where poshBillDate < @PBdate and posdItemid=@intItemID group by posdItemid
set @OPQty=@openingStock+@openingpurchase  --@openingSale
				  ---added by nidheesh on 15/08/2010--start-------
set @TotSale=0
select @TotSale= sum(Quantity)from vwSalesAnalysisByItem
where poshBillDate >= @PBdate and posdItemid=@intItemID group by posdItemid
				  ---added by nidheesh on 15/08/2010--end-------
if @intBalQty>@PBQty
begin -----------F8
set @SaleBalQty=@intBalQty-@PBQty
set @DelQty=@PBQty
end                                                                -----------/F8
else
begin                                                             ------------F9
set @DelQty=@intBalQty
set @SaleBalQty=0
end                                                                -----------/F9
		   ---------------added by nidheesh on 06-10-09--------
			if   @intBalQty >@OPQty
			begin
			 set @intBalQty=@intBalQty-@OPQty
			 set @OPSales=@OPQty
			end
			else
			begin
			---added by nidheesh on 15/08/2010--start---
			 --set @OPSales=@intBalQty
			 if @OPQty>@TotSale
			 begin
			  set @OPSales=@TotSale
			 end
			 else
			 begin
			  set @OPSales=@OPQty
			 end
			 set @intBalQty=0									
			---added by nidheesh on 15/08/2010--end---
			end
		   ------------------------------------------------------
update TempItemSaleBal set BalQty=@SaleBalQty where itemid=@intItemID
end
		 ---Sreejith G A Start    (The below part of code works independently to calculate the sales and cost value of the item against its PB qty)
		 set @BalPBQty=  @PBQty    --Assigns PB qty to an another varibale for recursive calc
		 while (select count(*) from #tempSales where  itemid=@intItemID and checked=0)>0
		 begin
	
		 select @minSlno=min(slno) from #tempSales where  itemid=@intItemID and checked=0 --and saledate=@minDate
		 select @intQty= isnull(qty,0) from #tempSales where  slno=@minSlno and checked=0 and itemid=@intItemID   --and saledate=@minDate
		 if  @intQty = 0
		 begin
		  break
		 end
		if @BalPBQty >= @intQty --or @BalPBQty>@intQty
		  begin
			  select @SalesValue=@SalesValue + (case when @DepartmentID <> 0 then sum(dsales)  else sum(csales) end)
			  from #tempSales
			  where  slno=@minSlno and checked=0 and itemid= @intItemID   --and saledate =@minDate
			
			  select @CostValue=@CostValue+(case when @DepartmentID <> 0 then sum(dcost)  else sum(ccost) end)
			  from #tempSales
			  where  slno=@minSlno and checked=0 and itemid= @intItemID    --and saledate =@minDate
		  end
		else
		 begin
			  select @SalesValue=@SalesValue+(case when @DepartmentID <> 0 then (sum(dsales)/@intQty)*@BalPBQty  else (sum(csales)/@intQty)*@BalPBQty  end)
			  from #tempSales
			  where  slno=@minSlno and checked=0 and itemid= @intItemID  --and saledate =@minDate
			
			  select @CostValue=@CostValue+(case when @DepartmentID <> 0 then (sum(dcost)/@intQty)*@BalPBQty  else (sum(ccost)/@intQty)*@BalPBQty  end)
			  from #tempSales
			  where  slno=@minSlno and checked=0 and itemid= @intItemID    --and saledate =@minDate
		 end
		 if @BalPBQty>@intQty
		 begin
		  set @BalPBQty=@BalPBQty-@intQty
		  update #tempSales set checked=1 where itemid=@intItemID  and checked=0 and slno=@minSlno     --and  saledate=@minDate
		 end
		 else if @BalPBQty=@intQty
		 begin
		  update #tempSales set checked=1 where itemid=@intItemID  and checked=0 and slno=@minSlno     --and  saledate=@minDate
		  break
		 end
		 else if @BalPBQty<@intQty
		 begin
		  set @BalQty=@intQty - @BalPBQty				 --@BalQty is used to update the temp table after taking Bill qty from sales if bill qty is lesser
		  update #tempSales set qty=@BalQty where itemid=@intItemID  and checked=0 and slno=@minSlno     --and  saledate=@minDate
		  break
		 end		
		 end
		  ---Sreejith G A End   (The above part of code works independently to calculate the sales and cost value of the item against its PB qty)
		
insert into #tempData select pbhBillID,pbhBillNo,pbhVendorBillNo,
pbhBIllDate,vendorname,code,Itemdescription,@intItemID,@PBQty,@DelQty,@SaleBalQty,@OPQty,@OPSales,@SalesValue,@CostValue from
vwitemdescription vw,LOspPurchaseBillHeader h inner join avendormaster v
on h.pbhVendorId=v.vendorid where vw.itemid=@intItemID and pbhBillID=@PBID
		  set @intItemID=''''
		  set @PBdate=''''
		  set @SalesValue=0.00																--Sree
		  set @CostValue=0.00															    --Sree
fetch next from opcurt into @PBID,@PBdate,@vendorId,@intItemID,@PBQty
end                                                                         ----------/F2
close opcurt
deallocate opcurt
end      ---------/F1
delete from TempItemSaleBal
delete from #tempSales
set @strsql=N''Select PBID,pBNO,ShipmentNo,BillDate,Vendorname,ItemCode,Itemdescription,itemid,PBQty ,DeldQty,SaleBal,isnull(OPQTY,0)OPQTY,OPSalesfromOP,isnull(SalesValue,0) SalesValue ,isnull(CostValue,0) CostValue from #tempData''
exec sp_executesql @strsql
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPurchaseAndStock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPurchaseAndStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spPurchaseAndStock ''20100101'',''20100115''
--exec spPurchaseAndStock ''20110101'',''20110115''
--Created By   : Prasanth
--Created for  : To get Purchase History with Current Stock on Purchased date
--Created on   : 29-11-2008
--Altered By   : Aadyakumar.D.V
--Altered for  : To solve string or binary data would be trancated
--Alterrd work : Just increse the data type length,as varchar(50) to varchar(150)
--Altered on   : 22-03-2011
-------------------------------------------------------------
CREATE procedure [dbo].[spPurchaseAndStock]
--@VendorID as int,
--@CategoryID as int,
--@Brandid as int,
@dtfromdate as varchar(200),
@dttodate as varchar(200)
as
set nocount on
declare
@ItemStock as numeric(18,2),
@ItemID as int,
@BillID as int,
@BillDate as datetime,
@strSql as nvarchar(4000)
CREATE table #StockDetails(
BillID numeric,
BillNo varchar(100),
BillDate datetime,
VendorID numeric,
ItemID numeric,
itemcode varchar(100) ,
ItemDescription varchar(150),
ItemCategoryID numeric,
CategoryNameDescription Varchar(150),
BrandID numeric,
BrandName Varchar(150),
PackingTypeID numeric,
ItemQuantity  numeric(18,2),
ItemCostedPrice  numeric(18,2),
StockValue  numeric(18,2),
asonStock  numeric(18,2),
VendorName varchar(150)
)
begin
declare opcurt cursor for
select pbdItemID,pbhBillDate,pbhBillID from losppurchasebillheader inner join losppurchasebilldetail
on pbhBillID=pbdBillID and pbhCancelled=0
and pbhBillDate >= @dtfromdate and pbhBillDate <=@dttodate
open opcurt
fetch next from opcurt into @ItemID,@BillDate,@BillID
while @@fetch_status =0
begin
select @ItemStock= sum(stock)
from (
select  itemid,stock,sdate from (
select   itemid, isnull(openingstock,0) stock,''1900/01/01'' sdate from
mosshopstock
union all
select itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) stock,sdate from
vwshopbincardaudit group by itemid,sdate
union all
select   gsitemid, isnull(gsopeningstock,0) gsstock,''1900/01/01'' sdate from moigodownstock
union all
select itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) stock,GDate sdate  from
vwgdnbincard group by itemid ,GDate) TotalStock  where itemid= @ItemID and sdate < @BillDate
) Stock
insert  into  #StockDetails
select pbhBillID,pbhBillNo,pbhBillDate,pbhVendorID,pbdItemID,a.ItemCode,
a.ItemDescription,Cat.ItemCategoryID,cat.CategoryNameDescription,isnull(B.BrandID,0),
isnull(B.BrandName,''''),pbdPackingTypeID,
pbdItemQuantity,pbdItemCostedPrice,pbdItemCostedPrice*pbdItemQuantity StockValue,
isnull(@ItemStock,0),
v.Vendorname
from losppurchasebillheader inner join losppurchasebilldetail
on pbhBillID=pbdBillID
left outer join avendormaster v on pbhVendorID=v.vendorid
left outer join (aitem a
left outer join aItemCategory Cat on a.itemCategoryID=cat.ItemCategoryID
left outer join aBrandmaster B on a.Brand=B.brandname)
on pbdItemID=itemid
where pbhBillID=@BillID and pbdItemID=@ItemID
fetch next from opcurt into @ItemID,@BillDate,@BillID
end
close opcurt
deallocate opcurt
end
-- set @strsql=N''select billNo,Billdate from #StockDetails order by BillID''
--print @strsql
--exec sp_executesql @strsql
select * from #StockDetails order by BillID
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spPurchaseandSalesItemwise]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPurchaseandSalesItemwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spPurchaseandSalesItemwise ''20090101'',''20091212'',4,''9017,9019,916,917''
--CRETAED BY : NIDHEESH P V
--CREATED NO : 22/12/09
--COMMENTS :TO GET PURCHASE AND SALES DETAILS OF ITEMS
CREATE proc [dbo].[spPurchaseandSalesItemwise]
@strfromdate as varchar(200),
@strTodate as varchar(200),
@DepartmentID as int
--@ItemId  as varchar (500)
as
set nocount on
declare
@OPstock as numeric,
@PBQty as numeric,
@SoldQty as numeric,
@BalanceQty as numeric
begin
if @DepartmentID>0     ---------DEPARTMENTWISE----------------------
begin
select * into temp from (
select ItemId,sum(stock)Qty,''OS''status from  ----selects OPQty(openingstock+InquiryStock)
(
---to find shop stock--
select  shopid, itemid, sum(openingstock) stock  from mosshopstock
where shopid IN(select shopid from ashops where departmentid=@DepartmentID)
--and itemid IN (select * from fnsplit(@ItemId,'',''))
group by shopid, itemid
union all
select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate<=@strfromdate
and shopid IN(select shopid from ashops where departmentid=@DepartmentID)
group by shopid,itemid
union all
---to find godown stock-----
select  gsgodownid, gsitemid, sum(gsopeningstock) stock from moigodownstock
where gsGodownID IN(select GodownID from aGodown where departmentid=@DepartmentID)
--and gsitemid IN (select * from fnsplit(@ItemId,'',''))
group by gsgodownid, gsitemid
union all
select godownid, itemid, convert(numeric(18,3), sum(transqty * mode)) stock from vwgdnbincard
where GDate<=@strfromdate
and godownid IN(select GodownID from aGodown where departmentid=@DepartmentID)
--and itemid IN (select * from fnsplit(@ItemId,'',''))
group by godownid, itemid)tb
group by ItemId
union all
-----selects Purchased Qty
select pbdItemID,sum(pbdPOQuantity),''PQ''status from vwShipmentwiseitem where pbhBilldate >=@strfromdate and pbhBilldate <=@strTodate
and pbhDepartmentID=@DepartmentID
--and pbdItemID IN (select * from fnsplit(@ItemId,'',''))
group by  pbdItemID
union all
---selects Sold Qty
select posdItemid,sum(Quantity),''SQ''status from vwSalesAnalysisByItem where poshBillDate >= @strfromdate
and poshBillDate <= @strTodate and poshShopId in
(select shopid from ashops where departmentid=@DepartmentID)
--and posdItemid IN (select * from fnsplit(@ItemId,'',''))
group by posdItemid
union all
------------stock verified quantity in between fromdate and todate----------
------------to include it in the ''Blalance Quantity''-------------------------
select itemid, sum(stock)Qty,''SVQ''status from
(select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate>=@strfromdate and sdate<=@strTodate
and shopid IN(select shopid from ashops where departmentid=@DepartmentID)
and type =''Verification Plus''
group by shopid,itemid
union all
select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate>=@strfromdate and sdate<=@strTodate
and shopid IN(select shopid from ashops where departmentid=@DepartmentID)
and type =''Verification Minus''
group by shopid,itemid)sv
group by itemid
------------------------------------------------------------------------------
)t
end
else	-----COMPANYWISE--------------------
begin
select * into temp from (
select ItemId,sum(stock)Qty,''OS''status from  ----selects OPQty(openingstock+InquiryStock)
(
---to find shop stock--
select  shopid, itemid, sum(openingstock) stock  from mosshopstock
--and itemid IN (select * from fnsplit(@ItemId,'',''))
group by shopid, itemid
union all
select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate<=@strfromdate
group by shopid,itemid
union all
---to find godown stock-----
select  gsgodownid, gsitemid, sum(gsopeningstock) stock from moigodownstock
--and gsitemid IN (select * from fnsplit(@ItemId,'',''))
group by gsgodownid, gsitemid
union all
select godownid, itemid, convert(numeric(18,3), sum(transqty * mode)) stock from vwgdnbincard
where GDate<=@strfromdate
--and itemid IN (select * from fnsplit(@ItemId,'',''))
group by godownid, itemid)tb
group by ItemId
union all
-----selects Purchased Qty
select pbdItemID,sum(pbdPOQuantity),''PQ''status from vwShipmentwiseitem where pbhBilldate >=@strfromdate and pbhBilldate <=@strTodate
--and pbdItemID IN (select * from fnsplit(@ItemId,'',''))
group by  pbdItemID
union all
---selects Sold Qty
select posdItemid,sum(Quantity),''SQ''status from vwSalesAnalysisByItem where poshBillDate >= @strfromdate
and poshBillDate <= @strTodate
--and posdItemid IN (select * from fnsplit(@ItemId,'',''))
group by posdItemid
union all
--------stock verified quantity in between fromdate and todate----------
--------to include it in the ''Blalance Quantity''-------------------------
select itemid, sum(stock)Qty,''SVQ''status from
(select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate>=@strfromdate and sdate<=@strTodate
and type =''Verification Plus''
group by shopid,itemid
union all
select shopid,itemid, convert(numeric(18,3), sum(transqty * mode)) stock from
vwshopbincardaudit where sdate>=@strfromdate and sdate<=@strTodate
and type =''Verification Minus''
group by shopid,itemid)sv
group by itemid
--------------------------------------------------------------------
)t
end
select vw.itemid,vw.ItemCode,vw.ItemDescription,vw.ItemCategoryID,sum(OpStock)OpeningStock,sum(PQty)PurchasedQty,
	sum(SQty)SoldQty,sum(OpStock+PQty+SVQty-SQty)BalanceQty from
(select temp.itemid,a.ItemCode,a.ItemDescription,a.ItemCategoryID,
case when status=''OS'' then sum(isnull(Qty,0)) else 0 end OpStock,
case when status=''PQ'' then sum(isnull(Qty,0)) else 0 end PQty ,
case when status=''SQ'' then sum(isnull(Qty,0)) else 0 end SQty,
case when status=''SVQ'' then sum(isnull(Qty,0)) else 0 end SVQty from temp
inner join aitem a on a.itemid=temp.itemid   where a.active=1  and  temp.itemid=6575
group by temp.itemid,temp.status,a.ItemDescription,a.ItemCategoryID,a.ItemCode)vw group by vw.itemid,vw.ItemDescription,vw.ItemCategoryID,vw.ItemCode
order by vw.ItemDescription
drop table temp
end
set nocount off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningCompanyStockOnDate]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningCompanyStockOnDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---Created By : Yogesh Joe
--Created On : 19-06-2010
--Purpose  : To get company-wise/department-wise stock of an item up to a particular date.
--spOpeningCompanyStockOnDate 5098,''''20100522'''',0,1
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spOpeningCompanyStockOnDate] (
@intItemId AS INT,
@fromdate AS VARCHAR(10),
@intdepartmentid AS INT =0,
@intcompanyid AS INT=1 ,
@outputopenstock AS NUMERIC(18,3)=0 OUTPUT)
AS
DECLARE
@Curstock AS NUMERIC(18,3),
@openingstock AS NUMERIC(18,3),
@openingShopStock AS NUMERIC(18,3),
@openingGodownStock AS NUMERIC(18,3),
@transqty AS NUMERIC(18,3),
@ShopTransqty AS NUMERIC(18,3),
@GodownTransqty AS NUMERIC(18,3),
@dtFromDate AS DATETIME,
@transcostprice AS NUMERIC(18,2),
@ShopTransCostPrice AS NUMERIC(18,2),
@GodownTransCostPrice AS NUMERIC(18,2),
@costprice AS NUMERIC(18,2),
@Itemctr AS NUMERIC(16,2),
@opencostprice AS NUMERIC(18,2),
@ToCurr AS integer,
@invCurrid AS integer,
@exrate AS NUMERIC(18,2)
SET NOCOUNT ON
BEGIN
SET @Curstock = 0.0
SET @openingstock = 0.0
SET @transqty = 0.0
SET @transcostprice =0.0
SET @costprice =0.0
SET @Itemctr =0.0
SET @opencostprice =0.00
SET @dtFromDate = CONVERT(DATETIME,@fromdate,101)
--------------------------------
if @intdepartmentid=0
BEGIN
SELECT @openingGodownStock = ISNULL(SUM(ISNULL(gsopeningstock,0.0)),0) FROM moigodownstock
WHERE  gsitemid=@intItemid
SELECT @openingShopStock = ISNULL(SUM(ISNULL(openingstock,0.0)),0) FROM mosshopstock
WHERE  itemid=@intItemid
END
ELSE
BEGIN
SELECT @openingGodownStock = ISNULL(SUM(ISNULL(gsopeningstock,0.0)),0) FROM moigodownstock gs
INNER JOIN aGodown g ON gs.gsGodownID=g.GodownID
WHERE  gsitemid=@intItemid AND g.DepartmentId=@intdepartmentid
SELECT @openingShopStock = ISNULL(SUM(ISNULL(openingstock,0.0)),0) FROM mosshopstock ss
INNER JOIN aShops s ON ss.ShopID=s.ShopID
where  itemid=@intItemid AND s.DepartmentID=@intdepartmentid
END
set @openingstock=@openingGodownStock+@openingShopStock
-------------------------------
SELECT @invCurrid=b.currencyid FROM apackagesettings a,acurrencymaster b,
aaccountmaster c WHERE accountid=inventoryid AND a.companyid=b.companyid AND
c.CurrencyID=b.currencyid
IF @intdepartmentid =0
BEGIN --Getting Company Curr
SELECT @Tocurr= a.currencyid FROM acurrencymaster a,
acompanymaster b WHERE a.companyid=b.companyid  AND
a.CurrencyID=b.currencyid
END
ELSE
BEGIN ----Getting dep Curr
SELECT  @Tocurr= a.currencyid FROM acurrencymaster a,
adepartmentmaster b WHERE a.companyid=b.companyid  AND
a.CurrencyID=b.depcurrencyid AND departmentid=@intdepartmentid
END
EXEC spGetExchangeRate @intcompanyid,@invCurrid,@Tocurr, @ExRate OUTPUT
SELECT @itemctr=COUNT(cditemid),@opencostprice=SUM(cdNewItemCostPrice*@ExRate) FROM loacostingheader,
loacostingdetail WHERE chcostingid=cdcostingid AND chcancelled=0 AND cdItemID=@intitemid
AND chcostingid=0
IF @itemctr=0
BEGIN
SELECT TOP 1 @opencostprice=cdOldItemCostPrice*@ExRate FROM loacostingheader,loacostingdetail
WHERE chcostingid=cdcostingid AND chcancelled=0 AND
cdItemID=@intitemid AND chcostingid<>0 ORDER BY chCostingDate ASC
END
-----------------------------------------------------
IF @intdepartmentid =0
BEGIN
SELECT  @GodownTransCostPrice=ISNULL(SUM(concostprice * ISNULL(Transqty*mode,0.0)),0.00),
@GodownTransqty = ISNULL(SUM(TRansqty*mode),0.0)
FROM  vwgdnbincard WHERE gdate< @dtFromDate AND itemid=@intitemid
SELECT  @ShopTransCostPrice=ISNULL(SUM(concostprice * ISNULL(Transqty*mode,0.0)),0.00) , @ShopTransqty = ISNULL(SUM(ISNULL(Transqty*mode,0.0)), 0.0)
FROM vwshopbincardaudit WHERE  itemid=@intItemId
AND sdate < @dtFromDate
END
ELSE
BEGIN
SELECT  @GodownTransCostPrice=ISNULL(SUM(depcostprice * ISNULL(Transqty*mode,0.0)),0.00),
@GodownTransqty = ISNULL(SUM(TRansqty*mode),0.0)
FROM  vwgdnbincard gb INNER JOIN aGodown g ON gb.godownid=g.GodownID
WHERE gdate< @dtFromDate AND itemid=@intitemid AND g.DepartmentId=@intdepartmentid
SELECT  @ShopTransCostPrice=ISNULL(SUM(depcostprice * ISNULL(Transqty*mode,0.0)),0.00) , @ShopTransqty = ISNULL(SUM(ISNULL(Transqty*mode,0.0)), 0.0) FROM
vwshopbincardaudit sb INNER JOIN aShops s ON sb.shopid=s.ShopID WHERE itemid=@intItemId
AND sdate < @dtFromDate  AND s.DepartmentID=@intdepartmentid
END
SET @transqty=@GodownTransqty+@ShopTransqty
SET @transcostprice=@GodownTransCostPrice+@ShopTransCostPrice
------------------------------------------
SET @curstock= ISNULL(@openingstock,0.0) + ISNULL(@transqty,0.0)
SET @costprice = ISNULL(@opencostprice * @openingstock,0.0)+ISNULL(@transcostprice,0.0)
IF @curstock = 0
SET @costprice = 0.0
IF @outputopenstock =1
BEGIN
SET @outputopenstock = @curstock
END
ELSE
SELECT @intItemid itemid,@curstock openstock,@costprice costprice
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[splocupdatestock]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocupdatestock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.splocupdatestock    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.splocupdatestock    Script Date: 03/10/2002 5:07:00 PM ******/
/* procedure splocupdatestock for update stock */
CREATE proc [dbo].[splocupdatestock]( @intLocationID as int, @chrLocType as char(1))
as
set nocount on
begin
--@intLocationID - shop or godownid
--@chrLocType - ''s'' or ''g''
--to store the bincard stock
if @chrLocType=''S''
--if location is shop
begin
insert  bincardstock
select s.shopid, vw.itemdescription, s.itemid,
(sum(isnull(openingstock,0)) + min(isnull(sbc.quantity,0))) curstock from mosshopstock s
left outer join
(select itemid, shopid, sum(Transqty * mode) quantity  from vwshopbincardaudit
group by shopid, itemid) sbc
on s.shopid=sbc.shopid and s.itemid=sbc.itemid , vwitemdescription vw
where s.itemid=vw.itemid and s.shopid = @intLocationID group by
s.shopid, s.itemid, vw.itemdescription order by vw.itemdescription
update mosshopstock set stock = bin.curstock from bincardstock bin where
bin.locationid=shopid and bin.itemid=mosshopstock.itemid and
bin.curstock<>mosshopstock.stock and shopid = @intLocationID
delete from bincardstock
end
else
--if location is godown
begin
insert  bincardstock
select g.gsgodownid, vw.itemdescription, g.gsitemid, (sum(isnull(gsopeningstock,0)) +
min(isnull(sbc.quantity,0))) curstock from moigodownstock g
left outer join
(select itemid, godownid, sum(Transqty * mode) quantity  from vwgdnbincard
group by godownid, itemid) sbc
on g.gsgodownid=sbc.godownid and g.gsitemid=sbc.itemid , vwitemdescription vw
where g.gsitemid=vw.itemid and g.gsgodownid=@intLocationID group by
g.gsgodownid, g.gsitemid,vw.itemdescription order by vw.itemdescription
update moigodownstock set gsstock = bin.curstock from bincardstock bin where
bin.locationid=gsgodownid and bin.itemid = moigodownstock.gsitemid and
bin.curstock<>moigodownstock.gsstock and gsgodownid = @intLocationID
delete from bincardstock
end
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[splocationwise]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocationwise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.splocationwise    Script Date: 18/01/2003 9:45:43 PM ******/
/****** Object:  Stored Procedure dbo.splocationwise    Script Date: 14/09/2002 12:48:13 AM ******/
CREATE proc [dbo].[splocationwise]( @intLocationID as int, @chrLocType as char(1),
@fetchType as char(1))
as
set nocount on
begin
--@intLocationID - shop or godownid
--@chrLocType - ''s'' or ''g''
--@fetchType - ''a'' to fetch all records other wise any character
--to store the bincard stock
create table #bincardstock
(locationid int,
itemdesc varchar(250),
itemid int,
curstock numeric(18,3))
--to store the actual stock
create table #ActualStock
(locationid int,
itemid int,
systemstock numeric(18,3))
if @chrLocType=''S''
	--if location is shop
	begin
	insert  #bincardstock
	select s.shopid, vw.itemdescription, s.itemid,
	 (sum(isnull(openingstock,0)) + min(isnull(sbc.quantity,0))) curstock from mosshopstock s
	left outer join
	(select itemid, shopid, sum(Transqty * mode) quantity  from vwshopbincardaudit
	group by itemid, shopid) sbc
	on s.shopid=sbc.shopid and s.itemid=sbc.itemid , vwitemdescription vw
	where s.itemid=vw.itemid and s.shopid=@intLocationID group by
	s.itemid, vw.itemdescription, s.shopid order by vw.itemdescription
	
	insert #ActualStock
	select shopid, itemid, sum(stock) stock from mosshopstock where shopid=@intLocationID
	group by itemid, shopid order by itemid
	
	end
else
	--if location is godown
	begin
	insert  #bincardstock
	select g.gsgodownid, vw.itemdescription, g.gsitemid, (sum(isnull(gsopeningstock,0)) +
	min(isnull(sbc.quantity,0))) curstock from moigodownstock g
	left outer join
	(select itemid, godownid, sum(Transqty * mode) quantity  from vwgdnbincard
	group by itemid, godownid) sbc
	on g.gsgodownid=sbc.godownid and g.gsitemid=sbc.itemid , vwitemdescription vw 	
	where g.gsitemid=vw.itemid and g.gsgodownid=@intLocationID group by
	g.gsitemid,vw.itemdescription, g.gsgodownid order by vw.itemdescription
	
	insert #ActualStock
	select gsgodownid, gsitemid, sum(gsstock) stock from moigodownstock where
	gsgodownid=@intLocationID group by gsitemid, gsgodownid order by gsitemid	
	end
	--TO FETCH ALL RECORDS GIVE ''a'' other wise any character to give distinct stock items
	if @fetchtype=''a''	
	select bin.*, ast.systemstock from #bincardstock bin, #actualstock ast where
	bin.locationid=ast.locationid and bin.itemid=ast.itemid
	else		
	--SELECTS THE ITEMS WHICH HAS STOCK PROBLEM
	select bin.*, ast.systemstock from #bincardstock bin, #actualstock ast where
	bin.locationid=ast.locationid and bin.itemid=ast.itemid and
	bin.curstock<>ast.systemstock
	drop table #bincardstock
	drop table #actualstock
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spItemStockDepartmentWise]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemStockDepartmentWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Created On  : 20/05/2009
--Created By  : Sebin.T.S
--Comments    : Created for showing total stock departmentwise
--spItemStockDepartmentWise 1,''20090201''
---------------------------------------------------------------
CREATE PROCEDURE [dbo].[spItemStockDepartmentWise]
(
@departmentid int,
@processDate varchar(15)
)
AS
BEGIN
if (@departmentid<>0)
begin
select itemid,ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,sum(stock)stock from
(
(select CompStock.ItemID,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,
Active,departmentid,departmentname,isnull(Sum(CompStock.OpeningStock),0)Stock,
0 badstock,0 openingstock,0 openingbadstock,max(ItemCostPrice)ItemCostPrice  FROM
(SELECT ItemID,sum(OpeningStock)OpeningStock,0 badstock,0 opstock,
0 openingbadstock,max(ItemCostPrice)ItemCostPrice
FROM mosShopStock where shopid in (select shopid from ashops where departmentid=@departmentid)
group By ItemID
UNION ALL
SELECT gsItemID,sum(gsOpeningStock),0 badstock,0 opstock,
0 openingbadstock,max(gsItemCost)
FROM moiGodownStock where gsgodownid in (select godownid from agodown where departmentid=@departmentid)
group By gsItemID) CompStock
left outer join aitem a on  CompStock.itemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from mosshopstock m
left outer join ashops s on m.shopid=s.shopid and departmentId=@departmentid)
group by CompStock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
union all
(select inqstock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,
convert(numeric(18,3), sum(stock)) stock,
sum(badstock) badstock, sum(openingstock) openingstock, sum(openingbadstock) openingbadstock,
max(itemcostprice) itemcostprice from
(select itemid, openingstock stock, isnull(openingbadstock,0) badstock,
isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock, itemcostprice  from
mosshopstock where StockDate <=@processDate and shopid in (select shopid from ashops where departmentid=@departmentid)
union all
select itemid, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0, 0 from
vwshopbincardaudit where sdate<=@processDate and shopid in (select shopid from ashops where departmentid=@departmentid) group by itemid
union all
select itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) stock, 0, 0, 0  from
vwshopbincardbadqty where sdate<=@processDate and shopid in (select shopid from ashops where departmentid=@departmentid)
group by itemid) inqstock
left outer join aitem a on  inqstock.itemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from mosshopstock m
left outer join ashops s on m.shopid=s.shopid and departmentId=@departmentid)
group by inqstock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
union all
(select gsitemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,
isnull(convert(numeric(18,3), sum(gsstock)),0) gsstock,
sum(gsbadstock) gsbadstock, sum(gsopeningstock) openingstock, sum(gsopeningbadstock)
openingbadstock,Max(gsitemcost) itemcostprice from
(select  gsitemid, gsopeningstock gsstock, isnull(gsopeningbadstock,0) gsbadstock,
isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost from moigodownstock  where gsStockDate <= @processDate and
gsgodownid in (select godownid from agodown where departmentid=@departmentid)
union all
select itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) gsstock, 0,0,0,0 from
vwgdnbincard where GDate <= @processDate
and godownid in (select godownid from agodown where departmentid=@departmentid) group by itemid
union all
select itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) gsbadstock,0,0,0
from vwgdnbincardbadqty where GDate <= @processDate
and godownid in (select godownid from agodown where departmentid=@departmentid) group by itemid) inqstock
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from moigodownstock
left outer join agodown on gsGodownID=GodownID and departmentId=1)
left outer join aitem a on  gsitemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
group by gsitemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
)a
group by itemid,ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname
end
else
begin
select itemid,ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,sum(stock)stock from
(
(select CompStock.ItemID,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,
Active,departmentid,departmentname,isnull(Sum(CompStock.OpeningStock),0)Stock,
0 badstock,0 openingstock,0 openingbadstock,max(ItemCostPrice)ItemCostPrice  FROM
(SELECT ItemID,sum(OpeningStock)OpeningStock,0 badstock,0 opstock,
0 openingbadstock,max(ItemCostPrice)ItemCostPrice
FROM mosShopStock group By ItemID
UNION ALL
SELECT gsItemID,sum(gsOpeningStock),0 badstock,0 opstock,
0 openingbadstock,max(gsItemCost)
FROM moiGodownStock group By gsItemID) CompStock
left outer join aitem a on  CompStock.itemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from mosshopstock m
left outer join ashops s on m.shopid=s.shopid)
group by CompStock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
union all
(select inqstock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,
convert(numeric(18,3), sum(stock)) stock,
sum(badstock) badstock, sum(openingstock) openingstock, sum(openingbadstock) openingbadstock,
max(itemcostprice) itemcostprice from
(select itemid, openingstock stock, isnull(openingbadstock,0) badstock,
isnull(openingstock,0 ) openingstock, isnull(openingbadstock, 0) openingbadstock, itemcostprice  from
mosshopstock where StockDate <= @processDate
union all
select itemid, convert(numeric(18,3), sum(transqty * mode)) stock, 0, 0, 0, 0 from
vwshopbincardaudit where sdate<=@processDate group by itemid
union all
select itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) stock, 0, 0, 0  from
vwshopbincardbadqty where sdate<=@processDate group by itemid) inqstock
left outer join aitem a on  inqstock.itemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from mosshopstock m
left outer join ashops s on m.shopid=s.shopid)
group by inqstock.itemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
union all
(select gsitemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname,
isnull(convert(numeric(18,3), sum(gsstock)),0) gsstock,
sum(gsbadstock) gsbadstock, sum(gsopeningstock) openingstock, sum(gsopeningbadstock)
openingbadstock,Max(gsitemcost) itemcostprice from
(select  gsitemid, gsopeningstock gsstock, isnull(gsopeningbadstock,0) gsbadstock,
isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost from moigodownstock  where gsStockDate <= @processDate
union all
select itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) gsstock, 0,0,0,0 from
vwgdnbincard where GDate <= @processDate group by itemid
union all
select itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) gsbadstock,0,0,0
from vwgdnbincardbadqty where GDate <= @processDate group by itemid) inqstock
left outer join aDepartmentMaster d on d.DepartmentID in (select distinct departmentId from moigodownstock
left outer join agodown on gsGodownID=GodownID)
left outer join aitem a on  gsitemid=a.itemid
left outer join aItemcategory c on a.ItemCategoryID=c.ItemCategoryID
group by gsitemid,c.ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname)
)a
group by itemid,ItemCategoryID,CategoryNameDescription,itemcode,itemdescription,Active,departmentid,departmentname
end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spItemFlowAnalysis]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spItemFlowAnalysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author     : Sebin.T.S
-- Create date: 03/07/2009
-- Description: To Show Data in Report Item Flow Analysis
-- =============================================
--[spItemFlowAnalysis] ''20090412'',''20090512'',5,7,''29''
CREATE PROCEDURE [dbo].[spItemFlowAnalysis]
-- Add the parameters for the stored procedure here
@startDate as varchar(15)='''',
@endDate as varchar(15)='''',
@shopid as int=0,
@godownid as int=0,
@itemCategoryId as varchar(2000)=''''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare @strSql as nvarchar (4000)
Declare @strDateCondition as varchar (200)
Declare @strGdnDateCondition as varchar (200)
Declare @strShopCondition as varchar(200)
Declare @strGdnCondition as varchar(200)
Declare @strCategoryCondition as varchar (200)
if @itemCategoryId<>''''
begin
set @strDateCondition=''sDate >= ''''''+ @startDate + '''''' AND sdate < '''''' + @endDate + ''''''''
set @strShopCondition=''and shopid='' + convert(varchar,@shopid)
set @strCategoryCondition='' and a.ItemCategoryID in (''+ @itemCategoryId +'')''
set @strGdnDateCondition=''gDate >= ''''''+ @startDate + '''''' AND gdate < '''''' + @endDate + ''''''''
set @strGdnCondition=''and godownid='' + convert(varchar,@godownid)
end
if @shopid <> 0
BEGIN
-- Insert statements for procedure here
if @itemCategoryId=''''
BEGIN
SELECT shopid,a.itemid,sdate,Transno, TransID,Transqty,Type,mode,updatetime,
Costprice,DepCostprice,ConCostprice,vw.ItemId,ItemCode,ItemDescription,Part_code,
SizeName,a.itemcategoryid,CategoryNameDescription,ColorName,ItemRate
FROM
vwShopBinCardAudit vw
INNER JOIN aItem a on vw.itemid=a.itemid
INNER JOIN aItemCategory aic on aic.ItemCategoryID=a.ItemCategoryID
LEFT OUTER JOIN aColor ac on a.ColorID=ac.ColorID
LEFT OUTER JOIN aSize az on az.SizeID=a.SizeID
WHERE
sdate >= @startDate AND sdate < @endDate AND shopid=@shopid
ORDER BY
CategoryNameDescription ASC
END
else
BEGIN
SET @strSql=N''SELECT shopid,a.itemid,sdate,Transno, TransID,Transqty,Type,mode,updatetime,Costprice,
DepCostprice,ConCostprice,vw.ItemId,ItemCode,ItemDescription,Part_code,
SizeName,a.itemcategoryid,CategoryNameDescription,ColorName,ItemRate
FROM
vwShopBinCardAudit vw
INNER JOIN aItem a on vw.itemid=a.itemid
INNER JOIN aItemCategory aic on aic.ItemCategoryID=a.ItemCategoryID
LEFT OUTER JOIN aColor ac on a.ColorID=ac.ColorID
LEFT OUTER JOIN aSize az on az.SizeID=a.SizeID
WHERE ''+ @strDateCondition + @strShopCondition + @strCategoryCondition +''
ORDER BY
CategoryNameDescription ASC''
EXEC sp_executesql @strSql
END
END
else if @godownid <> 0
if @itemCategoryId=''''
BEGIN
SELECT godownid,a.itemid,GDate,Transno, TransID,Transqty,Type,mode,updatetime,Costprice,
DepCostprice,ConCostprice,v.ItemId,ItemCode,ItemDescription,Part_code,
SizeName,a.itemcategoryid,CategoryNameDescription,ColorName,ItemRate
FROM
vwgdnBinCard v
INNER JOIN aItem a ON a.itemid =v.ItemID
LEFT OUTER JOIN  aSize s ON a.SizeID= s.SizeID
INNER JOIN  aItemCategory ai ON a.ItemCategoryID= ai.ItemCategoryID
INNER JOIN  aUnit au ON a.UnitsID= au.UnitID
LEFT OUTER JOIN aColor c ON a.ColorID=c.ColorID
WHERE GDate >= @startDate AND GDate < @endDate AND godownid = @godownid
END
else
BEGIN
SET @strSql=''SELECT godownid,a.itemid,GDate,Transno, TransID,Transqty,Type,mode,updatetime,Costprice,
DepCostprice,ConCostprice,v.ItemId,ItemCode,ItemDescription,Part_code,
SizeName,a.itemcategoryid,CategoryNameDescription,ColorName,ItemRate
FROM
vwgdnBinCard v
INNER JOIN aItem a ON a.itemid =v.ItemID
LEFT OUTER JOIN  aSize s ON a.SizeID= s.SizeID
INNER JOIN  aItemCategory ai ON a.ItemCategoryID= ai.ItemCategoryID
INNER JOIN  aUnit au ON a.UnitsID= au.UnitID
LEFT OUTER JOIN aColor c ON a.ColorID=c.ColorID
WHERE ''+ @strGdnDateCondition + @strGdnCondition + @strCategoryCondition +''
ORDER BY CategoryNameDescription ASC''
EXEC sp_executesql @strSql
END
--EXEC sp_executesql @strSql
END
--[spItemFlowAnalysis] ''20090412'',''20090512'',0,7,''29''' 
END
GO
/****** Object:  View [dbo].[vwQuantityUnprocessed_Inv]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwQuantityUnprocessed_Inv]'))
EXEC dbo.sp_executesql @statement = N'
-- Created on          : 26/01/2009
-- Created by          : Benzigar S D
-----------------------------------------------------------------------------------
Create VIEW [dbo].[vwQuantityUnprocessed_Inv] AS
--for hqarrivals which are not confirmed
select ad.adgodownid locationid, ad.aditemid itemid, ah.ahArrivaldate GDate,
ah.aharrivalid Transid, ah.ahArrivalno TransNo,
ad.adDespatchedQty * pk.quantity TransQty ,
''Shipment Arrival'' as type, ''T'' mode, updatetime, ''From HQ'' Fromlocation,
gd.godownname ToLocation, ''Not Confirmed'' ProcessType, ''g'' LocationType, ahDepartmentId DepartmentId,
adCostPrice*ahdepexrate  depCostPrice,adCostPrice*ahconexrate conCostPrice
from loiarrivalheader ah, loiarrivaldetail ad,
aitem ai, aPackingTypeCapacityDetail pk, Agodown gd
where ah.ahcancelled=0
and ah.ahtransfinished= 0
and ah.aharrivalid=ad.adarrivalid
and ah.ahlocalgodownid=ad.adgodownid
and ad.aditemid=ai.itemid
and ahlocalgodownid = gd.godownid
and ai.unitsid=pk.unitsid
and ad.adpackingtypeid=pk.packingtypeid
union all
--Despatches not received in godowns
select  case isnull(dhgodownid,0) when 0 then dhShopId else dd.ddgodownid end  locationid,
dd.dditemid itemid, dnm.dnmdespatchnotedate GDate,
dh.dhdespatchnoteid Transid, dh.dhdespatchnoteno TransNo,
dd.ddQty * pk.quantity, ''Shipment Arrival'' as type, ''T'' mode, dh.updatetime,
''From HQ'' Fromlocation, gd.godownname ToLocation,
''Not Received'' ProcessType, case isnull(dhgodownid,0) when 0 then ''s''
else ''g'' end LocationType, dnm.DepartmentId DepartmentId,
case isnull(dhgodownid,0) when 0 then ddcostprice*sed.DEXRATE else ddcostprice*ged.DEXRATE end  depcostprice,
case isnull(dhgodownid,0) when 0 then ddcostprice*sed.CEXRATE else ddcostprice*ged.CEXRATE end  concostprice
from ahqdespatchnotemain dnm,
(ahqdespatchnoteheader dh left outer join vwGodownExchangerateDetails ged on dh.dhgodownid=ged.godownid
left outer join vwShopExchangerateDetails sed on dh.dhShopId=sed.shopid
) left outer join aGodown gd on dhgodownid = gd.godownid
left outer join ashops sd on dhShopid = sd.shopid , 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
union all
--Transfer in from shop or godown which are not confirmed
select  ahlocalgodownid, asditemid, ah.ahArrivaldate, ah.aharrivalid,
ah.ahArrivalno TinNo, asd.asdDespatchedGoodQty  as TinQty,
''Transfer In'' as type, ''T'' mode,updatetime,
isnull(shopname,'''') + isnull(g.godownname,'''') FromLocation,
t.godownname ToLocation, ''Not Confirmed'' ProcessType, ''g'' LocationType,
ahDepartmentid,asd.asdcostprice*ahdepexrate depcostprice,asd.asdcostprice*ahconexrate concostprice
from  loiarrivalshipmentdetail asd, loiarrivalheader ah
left outer join ashops on ah.ahshopid = shopid
left outer join agodown g on ah.ahgodownid = g.godownid, agodown t
where ahlocalgodownid = t.godownid
and ah.ahcancelled=0
and ah.ahtransfinished = 0
and ahlocalgodownid = asd.asdgodownid
and aharrivalid = asd.asdarrivalid
union all
--Deapatch to shop which are not processed yet in shops
select dh.dhShopid, dd.dditemid, dh.dhDespatchDate,
dh.dhdespatchid, dh.dhDespatchNo DespatchNo,
dd.dditemgoodqty as despatchqty,
''Despatch To Shop'' as Type, ''T'' mode,updatetime, g.godownname fromlocation,
s.shopname, ''Not Received'', ''s'' LocationType, dhDepartmentid,ddcostedprice*dhdepexrate  depCostPrice,ddcostedprice*dhconexrate conCostPrice
from meidespatchtoshopheader dh, meidespatchtoshopdetail dd, ashops s, agodown g
where dh.dhdespatchid=dd.dddespatchid
and dh.dhgodownid=dd.ddgodownid
and dh.dhcancelled=0
and dhselected=0
and dhshopid = s.shopid
and dhgodownid = g.godownid
and dhtransfinished=1
union all
--Transferouts which are not processed yet in the receving godown
select gthToGodownid, gtditemid, gthDespatchDate, gthdespatchid,
gthDespatchNo ToutNo, gtdItemGoodQty as ToutQty ,
''Transfer Out'' as Type, ''T'' mode,updatetime, fg.godownname,
tg.godownname, ''Not Received'', ''g'' LocationType, gthDepartmentID,gtdCostPrice*gthdepexrate depCostPrice,gtdCostPrice*gthconexrate ConCostPrice
from meigodowntransferheader, meigodowntransferdetail, agodown fg, agodown tg
where gthdespatchid=gtddespatchid
and gthFromGodownid=gtdgodownid
and gthCancelled=0
and gthselected =0
and gthfromgodownid = fg.godownid
and gthtogodownid = tg.godownid
and gthtransfinished=1
union all
--arrival in shops from godown which are not confirmed yet
select h.gahshopid shopid, d.gaditemid itemid, h.gaharrivaldate sdate,
h.gaharrivalid Transid, h.gaharrivalno Transno, d.gadItemGoodQuantity TransQty,
''Arrival From Godown'' Type, ''T'' mode,updatetime,
isnull(g.godownname, ''HQ Despatch''), s.shopname, ''Not Confirmed'', ''s'' LocationType,
gahDepartmentId,gadCostPrice * gahdepexrate depCostPrice, gadCostPrice * gahconexrate ConCostPrice
from losgoodsarrivaltoshopheader h left outer join  agodown g on
gahDespatchedGodownID = g.godownid, losgoodsarrivaltoshopdetail d,
ashops s where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid
and h.gahcancelled=0 and h.gahtransfinished=0 and gahshopid = s.shopid
union all
--transfer in from other shops which are not confirmed yet
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihid, h.tihno,
d.TIDtransfergoodqty TinQty, ''Transfer In'' TYpe, ''T'' mode,
updatetime, fs.shopname, ts.shopname, ''Not Confirmed'', ''s'' LocationType,
tihDepartmentId, tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice
from lostransferinheader h, lostransferindetail d, ashops fs, ashops ts
where h.tihid=d.tidid
and h.tihshopid=d.tidshopid
and h.tihcancel=0
and h.tihtransfinished=0
and tihfromshopid = fs.shopid
and tihshopid = ts.shopid
union all
--Transferouts from shops to another shops which are not selected
select tohToshopid, toditemid, tohDate sdate, tohid, tohno,
todissuedgoodqty as ToutQty , ''Transfer Out'' Type, ''T'' mode,
updatetime, fs.shopname, ts.shopname, ''Not Received'', ''s'' LocationType,
tohDepartmentId,todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice
from mestransferoutheader , mestransferoutdetail, ashops fs, ashops ts
where tohid=todid
and Tohshopid=todshopid
and tohcancelled=0
and tohshopid = fs.shopid
and tohtoshopid = ts.shopid
and tohused = 0
and tohtransfinished=1
union all
--Deapatch to godowns from shops which are not received in godowns
select dh.dghGodownid, dd.dgditemid, dh.dghDate sdate, dh.dghid, dh.dghNo,
dd.dgddespatchedgoodqty as despatchqty,
''Despatch To Godown'' TYpe, ''T'' mode,updatetime, s.shopname,
g.godownname, ''Not Received'', ''g'' LocationType, dghDepartmentid,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd , ashops s, agodown g
where dh.dghid=dd.dgdid
and dh.dghshopid=dd.dgdshopid
and dh.dghcancelled=0
and dghshopid = s.shopid
and dghgodownid = g.godownid
and dghused = 0
and dghtransfinished=1
union all
-- Items which have difference in transactions while sending and receiving
select hdw.dstogodownid, dsitemid, getdate() sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Distribute'' TYpe, ''d''  mode,getdate(),
'''', ag.godownname, ''Not Distributed'', ''g'' LocationType, ag.departmentid,dscostprice*ged.Dexrate depCostPrice,dscostprice*ged.Cexrate ConCostPrice
from  agodown ag,vwHQDiffwriteoff hdw
inner join vwGodownExchangerateDetails ged on hdw.dstogodownid=ged.godownid
where dstogodownid = ag.godownid and dstogodownid <> 0 and ag.departmentid=ged.departmentid
union all
-- Items which have difference in transactions while sending and receiving
select dstoshopid, dsitemid, getdate() sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Distribute'' TYpe, ''d''  mode, getdate(),
'''', ash.shopname, ''Not Distributed'', ''s'' LocationType , ash.departmentid,
dscostprice*sed.Dexrate depCostPrice,dscostprice*sed.Cexrate ConCostPrice
from  ashops ash,vwHQDiffwriteoff hdw
inner join vwShopExchangerateDetails sed on hdw.dstoshopid=sed.shopid
where dstoshopid = ash.shopid and dstoshopid <> 0
union all
-- Items which have difference in transactions while sending and receiving
select dsfromshopid, dsitemid, getdate() sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Recovery'' TYpe, ''r''  mode, getdate(),
s.shopname, location, ''Not Recovered'', ''s'' LocationType , s.departmentid,
dsr.dscostprice*sed.Dexrate depCostPrice,dsr.dscostprice*sed.Cexrate ConCostPrice
from  ashops s,vwDiffStockRecovery dsr
inner join vwShopExchangerateDetails sed on dsr.dsfromshopid=sed.shopid
where dsfromshopid = s.shopid and dsfromshopid <> 0
union all
-- Items which have difference in transactions while sending and receiving
select dsfromgodownid, dsitemid, getdate() sdate, 1, ''DIST'',
(dstoadd - dstodeduct) transqty, ''Recovery'' TYpe, ''r''  mode, getdate(),
g.godownname, location, ''Not Recovered'', ''g'' LocationType , g.departmentid,
dgr.dscostprice*ged.Dexrate depCostPrice,dgr.dscostprice*ged.Cexrate ConCostPrice
from  agodown g,vwDiffStockRecovery dgr
inner join vwGodownExchangerateDetails ged on dgr.dsfromshopid=ged.godownid
where dsfromgodownid = g.godownid and dsfromgodownid <> 0'
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate_TransWise]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryValueAsOnDate_TransWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec spInventoryValueAsOnDate_TransWise 0,0,''20080101'',1,2,'''','''',0
--exec [spInventoryValueAsOnDate_TransWise] 0,0,''20091231'',1,1,'''','''',0
/*
-----------------------------------------------------------------------------------------------------------------------------------
Created on   :  26/01/2009
Created by   :  Prasanth Joseph
Description  :  Inventory Valuation Summary Report
Usage    :  [spInventoryValueAsOnDate_TransWise] 0,0,''20071231'',1,0,''5,6,7'','''',0
------------------------------------------------------------------------------------------------------------------------------------
--spInventoryValueAsOnDate_TransWise 0,0, ''20071231'',1,0,'''','''',0
*/
CREATE  PROCEDURE [dbo].[spInventoryValueAsOnDate_TransWise]
(
@intShopId as int,
@intGodownId as int,
@strOnDate as varchar(10),
@intCompanyId as int,
@intDepartmentId as int,
@strCategoryID as varchar(2000),
@strBrand as varchar(50),
@strDistributer as int
)
AS
/*
DECLARE
@intShopId as int,
@intGodownId as int,
@strOnDate as varchar(10),
@intCompanyId as int,
@intDepartmentId as int,
@strCategoryID as varchar(2000),
@strBrand as varchar(50),
@strDistributer as int
SET  @intShopId = 0
SET @intGodownId = 0
SET @strOnDate = ''20071231''
SET @intCompanyId  = 1
SET @intDepartmentId = 0
SET @strCategoryID = ''''
SET @strBrand = ''''
SET @strDistributer = 0
--*/
BEGIN
SET NOCOUNT ON
Declare @strShopCondition as varchar (200)
Declare @strGodownCondition as varchar (200)
Declare @strDepartmentCondition as varchar (200)
Declare @strCompanyCondition as varchar (200)
Declare @strCategoryCondition as varchar (200)
Declare @strDistribiterCondition as varchar (200)
Declare @strBrandCondition as varchar (200)
Declare @strSql as nvarchar (4000)
Set @strShopCondition = ''''
Set @strGodownCondition = ''''
Set @strDepartmentCondition = ''''
Set @strCompanyCondition = ''''
Set @strCategoryCondition = ''''
Set @strDistribiterCondition = ''''
Set @strBrandCondition = ''''
if @intShopId <> 0
Set @strShopCondition = '' And ShopID = '' + convert(varchar,@intShopId)
if @intGodownId <> 0
Set @strGodownCondition = '' And GodownID = '' + convert(varchar,@intGodownId)
if @intDepartmentId <> 0
Set @strDepartmentCondition = '' And ShopID  in ( select ShopID from Ashops where DepartmentID = '' + convert(varchar,@intDepartmentId) + '') or GodownID in ( select GodownID from AGodown where DepartmentID = '' + convert(varchar,@intDepartmentId)+'')''
if @intCompanyId<>0
set @strCompanyCondition='' where Companyid = '' + convert(varchar,@intCompanyId)
if @strCategoryID<>''''
set @strCategoryCondition='' and AC.itemcategoryid in (''+ @strCategoryID +'')''
if @strBrand<>''''
set @strBrandCondition='' and brand= '' + @strBrand
if @strDistributer<>0
set @strDistribiterCondition='' and DID = '' + convert(varchar,@strDistributer)
CREATE TABLE #ONDATESTOCK(
COMPANYID INT,
SHOPID INT,
GODOWNID INT,
TRDATE DATETIME,
ITEMID INT,
STOCK NUMERIC(18,3),
DEPCOSTPRICE NUMERIC(18,3),
DEPSTOCKVALUE NUMERIC(18,3),
COMCOSTPRICE NUMERIC(18,3),
COMSTOCKVALUE NUMERIC(18,3)
)
CREATE TABLE #SHOPEXRATE(
SHOPID INT,
EXRATE NUMERIC(18, 8)
)
CREATE TABLE #GODOWNEXRATE(
GODOWNID INT,
EXRATE NUMERIC(18, 8)
)
INSERT INTO #SHOPEXRATE
SELECT SHOPID,CEXRATE FROM VWSHOPEXCHANGERATEDETAILS
INSERT INTO #GODOWNEXRATE
SELECT GODOWNID,CEXRATE FROM VWGODOWNEXCHANGERATEDETAILS
--/*
----********************************************** Retriving Stock Informations **********************************************************************
---INSERTING  OPENING STOCK FOR SHOP
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT 1 COMPANYID,S.SHOPID,0 GODOWNID,ITEMID, ISNULL(CONVERT(NUMERIC(18,3),OPENINGSTOCK),0) STOCK ,ISNULL(CDCOSTINGPRICE,0) DEPCOSTPRICE,
ISNULL(CONVERT(NUMERIC(18,3),OPENINGSTOCK),0) * ISNULL(CDCOSTINGPRICE,0)  DEPSTOCKVALUE,
ISNULL(CDCOSTINGPRICE,0)* EXRATE COMCOSTPRICE,
ISNULL(CONVERT(NUMERIC(18,3),OPENINGSTOCK),0) * ISNULL(CDCOSTINGPRICE,0)*EXRATE  COMSTOCKVALUE
FROM MOSSHOPSTOCK S
LEFT OUTER JOIN LOACOSTINGDETAIL ON ITEMID = CDITEMID AND CDCOSTINGID =0
INNER JOIN #SHOPEXRATE EX ON EX.SHOPID=S.SHOPID
WHERE OPENINGSTOCK <> 0
--*/
---INSERTING  OPENING STOCK FOR GODOWN
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT 1 COMPANYID,0 SHOPID,GSGODOWNID,GSITEMID,ISNULL(CONVERT(NUMERIC(18,3),GSOPENINGSTOCK),0) STOCK ,ISNULL(CDCOSTINGPRICE,0) DEPCOSTPRICE,
ISNULL(CONVERT(NUMERIC(18,3),GSOPENINGSTOCK),0) * ISNULL(CDCOSTINGPRICE,0)  DEPSTOCKVALUE,
ISNULL(CDCOSTINGPRICE,0) * EXRATE COMCOSTPRICE,
ISNULL(CONVERT(NUMERIC(18,3),GSOPENINGSTOCK),0) * ISNULL(CDCOSTINGPRICE,0) * EXRATE  COMSTOCKVALUE
FROM MOIGODOWNSTOCK G
LEFT OUTER JOIN LOACOSTINGDETAIL ON GSITEMID = CDITEMID AND CDCOSTINGID =0
INNER JOIN #GODOWNEXRATE EX ON EX.GODOWNID=G.GSGODOWNID
WHERE GSOPENINGSTOCK <> 0
--*/
---INSERTING TRANSACTION STOCK FOR SHOP
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,TRDATE,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT 1 COMPANYID,SHOPID, 0 GODOWNID, SDATE ,ITEMID, CONVERT(NUMERIC(18,3), TRANSQTY * MODE) STOCK ,DEPCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY * MODE)*DEPCOSTPRICE DEPSTOCKVALUE ,
CONCOSTPRICE,CONVERT(NUMERIC(18,3), TRANSQTY * MODE)*CONCOSTPRICE COMSTOCKVALUE
FROM VWSHOPBINCARDAUDIT WHERE SDATE <= @STRONDATE
---INSERTING TRANSACTION STOCK FOR GODOWN
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,TRDATE,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT 1 COMPANYID,0 SHOPID,GODOWNID, GDATE,ITEMID, CONVERT(NUMERIC(18,3), TRANSQTY * MODE) STOCK  ,DEPCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY * MODE)  * DEPCOSTPRICE ,CONCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY * MODE)  * CONCOSTPRICE
FROM VWGDNBINCARD WHERE GDATE <= @STRONDATE
--/*
---INSERTING UNPROCESSED STOCK FOR SHOP
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,TRDATE,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT 1 COMPANYID,LOCATIONID SHOPID,0 GODOWNID, GDATE,ITEMID,CONVERT(NUMERIC(18,3), TRANSQTY ) STOCK ,DEPCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY )  * DEPCOSTPRICE ,CONCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY ) * CONCOSTPRICE
FROM VWQUANTITYUNPROCESSED_INV WHERE LOCATIONTYPE=''S'' AND GDATE <= @STRONDATE
--*/
---INSERTING UNPROCESSED STOCK FOR GODOWN
INSERT INTO #ONDATESTOCK (COMPANYID,SHOPID,GODOWNID,TRDATE,ITEMID,STOCK,DEPCOSTPRICE,DEPSTOCKVALUE,COMCOSTPRICE,COMSTOCKVALUE)
SELECT  1 COMPANYID,0 SHOPID,LOCATIONID GODOWNID,GDATE, ITEMID,  CONVERT(NUMERIC(18,3), TRANSQTY ) STOCK ,DEPCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY )  * DEPCOSTPRICE ,CONCOSTPRICE,
CONVERT(NUMERIC(18,3), TRANSQTY ) * CONCOSTPRICE
FROM VWQUANTITYUNPROCESSED_INV WHERE LOCATIONTYPE=''G'' AND GDATE <= @STRONDATE
---*/
----**************************************************************************************************************************************************
select *  into bak_ondatestock from #ONDATESTOCK
--print @strDepartmentCondition
IF @INTSHOPID=0 AND @INTGODOWNID  = 0  and @intDepartmentId=0
SET @strSql = N'' SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(COMCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(COMSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION  +  @STRDISTRIBITERCONDITION + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
ELSE IF @intDepartmentId > 0 and @INTSHOPID=0 AND @INTGODOWNID  = 0
SET @strSql=N''SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(DEPCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(DEPSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION + @STRDISTRIBITERCONDITION +
@strDepartmentCondition + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
ELSE IF  @intDepartmentId > 0  AND @INTGODOWNID  = 0  and @INTSHOPID > 0
SET @strSql=N''SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(DEPCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(DEPSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION + @STRDISTRIBITERCONDITION +
@STRSHOPCONDITION + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
ELSE IF @intDepartmentId > 0  AND @INTGODOWNID  > 0  and @INTSHOPID=0
SET @strSql=N''SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(DEPCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(DEPSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION + @STRDISTRIBITERCONDITION +
@strGodownCondition + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
ELSE IF @intDepartmentId = 0  AND @INTGODOWNID = 0  and @INTSHOPID>0
SET @strSql=N''SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(DEPCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(DEPSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION + @STRDISTRIBITERCONDITION +
@STRSHOPCONDITION + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
ELSE IF @intDepartmentId = 0  AND @INTGODOWNID > 0  and @INTSHOPID=0
SET @strSql=N''SELECT S.ITEMID,VW.ITEMDESCRIPTION,CODE,SUM(STOCK)STOCK ,AVG(DEPCOSTPRICE)COSTPRICE,CATEGORYNAMEDESCRIPTION ,DID,
BRAND,AC.ITEMCATEGORYID,SUM(DEPSTOCKVALUE)STOCKVAL,VUNITCODE
FROM #ONDATESTOCK S
INNER JOIN VWITEMDESCRIPTION VW ON S.ITEMID=VW.ITEMID
INNER JOIN AITEM AI ON AI.ITEMID=S.ITEMID
INNER JOIN AITEMCATEGORY AC ON VW.VITEMCATEGORYID=AC.ITEMCATEGORYID '' +
@STRCOMPANYCONDITION + @STRCATEGORYCONDITION + @STRBRANDCONDITION + @STRDISTRIBITERCONDITION +
@strGodownCondition + ''
GROUP BY S.ITEMID,CATEGORYNAMEDESCRIPTION ,DID,VW.ITEMDESCRIPTION,CODE,VUNITCODE,BRAND,AC.ITEMCATEGORYID
HAVING SUM(STOCK) <>0 ''
print @strSql
EXEC sp_executesql @strSql
DROP TABLE #ONDATESTOCK
DROP TABLE #SHOPEXRATE
DROP TABLE #GODOWNEXRATE
drop table bak_ondatestock
SET NOCOUNT OFF
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryValueAsOnDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------
-- spInventoryValueAsOnDate 1,0,''20040101'',1,1
-----------------------------------------------------------------------------------
-- Modified on  : 10/06/2003, 28/04/2004, 01/05/2004
-- Modified by  : Kishore, Hariharan
-- Comments     : Added the @CompanyId and @DepartmentId parameters.
--                Converted the amount to department currency
--  : taken asondate costprice correctly
-- Modified on  : 06/07/04,
-- Modified by  : venkitesh
-- Comments     : Added the unitcode
-----------------------------------------------------------------------------------
--Modified on : 27/05/2010
--Modified By : Nidheesh P V
--Comments : used departmentid to filter transactions and to get departmentwise inventry
--valuation
-----------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spInventoryValueAsOnDate] ( @intShopId as int,
@intGodownId as int,
@strOnDate as varchar(10), @intCompanyId as int,
@intDepartmentId as int) as
Set noCount on
CREATE table #ONDateStock(
LocationId int,
itemid int,
Stock numeric(18,3),
newSCost numeric(18,8),
newSUpdtime datetime,
OldSCost numeric(18,8),
OldSUpdtime datetime,
newLCost numeric(18,8),
newLUpdtime datetime,
OldLCost numeric(18,8),
OldLUpdtime datetime)
begin
Declare @intDepCurrency as int
Declare @intInvCurrency as int
Declare @numExchangeRate as Numeric(18, 8)
-- get the inventory currency id
select @intInvCurrency = currencyid from aAccountMaster
where AccountId = (select InventoryID from aPackageSettings)
and CompanyId = @intCompanyId
Set @numExchangeRate = 0
-- if department id is not 0
If @intDepartmentId <> 0
Begin
-- get the department currency
Select @intDepCurrency = DepCurrencyId from aDepartmentMaster
Where DepartmentId = @intDepartmentId
And CompanyId = @intCompanyId
-- get the exchange rate
Exec spGetExchangeRate @intCompanyId, @intInvCurrency, @intDepCurrency,
@numExchangeRate OUTPUT
End
Else
Begin
-- get the department currency
Select @intDepCurrency = CurrencyId from aCompanyMaster
Where CompanyId = @intCompanyId
-- get the exchange rate
Exec spGetExchangeRate @intCompanyId, @intInvCurrency, @intDepCurrency,
@numExchangeRate OUTPUT
End
-- if Shop Id and Godown Id are zero,
-- return all records
if @intShopId = 0 and @intGodownId = 0
begin
if @intDepartmentId= 0 --if depaartment is not selected then companywise
Begin
insert #ONDateStock
Select 0,Total.itemId, sum(Stock), 0, null, 0, null, 0, null, 0, null  from
(select  gsItemId ItemId, isnull(gsopeningStock, 0) Stock
from moiGodownStock
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwGdnBinCard where gdate <= @strOnDate group by Itemid
union all
select ItemId, isnull(convert(numeric(18,3),openingStock),0) Stock
from mosShopStock
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwshopbincardaudit where sdate <= @strOnDate group by Itemid
union all
select ItemId,  convert(numeric(18,3), sum(transqty ))
from vwquantityunprocessed where GDate <= @strOnDate
group by Itemid) total
group by total.ItemId
end
else   --if depaartment is selected
begin
insert #ONDateStock
Select 0,Total.itemId, sum(Stock), 0, null, 0, null, 0, null, 0, null  from
(select  gsItemId ItemId, isnull(gsopeningStock, 0) Stock
from moiGodownStock where gsGodownId in (select godownid from agodown where departmentid=@intDepartmentId)
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwGdnBinCard where GodownId in (select godownid from agodown where departmentid=@intDepartmentId)
and gdate <= @strOnDate group by Itemid
union all
select ItemId, isnull(convert(numeric(18,3),openingStock),0) Stock
from mosShopStock  where ShopId in (select shopid from ashops where departmentid=@intDepartmentId)
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwshopbincardaudit where  ShopId in (select shopid from ashops where departmentid=@intDepartmentId)
and sdate <= @strOnDate group by Itemid
union all
select ItemId,  convert(numeric(18,3), sum(transqty ))
from vwquantityunprocessed where GDate <= @strOnDate and DepartmentId=@intDepartmentId
group by Itemid) total
group by total.ItemId
end
end
if @intShopId > 0
begin
insert #ONDateStock
Select 0,Total.itemId, sum(Stock), 0, null, 0, null, 0, null, 0, null  from
(select ItemId, isnull(convert(numeric(18,3),openingStock),0) Stock
from mosShopStock where OpeningStock <> 0 and ShopId = @intShopID
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwshopbincardaudit where sdate <= @strOnDate and ShopId = @intShopId group by Itemid ) total
group by total.ItemId
end
if @intGodownId > 0
begin
insert #ONDateStock
Select 0,Total.itemId, sum(Stock), 0, null, 0, null, 0, null, 0, null  from
(select  gsItemId ItemId, isnull(gsopeningStock, 0) Stock
from moiGodownStock where gsGodownId = @intGodownId and gsOpeningStock <> 0
union all
select ItemId, convert(numeric(18,3), sum(transqty * mode)) Stock
from vwGdnBinCard where gdate <= @strOnDate and GodownId = @intGodownId group by Itemid) total
group by total.ItemId
end
Update #ONDateStock set newSCost = scostNew.cost,
newSUpdtime = scostNew.UpdateTime from
(Select CdItemId, isnull(ItemRate* @numExchangeRate,0) cost,
UpdateTime from loaCostingDetail cd, loaCostingHeader ch, aitem where
cdCostingId = chCostingId and ChCancelled = 0 and
(isnull(chCostingDate, ''20000101'') <= @strOnDate or chcostingdate is null)
and chCostingId = (Select  max(ChCostingId) from loaCostingHeader ch1,
loaCostingDetail cd1 where ch1.chCostingId = cd1.cdCostingId
and cd1.cdItemId = cd.cdItemId and (isnull(ch1.chCostingDate, ''20000101'') <= @strOnDate or
ch1.chcostingdate is null)) and cdCostingId = 0 and 0 = (Select count(*)
from loaCostingDetail cd2, Loacostingheader ch2 where chcostingid = cdcostingid and chcancelled = 0
and ch2.chCostingid >0 and cd.cdItemid = cd2.cdItemid) and cd.cdItemId = aitem.itemid) scostNew where
#ONDateStock.Itemid = scostNew.cdItemId
Update #ONDateStock set newSCost = scostNew.cost,
newSUpdtime = scostNew.UpdateTime from
(Select CdItemId, isnull(cdNewItemCostPrice * @numExchangeRate,0) cost,
UpdateTime from loaCostingDetail cd, loaCostingHeader ch, aitem where
cdCostingId = chCostingId and ChCancelled = 0 and
(isnull(chCostingDate, ''20000101'') <= @strOnDate or chcostingdate is null)
and chCostingId = (Select  max(ChCostingId) from loaCostingHeader ch1,
loaCostingDetail cd1 where ch1.chCostingId = cd1.cdCostingId
and cd1.cdItemId = cd.cdItemId and (isnull(ch1.chCostingDate, ''20000101'') <= @strOnDate or
ch1.chcostingdate is null)) and (cdCostingID >0 or (cdCostingId = 0 and 0 <> (Select count(*)
from loaCostingDetail cd2, Loacostingheader ch2 where chcostingid = cdcostingid and chcancelled = 0
and ch2.chCostingid >0 and cd.cdItemid = cd2.cdItemid))) and cd.cdItemId = aitem.itemid) scostNew where
#ONDateStock.Itemid = scostNew.cdItemId
Update #ONDateStock set OldSCost = scostold.cost,
OldSUpdtime = scostOld.UpdateTime from
(Select CdItemId, isnull(cdOldItemCostPrice * @numExchangeRate,0) cost,
UpdateTime from loaCostingDetail cd, loaCostingHeader ch where
cdCostingId = chCostingId and ChCancelled = 0 and
chCostingDate > @strOnDate  and chCostingId = (Select  min(ChCostingId) from
loaCostingHeader ch1, loaCostingDetail cd1 where
ch1.chCostingId = cd1.cdCostingId and cd1.cdItemId = cd.cdItemId
and chCostingDate >@strOnDate )) scostOLD where
#ONDateStock.Itemid = scostOLD.cdItemId
Update #ONDateStock set newLCost = scostNew.cost,
newLUpdtime = scostNew.UpdateTime from
(Select lpCdItemId, isnull(lpcdnewitemcostprice * @numExchangeRate,0) cost,
UpdateTime from loaLocalPurchaseCostingDetail cd,
loaLocalPurchaseCostingHeader ch where
lpcdcostingid = lpchCostingid and lpChCancelled = 0 and
lpchDate <= @strOnDate  and lpchCostingId = (Select  max(lpchcostingid) from
loaLocalPurchaseCostingHeader ch1, loaLocalPurchaseCostingDetail cd1 where
ch1.lpchcostingid = cd1.lpcdcostingid and cd1.lpcditemid = cd.lpcditemid
and lpchDate <= @strOnDate)) scostNew where
#ONDateStock.Itemid = scostNew.lpcdItemId
Update #ONDateStock set OldLCost = scostOld.cost,
OldLUpdtime = scostOld.UpdateTime from
(Select lpCdItemId, isnull(lpcdOLDitemcostprice * @numExchangeRate,0) cost,
UpdateTime from loaLocalPurchaseCostingDetail cd,
loaLocalPurchaseCostingHeader ch where
lpcdcostingid = lpchCostingid and lpChCancelled = 0 and
lpchDate > @strOnDate  and lpchCostingId = (Select  min(lpchcostingid) from
loaLocalPurchaseCostingHeader ch1, loaLocalPurchaseCostingDetail cd1 where
ch1.lpchcostingid = cd1.lpcdcostingid and cd1.lpcditemid = cd.lpcditemid
and lpchDate > @strOnDate)) scostOLD where
#ONDateStock.Itemid = scostOLD.lpcdItemId
--<TOBE COMMENTED AFTER FIRST RUN ************************************************************>
/*insert loaCostingDetail( cdcostingid, cditemid, cdCostingValue, cdItemQuantity, cdBillUnitPrice,
cdCustomsUnitPrice, cdOldItemCostPrice, cdNewItemCostPrice, cdCostingprice, cdcustcategoryperc )
Select 0, AITEM.itemid, 1,  0, ITEMRATE, ITEMRATE, ITEMRATE, ITEMRATE, ITEMRATE, 20040228 from
#ONDateStock, AITEM where newLUpdtime is null and
newSUpdtime is null AND OldLUpdtime is null and  OldSUpdtime is null and stock<>0
AND AITEM.ITEMID = #ONDateStock.ITEMID */
--<TOBE COMMENTED AFTER FIRST RUN ************************************************************>
--query starts here
Select #ONDateStock.itemid, vw.ItemDescription, vw.Code, Stock, case when newSUpdtime > newLUpdtime then newSCost
else NewLCost end CostPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId,
case when newSUpdtime > newLUpdtime then newSCost * Stock
else NewLCost * Stock end stockval ,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId
and newSUpdtime is not null and  newLUpdtime is not null
and Stock <> 0
union all
Select #ONDateStock.itemid ,vw.ItemDescription, vw.Code,  Stock, NewLCost CostPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId, Stock * NewLCost stockval,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and
newSUpdtime is null and  newLUpdtime is not null
and Stock <> 0
union all
Select #ONDateStock.itemid ,vw.ItemDescription, vw.Code,  Stock, NewsCost CostPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId, Stock * newSCost stockval,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and newLUpdtime is null and  newSUpdtime is not null
and Stock <> 0
union all
Select #ONDateStock.itemid,vw.ItemDescription, vw.Code,  Stock, case when oldSUpdtime > oldLUpdtime  then oldSCost
else oldLCost end CostPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId,
case when oldSUpdtime > oldLUpdtime  then oldSCost * Stock
else oldLCost * Stock end stockval,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and newLUpdtime is null and  newSUpdtime is null
AND OldLUpdtime is not null and  OldSUpdtime is not null and Stock <> 0
union all
Select #ONDateStock.itemid,vw.ItemDescription, vw.Code,  Stock, oldSCost costPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId, Stock * oldSCost,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and newLUpdtime is null and
newSUpdtime is null AND OldLUpdtime is null and  OldSUpdtime is not null and Stock <> 0
union all
Select #ONDateStock.itemid,vw.ItemDescription, vw.Code,  Stock, oldLCost costPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId, Stock * oldLCost,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and newLUpdtime is null and
newSUpdtime is null AND OldLUpdtime is not null and  OldSUpdtime is null and Stock <> 0
union all
Select #ONDateStock.itemid,vw.ItemDescription, vw.Code,  Stock, itemrate * @numExchangeRate costPrice, aItemCategory.CategoryNameDescription,
aItem.dId, aItem.Brand, aItem.ItemCategoryId, Stock * itemrate * @numExchangeRate,vw.vunitcode unitcode
from #ONDateStock, vwItemDescription vw, aItem, aItemCategory
where #ONDateStock.ItemId = vw.ItemId and vw.ItemId = aItem.ItemId
and aItem.ItemCategoryId = aItemCategory.ItemCategoryId  and  newLUpdtime is null and
newSUpdtime is null AND OldLUpdtime is null and  OldSUpdtime is null and stock<>0
AND AITEM.ITEMID = #ONDateStock.ITEMID and Stock <> 0
end
Set noCount Off' 
END
GO
/****** Object:  StoredProcedure [dbo].[spFindItemsRateNotFixed]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFindItemsRateNotFixed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--modified by   : hariharan
--MOdified Date : 05/09/2002, 18/10/2003
--Comments	: Departmentid Condition is added
CREATE procedure [dbo].[spFindItemsRateNotFixed]( @strDate as varchar(10), @intDepId as int=0)
as
declare
@dtDate as datetime
select @dtDate= convert(datetime,@strDate)
/*select distinct vw.itemdescription,vw.itemid, i.itemrate from vwshopitemsales s,
vwitemdescription vw, aITEM i where s.posditemid=vw.itemid
--and s.poshbilldate=@dtDate
and i.itemid=s.posditemid and i.itemrate=0 order by vw.itemdescription
previous code commented by hariharan on 020905*/
if @intDepId >0
select distinct zerorate.itemdescription, zerorate.itemid, zerorate.itemrate from
( select distinct vw.itemdescription,vw.itemid, i.itemrate from  vwshopbincardaudit s,
vwitemdescription vw, aITEM i, ashops sh where s.itemid = vw.itemid
and s.sdate = @dtDate and i.itemid = s.itemid and i.itemrate=0
and sh.shopid = s.ShopId and sh.Departmentid = @intDepId
union all
select distinct vw.itemdescription,vw.itemid, i.itemrate from vwgdnbincard s,
vwitemdescription vw, aITEM i, aGodown G where s.itemid = vw.itemid
and s.GDate=@dtDate and i.itemid = s.itemid and i.itemrate=0
and s.Godownid = g.GodownId and g.Departmentid = @intDepId) zerorate
else
select distinct zerorate.itemdescription, zerorate.itemid, zerorate.itemrate from
( select distinct vw.itemdescription,vw.itemid, i.itemrate from  vwshopbincardaudit s,
vwitemdescription vw, aITEM i where s.itemid = vw.itemid
and s.sdate = @dtDate and i.itemid = s.itemid and i.itemrate=0
union all
select distinct vw.itemdescription,vw.itemid, i.itemrate from vwgdnbincard s,
vwitemdescription vw, aITEM i where s.itemid = vw.itemid
and s.GDate=@dtDate and i.itemid = s.itemid and i.itemrate=0
) zerorate' 
END
GO
/****** Object:  View [dbo].[vwLocalPurchaseInvoiceDetails]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseInvoiceDetails]'))
EXEC dbo.sp_executesql @statement = N'
-- 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
/****** Object:  View [dbo].[vwShopBinCardAuditCustWise]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAuditCustWise]'))
EXEC dbo.sp_executesql @statement = N'
----Created By   : Prasanth joseph
----Created on   : 05-05-2008
----Created for  : To get Bincard Audit Report Accoding to Customer
---------------------------------------------------------------------------------------------------
----Modified By  : Benzigar S D
----Modified On  : 16-09-2009
----Comment      : Modified sellingpriceperunit in POS and Credit Invoice Part
--------------------------------------------------------------------------------
--Modified by          : Nidheesh P V
--Modified on          : 6/07/2011
--Comments             : Added In-House Consumption part seperately.
--Modified Area        : All Interfaces where stock effects
--Referenc No          : Ref-No1
--------------------------------------------------------------------------------
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U
-- Modified on	: 26/03/2012
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- -----------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwShopBinCardAuditCustWise] AS
select shopid, itemid, sdate , Transno, TransID ,Transqty, Type, mode,updatetime, Costprice,
DepCostprice,ConCostprice,CustomerName,SellingPrice,sellingperUnit,Margin,CustID
from
--arrival from godown
(select h.gahshopid shopid, d.gaditemid itemid, h.gaharrivaldate sdate,
h.gaharrivalid Transid, h.gaharrivalno Transno,
convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,
''Arrival From Godown'' Type, 1 mode,updatetime,gadCostprice CostPrice,
gadCostPrice * gahdepexrate depCostPrice, gadCostPrice * gahconexrate ConCostPrice,'''' CustomerName ,0 SellingPrice ,0 sellingperUnit,0 Margin,'''' CustID from
losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d where
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1 group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,
gaharrivalno, d.gaditemid,updatetime, gadCostprice, gahdepexrate, gahconexrate
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,
GrnhGoodsreturnnoteID transid, GrnhGoodsreturnnoteNO transno, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,
''Goods Return'',1 as mode,updatetime, grncostprice,
grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,grnhCustomerID CustID from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0
union all
--transfer in
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihid, h.tihno,
convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, ''Transfer In'' TYpe, 1 mode,
updatetime, tidCostPrice, tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,
tihdepexrate, tihconexrate
union all
--recovery add
select sr.srshopid, sr.sritemid, sr.srdate sdate, sr.srid,
''Rec'' + convert(varchar(50), sr.srid) srno,
convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, ''Recovery Plus'' Type,
1 Mode,updatetime, srCostPrice,
srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice
,'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID  from
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid, svhDate sdate, svhid, svhno,
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,
''Verification Plus'' Type, 1 mode,updatetime, svdCostPrice,
svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0 group by   svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate, svhconexrate
union all
--exchange in
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeid, sehexchangeno,
convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, ''Exchanged In'' Type,
1 mode,updatetime, sedCostPrice,
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID    from
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPrice, sehDepExrate, sehExchangerate
union all
--local purchase
select lphShopid, lpditemid, lphbilldate, lphBillid, lphBillNo,
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,''Local Purchase'' Type, 1 mode,updatetime,
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice,'''' CustomerName,0 SellingPrice,0 sellingperUnit,
	0 Margin,'''' CustID
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphconfirmed=1 --<<Ref-No2>>
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,
	lphdepexrate,lphExchangerate
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whid, wh.whno,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, ''Write off'' TYpe, -1 mode,
updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype<>''I''   --Ref-No1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--In-House Cons  --Ref-No1
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whid, wh.whno,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, ''In-House Cons'' TYpe, -1 mode,
updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype=''I'' and whVerified=1
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Deapatch
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghid, dh.dghNo,
convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,
''Despatch To Godown'' TYpe, -1 mode,updatetime, dgdCostPrice,
dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 MArgin,'''' CustID
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,
dgdCostPrice, dghdepexrate, dghconexrate
union all
--Transferout
select todshopid, toditemid, tohDate sdate, tohid, tohno,
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty , ''Transfer Out'' Type,
-1 mode,updatetime, todCostPrice,
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 MArgin,'''' CustID
from mestransferoutheader , mestransferoutdetail  where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,
tohdepexrate, tohConExrate
union all
--recovery minus
select sr.srshopid, sr.sritemid, sr.srdate sdate, sr.srid,
''Rec'' + convert(varchar(50), sr.srid) srno,
convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, ''Recovery Minus'' type,
1 Mode, updatetime, srCostPrice,
srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID from
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhid, svhno,
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,
''Verification Minus'' type, -1 mode,updatetime, svdCostPrice,
svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--pos sales
select poshShopID, posditemid, poshBilldate sdate, poshbillid, poshBillNo,
convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,
''Cash Sales'' as type, -1 mode,updatetime, posdCostPrice,
posdCostPrice * poshdepexrate depCostPrice,
posdCostPrice * poshExchangeRate ConCostPrice,
poshCustomerName CustomerName,posdUnitPrice SellingPrice,
--posdBlockPrice sellingperUnit,   ''benzigar 16/09/2009 commented this and added the below
posdUnitPrice/posdQuantity  sellingperUnit,
case   posdUnitPrice when 0 then 0
else
((posdUnitPrice-(posdCostPrice * poshExchangeRate))/posdUnitPrice)*100  end Margin,'''' CustID
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0 group by
poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate,poshCustomerName ,posdUnitPrice,posdBlockPrice,
posdQuantity    -- benzigar 16/09/2009 added
union all
--credit invoice
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceid, ihInvoiceNo,
convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, ''Credit Sales'' Type,
-1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,
idCostPrice * ihExchangeRate ConCostPrice,
CustomerName,idUnitPrice SellingPrice,
--idBlockPrice sellingperUnit, ''benzigar 16/09/2009 commented this and added the below
idUnitPrice/idQuantity sellingperUnit,
case idUnitPrice when 0 then 0
else ((idUnitPrice-(idCostPrice * ihExchangeRate))/idUnitPrice)*100 end Margin,ihCustomerID CustID
from losinvoicedetail,losinvoiceheader,aCustomerMaster
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''I'' and ihCustomerID=CustomerID group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,
updatetime, idCostPrice, ihdepexrate, ihExchangeRate,CustomerName,idUnitPrice,idBlockPrice,ihCustomerID,
idQuantity  -- benzigar 16/09/2009 added
union all
--exchange out
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeid, sehexchangeno,
convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,
''Exchange Out'' Type, -1 mode,updatetime, sedCostPRice,
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPRice, sehdepexrate, sehExchangerate
union all
--special invoice return to shop
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceid, ihInvoiceNo,
convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, ''Special Invoice Return'' Type,
1 mode,updatetime, idCostPrice,
idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin, ihCustomerID CustID
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1 group by ihshopid, ihinvoicedate, ihInvoiceid,
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate,ihCustomerID
-- transfinished added as stock is updated only after confirming
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select serinvhShopid, repinvdpartsid, serinvhdate , serinvhid , serinvNo ,
convert(numeric(18,3) , sum(repinvdqty)) , ''Parts Replaced'' type,
-1 as mode, serinvhupdatetime, repinvdcostprice,
repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,
'''' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,
serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate
union all
--Re-Exporting
select rehShopID, reditemid, rehExportDate sdate, rehExportID, rehExportNo,
convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, ''Re-Export'' Type,
-1 mode, rehUpdatetime, redCostPrice,
redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,
'''' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'''' CustID
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''I'' group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate
union all
-----Hire Purchase Invoice
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationID,hpqhQuotationNo,1 as Qty, ''Hire Purchase'' Type,
-1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,
CustomerName CustomerName,hpqdSellingPrice SellingPrice,hpqdSellingPrice sellingperUnit,((hpqdSellingPrice-hpqdCostPrice)/hpqdSellingPrice)*100 Margin,hpqhCustomerID CustID
from loshpInvoiceDetail,losHpInvoiceHeader,acustomerMAster where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I'' and CustomerID=hpqhCustomerID group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,
hpqhUpdatetime,hpqdCostPrice,CustomerName,hpqdSellingPrice,hpqdSellingPrice,hpqhCustomerID)
shopbin
group by shopid, itemid, sdate , Transno, TransID , Transqty, Type, mode,updatetime, Costprice,depcostprice,concostprice,CustomerNAme,SellingPrice,Margin,CustID,sellingperUnit'
GO
/****** Object:  View [dbo].[vwShopBincardAudit_new]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit_new]'))
EXEC dbo.sp_executesql @statement = N'
--sp_helptext vwshopbincardaudit
-- Modified By   : Benzigar 23092008
-- Modified Date : 23092008
-- Comment       : Added Business Promotion/Warrenty claim
-- =====================================
-- Upgraded By : Regin T.
-- Upgraded On : 22-07-2010
-- Upgrade     : An outer Group By clause was used to change
--   the position of TransId and TransNo fields.
--   This Group By clause casued delay. So I removed it, and
--   changed the position of fields in all union all parts.
--   Old position: TransId, TransNo
--   New position: TransNo, TransId
-- =====================================
-- Upgraded By : Regin T.
-- Upgraded On : 18-09-2010
-- Upgrade     : Added FandB Bill
-- =====================================
-- Upgraded By : NIDHEESH P.V.
-- Upgraded On : 09-02-2011
-- Upgrade     : Added In-House Return
-- =====================================
--------------------------------------------------------------------------------
-- Modified by          : MANUNADH.U ON : 11/05/2011
-- Comments             : Added the column From/To for Bincard Audit report
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011
-- Comments             : Bug fixed in transfer out
--------------------------------------------------------------------------------
-- Referenc No  : Ref-No1
-- Modified by	: MANUNADH.U
-- Modified on	: 26/03/2012
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ------------------------------------------------------------------------------
create VIEW [dbo].[vwShopBincardAudit_new] AS
--arrival from godown
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,
convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,''Arrival From Godown'' [Type],
1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,
gadCostPrice * gahconexrate ConCostPrice,
--(case when g.GodownName IS null then ''HQ'' else g.GodownName end  + ''/'' + s.ShopName)  as ''From/To''
(case when g.GodownName IS null then ''HQ'' else g.GodownName end  )  as ''From/To''
from losgoodsarrivaltoshopheader h
left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID
left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1
AND gaharrivaldate >=''20100101'' and gaharrivaldate<=''20110131'' --and h.gahshopid=5
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,
gahdepexrate, gahconexrate,g.GodownName,s.ShopName
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,
GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,''Goods Return'',1 as mode,
updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,
'''' as ''From/To''
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0
and GRNDDamaged=0
union all
--transfer in
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,
convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, ''Transfer In'' TYpe, 1 mode,updatetime, tidCostPrice,
tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as ''From/To''
from lostransferinheader h
left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,
tihdepexrate, tihconexrate,s.ShopName
union all
--recovery add
select sr.srshopid, sr.sritemid, sr.srdate sdate, ''Rec'' + convert(varchar(50), sr.srid) srno, sr.srid,
convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, ''Recovery Plus'' Type,1 Mode,updatetime,
srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'''' as ''From/To''
from losstockrecovery sr
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate
having isnull(sum(sr.sraddstock),0) >0
union all
--stock verification add
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,''Verification Plus'' Type, 1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and
left(svhFutureVc, 1) <> ''t''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate
union all
--TOTAL stock verification add
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,''Verification Plus'' Type, 1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and
left(svhFutureVc, 2) = ''tc''
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate
union all
--exchange in
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,
convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, ''Exchanged In'' Type,1 mode,updatetime,
sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'''' as ''From/To''
from losposexchangeheader, losposexchangedetail
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPrice, sehDepExrate, sehExchangerate
union all
--local purchase
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,''Local Purchase'' Type, 1 mode,updatetime,
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'''' as ''From/To''
from loslocalpurchasedetail, loslocalpurchaseheader
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1 --<<Ref-No1>>
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,
	lphdepexrate,lphExchangerate
union all
--write off
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, ''Write off'' TYpe, -1 mode,updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'''' as ''From/To''
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Despatch
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghNo, dh.dghid,
convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,''Despatch To Godown'' TYpe, -1 mode,updatetime,
dgdCostPrice,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice
,g.GodownName  as ''From/To''
from mesdespatchtogodownheader dh
left outer join aGodown g on g.GodownID=dh.dghGodownID,mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,
dgdCostPrice, dghdepexrate, dghconexrate,g.GodownName
union all
--Transferout
select todshopid, toditemid, tohDate sdate, tohno, tohid,
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty ,
''Transfer Out'' Type,-1 mode,updatetime, todCostPrice,
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as ''From/To''
from mestransferoutdetail inner join mestransferoutheader h
on tohid=todid and Tohshopid=todshopid and tohcancelled=0 and tohtransfinished = 1 inner join
ashops s on s.ShopID=h.TOHtoShopid --inner join lostransferindetail on TODitemid=TIDitemID
where TOHShopid=5 and TODitemid=8626
group by todissuedgoodqty,tohid,todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,
tohdepexrate, tohConExrate,s.ShopName
union all
--recovery minus
select sr.srshopid, sr.sritemid, sr.srdate sdate,''Rec'' + convert(varchar(50), sr.srid) srno, sr.srid,
convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, ''Recovery Minus'' type,-1 Mode, updatetime,
srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'''' as ''From/To''
from losstockrecovery sr
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,''Verification Minus'' type, -1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice
,'''' as ''From/To''
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--Total stockverification minus
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,''Verification Minus'' type, -1 mode,
updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,
'''' as ''From/To''
from losstockverificationheader,losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,
svdCostPrice, svhdepexrate , svhconexrate
union all
--pos sales
select poshShopID, posditemid, poshBilldate sdate, poshBillNo, poshbillid,
convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,''Cash Sales'' as type, -1 mode,updatetime,
posdCostPrice,posdCostPrice * poshdepexrate depCostPrice,posdCostPrice * poshExchangeRate ConCostPrice
,'''' as ''From/To''
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
group by poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate
union all
--credit invoice
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,
convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, ''Credit Sales'' Type,
-1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,
idCostPrice * ihExchangeRate ConCostPrice,'''' as ''From/To''
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0 and ihType =''I''
group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,
updatetime, idCostPrice, ihdepexrate, ihExchangeRate
union all
--exchange out
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,
convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,
''Exchange Out'' Type, -1 mode,updatetime, sedCostPRice,
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'''' as ''From/To''
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,
sedCostPRice, sehdepexrate, sehExchangerate
union all
--special invoice return to shop
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,
convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, ''Special Invoice Return'' Type,
1 mode,updatetime, idCostPrice,
idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,'''' as ''From/To''
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
group by ihshopid, ihinvoicedate, ihInvoiceid,
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate
-- transfinished added as stock is updated only after confirming
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select serinvhShopid, repinvdpartsid, serinvhdate , serinvNo, serinvhid,
convert(numeric(18,3) , sum(repinvdqty)) , ''Parts Replaced'' type,-1 as mode, serinvhupdatetime, repinvdcostprice,
repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,'''' as ''From/To''
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,
serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate
union all
--Re-Exporting
select rehShopID, reditemid, rehExportDate sdate, rehExportNo, rehExportID,
convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, ''Re-Export'' Type,
-1 mode, rehUpdatetime, redCostPrice,
redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,'''' as ''From/To''
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0 and rehType=''I''
group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate
union all
--MerGing minus
select lsdShopID, lsdItemID, lshDate, lshno, lshid,convert(numeric(18,3), sum(lsdqty)) as mergeded,
''Merging Deduct'' as type, -1 as mode, lshUpdatetime,null,null,null,'''' as ''From/To''
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid and md.lsdShopid = mh.lshShopId and lshCancelled=0
group by lsdShopID, lsdItemID, lshDate, lshid, lshno, lshUpdatetime
Having Sum(lsdQty) <> 0
union all
--MerGing Add
select lsdShopID, lshItemID, lshDate, lshno, lshid,convert(numeric(18,3),sum(lsdqty)) as splitminus,
''Merging Add'' as type, 1 as mode, lshUpdatetime,null,null,null,'''' as ''From/To''
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid and md.lsdShopID = mh.lshShopid and lshCancelled = 0
group by lsdShopID, lshItemID, lshDate, lshid, lshno, lshUpdatetime
Having Sum(lsdQty) <> 0
union all
--Purchase Return
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whno, Ph.whid,
convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, ''Purchase Return'' TYpe, -1 mode,
updatetime, wdCostPrice,
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'''' as ''From/To''
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1
group by Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime, wdCostPrice,
whDepExrate, whConExrate
union all
--Warrenty Claim/Business promotion
select wchShopID, wcditemid, wchdate sdate, wchNo, wchid,convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,
''WC/BP'' as type, -1 mode,wchupdatedtime, wcdCostPrice,wcdCostPrice * wchdepexrate depCostPrice,
wcdCostPrice * wchcomexrate ConCostPrice,'''' as ''From/To''
from losWarrentyClaimDetail,losWarrentyClaimHeader
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0
group by wchShopid, wchid, wchNo, wchdate, wchid, wchNo,
wcditemid,wchupdatedtime, wcdCostPrice, wchdepexrate, wchcomexrate
union all
-----Hire Purchase Invoice
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationNo,hpqhQuotationID,1 as Qty, ''Hire Purchase'' Type,
-1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,'''' as ''From/To''
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I''
group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,hpqhUpdatetime,hpqdCostPrice
union all
-- Food and Beverages Bill - added by Regin on 18-09-2010
SELECT Fb_kh_outletid, a.fb_ItemID, DATEADD(D, 0, DATEDIFF(D, 0, Fb_kh_kotdatetime)) sdate,Fb_kh_kotno, Fb_kh_kotid,
a.KotOrder,''FandB Bill'' Type, -1 mode, Fb_kh_kotdatetime,fb_costprice, fb_costprice*h.fb_depexrate depCostPrice,
fb_costprice*h.fb_ExchangeRate conCostPrice,'''' as ''From/To''
from fb_kotheader h
inner join fb_alternate a on Fb_kh_kotid=fb_kotID
where Fb_kh_cancelled=0
union all
--InHouse Return
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,
convert(numeric(18,3),sum(IHRDReturnedqty)) as IHRDReturnedqty,''In-House Return'' Type,1 mode,updatetime,
IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice
,'''' as ''From/To''
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1
AND (IHRDRetrnOrExch=''R'' OR IHRDRetrnOrExch=''B'' OR IHRDRetrnOrExch IS NULL) AND IHRDReturnedqty<>0
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,
IHRDcostprice,IHRHdepexrate,IHRHconexrate
UNION ALL
--InHouse Exchanged In
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,
convert(numeric(18,3),sum(IHRDArrivedQty)) as IHRDExchgdqty,''In-House Exchnaged In'' Type,-1 mode,updatetime,
IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice,'''' as ''From/To''
FROM LOs_InHouseCons_ReturnHeader rh
INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND
IHRHConfirmed=1 AND IHRDRetrnOrExch=''E'' AND IHRDArrivedQty<>0
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,IHRDcostprice,IHRHdepexrate,IHRHconexrate'
GO
/****** Object:  View [dbo].[vwDistributeWriteoff]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDistributeWriteoff]'))
EXEC dbo.sp_executesql @statement = N'
/*
------------------------------------------------------------------------------------------------------------------------
--Created by    :  Shinu
--Created On :  31/03/2008
--Comments      :  For  vwDistributeWriteoff Preview
------------------------------------------------------------------------------------------------------------------------
--Modified By   :
--Modified On   :
------------------------------------------------------------------------------------------------------------------------
*/
CREATE view [dbo].[vwDistributeWriteoff]  as
---shop arrival
select
dsTransId, dsTransCode,dstransdate,dsitemid,a.itemcode,a.itemdescription,dstoadd, dstodeduct,
shopname Location,d.dstoshopid,s.departmentid,
sd.gadItemGoodQuantity,case when dstoadd > 0 and dstodeduct=0 then sd.gadItemGoodQuantity-dstoadd else sd.gadItemGoodQuantity+dstodeduct end ReceivedQuantity,
u.UnitName
from medifferenceinstock d inner join ashops s   on  d.dstoshopid = s.shopid
inner  JOIN LOsGoodsArrivaltoShopHeader h ON d.dstransid=h.gahArrivalID and d.dstoshopid=h.gahShopid
and  dsfromgodownid = 0 and dsfromshopid = 0 and dstogodownid = 0
inner  JOIN LOsGoodsArrivaltoShopDetail sd ON h.gahArrivalID=sd.gadArrivalID
AND h.gahShopid=sd.gadShopid and d.dsItemid=sd.gaditemid
inner join aitem a on a.itemid=d.dsItemid inner join aunit u on u.UnitID=a.UnitsID
where
dsfromgodownid = 0
and dsfromshopid = 0
and dstogodownid = 0
and gahCancelled=0
and (dstoadd<>0 or dstodeduct<>0)
union all
---any godown arrival
select dsTransId, dsTransCode,dstransdate,dsitemid,a.itemcode,a.itemdescription, dstoadd, dstodeduct,
godownname Location,d.dstogodownid,h.ahdepartmentid,
ad.despacthedqty,case when dstoadd >0 and  dstodeduct=0 then ad.despacthedqty-dstoadd else ad.despacthedqty+dstodeduct end receivedQuantity,
u.UnitName
from medifferenceinstock d INNER JOIN agodown g  ON d.dstogodownid = g.godownid
INNER JOIN LOiArrivalHeader h ON d.dstransid=h.ahArrivalID and d.dstogodownid=h.ahLocalGodownID
INNER JOIN vwloiarrivaldetail ad ON h.ahArrivalID=ad.adArrivalID and h.ahLocalGodownID=ad.adGodownID
INNER JOIN aitem a on a.itemid=d.dsItemid inner join aunit u on u.UnitID=a.UnitsID
where
dsfromgodownid = 0
and dsfromshopid = 0
and dstoshopid = 0
and ahCancelled =0
and (dstoadd<>0 or dstodeduct<>0)
union all
----transferin
select dsTransId, dsTransCode,dstransdate,dsitemid,a.itemcode,a.itemdescription, dstoadd, dstodeduct,
shopname Location,d.dstoshopid,s.departmentid,
sd.TIDtransfergoodqty,case when dstoadd >0 and  dstodeduct=0 then sd.TIDtransfergoodqty-dstoadd else sd.TIDtransfergoodqty+dstodeduct end receivedQuantity,
u.UnitName
from medifferenceinstock d inner join ashops s on  d.dstoshopid = s.shopid
inner join LOSTransferinheader h on d.dstransid=h.TIHID and d.dstoshopid=h.TIHShopid
inner join LOSTransferinDetail sd on h.TIHID=sd.TIDID and h.TIHShopid=sd.TIDshopid
inner join aitem a on d.dsItemid=a.itemid inner join aunit u on u.UnitID=a.UnitsID
where
dsfromgodownid = 0
and dsfromshopid = 0
and dstogodownid = 0
and TIHcancel = 0
and (dstoadd<>0 or dstodeduct<>0)'
GO
/****** Object:  View [dbo].[vwarrivaldistributedetails]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwarrivaldistributedetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwarrivaldistributedetails    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwarrivaldistributedetails    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwarrivaldistributedetails    Script Date: 31/07/2002 2:00:31 PM ******/
CREATE view [dbo].[vwarrivaldistributedetails] as
select  ahArrivalID,''Arrival from HQ'' as transtype ,''HQ'' fromloc,a.godownname,
ahArrivalNo,ahArrivalDate,ahRemarks,aditemid,''H'' type,ahLocalGodownID LocID
from loiarrivalheader lh,loiarrivaldetail ld, agodown a where
lh.ahArrivalID=ld.adArrivalID and lh.ahLocalGodownID = adGodownID
and adDespatchedQty<>adReceivedQty and a.godownid=lh.ahLocalGodownID
and lh.ahArrivalType = ''H'' --order by ahArrivalID
union all
select  ahArrivalID,''Arrival from Godown'' as transtype,b.godownname,
a.godownname,ahArrivalNo,ahArrivalDate,ahRemarks,asdItemID,''G'',ahLocalGodownID LocID
from loiarrivalheader lh,LOiArrivalShipmentDetail ld,agodown a,agodown b where
lh.ahArrivalID=ld.asdArrivalID and lh.ahLocalGodownID = asdGodownID
and a.godownid=lh.ahLocalGodownID and b.godownid=lh.ahGodownID
and lh.ahArrivalType = ''G'' and asdReceivedGoodQty <> asdDespatchedgoodQty --order by ahArrivalID
union all
select  ahArrivalID,''Arrival from Shop'' as transtype,s.shopname,a.godownname,
ahArrivalNo,ahArrivalDate,ahRemarks,asdItemID,''S'',ahLocalGodownID LocID
from loiarrivalheader lh,LOiArrivalShipmentDetail ld,agodown a,ashops s where
lh.ahArrivalID=ld.asdArrivalID and lh.ahLocalGodownID = asdGodownID and
s.shopid=ahshopid
and a.godownid=lh.ahLocalGodownID
and lh.ahArrivalType = ''S'' and asdReceivedGoodQty <> asdDespatchedgoodQty-- order by ahArrivalID
union all
select  TIHID,''Transfer In'' as transtype,s.shopname,s1.shopname,TIHNO,TIHDate,
TIHremarks,TIDitemID,''T'',lth.TIHShopid
from lostransferinheader lth,
lostransferindetail ltd,ASHOPS S,ashops s1  where
lth.TIHID=ltd.TIDID and lth.TIHShopid=ltd.TIDshopid and LTH.TIHfromshopID=S.SHOPID
and s1.shopid=lth.TIHShopid and TIDtransfergoodqty<>TIDrecievedgoodqty
union all
select  gahArrivalID,''Arrival from Godown'' as transtype, a.godownname,s.shopname,
gahArrivalNo,gahArrivalDate,gahremarks,gadItemID,''A'',gahShopid from losgoodsarrivaltoshopheader agh,
losgoodsarrivaltoshopdetail agd,agodown a,ashops s where
agh.gahArrivalID=agd.gadArrivalID and gahShopid=gadShopid and
gahDespatchedGodownID=a.godownid and gahShopid=s.shopid and
gadItemGoodQuantity<>gadItemGoodQuantityArrived'
GO
/****** Object:  StoredProcedure [dbo].[spCurrentShopStock]    Script Date: 10/06/2012 14:17: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].[spCurrentShopStock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- This Stored Procedure returns the current shop stock of given item.
-- This sp was created to speed up the process of finding the current stock.
-- This sp was created to replace already availabe view vwInquiryshopstock.
--------------------------------------------------------------------------------
-- INPUT
-- @intShopID - Shop ID
-- @intItemID - Item ID
-- @intPackID - Packing ID of given item
-- OUTPUT
-- ItemQty    - Current Item Stock in a given shop
-- PackQty    - Current Package Quantity of given item
--------------------------------------------------------------------------------
-- Written By: Regin
-- Written On: 10/02/2009
-- spCurrentShopStock 11, 6, 1
--------------------------------------------------------------------------------
-- Modified By: Nidheesh P V
-- Modified on : 23/02/10
-- Comments : added the cases  1) --MerGing minus --2)MerGing Add
--    --3)Warrenty Claim/Business promotion-----4)Hire Purchase Invoice
---these 4 cases were included in vwShopBinCardAudit
--------------------------------------------------------------------------------
-- Modified By: Regin
-- Modified On: 21/07/2010
-- Added Shop Transactions Summary part to increase the speed.
-- Also, @dtSummaryDate filtering was added to all portions.
--------------------------------------------------------------------------------
-- Ref.No.01
-- Modified By: Aadyakumar.D.V
-- Modified On: 27/07/2011
-- Correct the quantity in Merging
--------------------------------------------------------------------------------
-- Ref.No.02
-- Modified By: Aadyakumar.D.V
-- Modified On: 18/01/2012
-- Addeed whVerified=1 flag in stock write off :TWX-800461
--------------------------------------------------------------------------------
-- Ref.No-03
-- Modified By: Bijesh.B
-- Modified On: 23/01/2012
-- Ticket id  : JJC-787172
--------------------------------------------------------------------------------
-- Ref.No-04
-- Modified By: MANUNADH.U
-- Modified On: 27/02/2012
-- Ticket id  : IKF-161540
-- Add Total stockverification minus. Otherwise stock shows wrong after do item merging.
--------------------------------------------------------------------------------
-- Ref.No-05
-- Modified By: SHINE DAS
-- Modified On: 29/02/2012
-- Write Off and Inhouse cons uses same table. And only inhouse Cons uses the verify bit. So
-- Current code is splitted into two and added transaction type checking.
--------------------------------------------------------------------------------
-- Ref.No-06
-- Modified By : BIJESH.B
-- Modified On : 21/03/2012
-- Ticket id   : VFB-632819 (SOSUN FIHARA)
-- Desc        : -ve stock is showing in pos cash sales
--------------------------------------------------------------------------------
CREATE procedure [dbo].[spCurrentShopStock]
@intShopID integer,
@intItemID integer,
@intPackID integer = 0
as
begin
declare @numItemQty as numeric(18,3)    -- Item Quantity
declare @numPackQty as numeric(18,3)   -- Package Quantity
declare @numPackCapacity as numeric(18,3) -- Packing Capacity
DECLARE @dtSummaryDate AS DATETIME     -- Date of transaction summary
DECLARE @bitTransSummary as bit
DECLARE @SummaryStock AS NUMERIC(18,3)
set @numPackQty = 0 -- If @intPackID input is not provided, @numPackQty will remain 0.
-- If Transactions Summary is enabled,
--   1. Set filter date to summary date.
--   2. Get summary stock from summary table.
SELECT @bitTransSummary=TransactionsSummary from aPackageSettings
IF @bitTransSummary = 1
BEGIN
select @dtSummaryDate=isnull(TransactionsSummaryDate,''19000101'') from aPackageSettings
select @SummaryStock=Stock from losShopTransactionsSummary
where ShopId=@intShopID and ItemId=@intItemID
END
ELSE
BEGIN
SELECT @dtSummaryDate=''19000101''
select @SummaryStock=0
END
select @numItemQty = sum(stock * mode) from
(
-- for vwInquiryShopStock
-- SHOP TRANSACTIONS SUMMARY
select @SummaryStock stock, 1 mode
union all
-- OPENING STOCK
select  isnull(openingstock,0) stock, 1 mode
from
mosshopstock
where shopid = @intShopID and itemid = @intItemID and StockDate>@dtSummaryDate
union all
-----------------------------------------------------------------------------------------------
-- vwShopBinCardAudit portion begins
--Arrival from godown
select convert(numeric(18,3),isnull(d.gadItemGoodQuantityArrived,0)) TransQty, 1 mode
from losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d
where
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1
and h.gahshopid = @intShopID and d.gaditemid = @intItemID
and h.gaharrivaldate>@dtSummaryDate
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,
1 as mode
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0
and grn.grnhShopid = @intShopID and grd.GRNDItemID = @intItemID
and GrnhGoodsreturnnoteDate>@dtSummaryDate
union all
--transfer in
select convert(numeric(18,3),isnull(d.TIDrecievedgoodqty,0)) as TinQty, 1 mode
from lostransferinheader h, lostransferindetail d
where
h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
and h.tihshopid = @intShopID and d.tiditemid = @intItemID
and h.tihdate>@dtSummaryDate
union all
--recovery add
select convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 1 Mode
from
losstockrecovery sr group by  sr.srshopid, sr.sritemid, sr.srdate
having isnull(sum(sr.sraddstock),0) >0
and sr.srshopid = @intShopID and sr.sritemid = @intItemID
and sr.srdate>@dtSummaryDate
union all
--stock verification add
select convert(numeric(18,3),isnull(svdVerifiedStock-svdAvailStock, 0)) as svAddQty, 1 mode
from  losstockverificationheader, losstockverificationdetail
where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0
and svdshopid = @intShopID and svdItemid = @intItemID
and svhDate>@dtSummaryDate
and  left(svhFutureVc, 1) <> ''t'' -- Ref.No-06 added
-- Ref.No-06 start (updated from vwShopBincardAudit)
union all
--TOTAL stock verification add
select convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty, 1 mode
from  losstockverificationheader, losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and
svdshopid = @intShopID and svdItemid = @intItemID and svhDate>@dtSummaryDate  and
left(svhFutureVc, 2) = ''tc''
-- Ref.No-06 ends
union all
--exchange in
select convert(numeric(18,3),isnull(sedExchangeQty,0))  as exchangedin, 1 mode
from
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
and sehShopID = @intShopID and seditemid = @intItemID
and sehExchangeDate>@dtSummaryDate
union all
--local purchase
select convert(numeric(18,3),isnull(lpdItemQuantity,0)) localpurchase, 1 mode
from loslocalpurchasedetail, loslocalpurchaseheader where lphBillId=lpdBillID and
lphShopID= lpdShopid and lphCancelled=0
and lphShopid = @intShopID and lpditemid = @intItemID
and lphbilldate>@dtSummaryDate
union all
--write off
select convert(numeric(18,3),isnull(wd.wdWriteoffQty, 0)) as writeoffqty, -1 mode
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
--and whVerified=1 -- Ref.No.02       -- Ref.No-05 Commented
and whtype=''W''                 -- Ref.No-05 Added
and wh.whshopid = @intShopID and wd.wditemid = @intItemID
and wh.whdate>@dtSummaryDate
union all
--Inhouse Consuption      (Newly added snippet -- Ref.No-05)
select convert(numeric(18,3),isnull(wd.wdWriteoffQty, 0)) as writeoffqty, -1 mode
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
and whVerified=1 -- Ref.No.02
and whtype=''I''
and wh.whshopid = @intShopID and wd.wditemid = @intItemID
and wh.whdate>@dtSummaryDate
union all
--Despatch
select convert(numeric(18,3),isnull(dd.dgddespatchedgoodqty,0)) as despatchqty,-1 mode
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
and dd.dgdshopid = @intShopID and dd.dgditemid = @intItemID
and dh.dghDate>@dtSummaryDate
union all
--Transferout
select convert(numeric(18,3),isnull(todissuedgoodqty,0)) as ToutQty , -1 mode
from mestransferoutheader , mestransferoutdetail
where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
and todshopid = @intShopID and toditemid = @intItemID
and tohDate>@dtSummaryDate
union all
--recovery minus
select convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd,-1 Mode
from
losstockrecovery sr
where sr.srshopid = @intShopID and sr.sritemid = @intItemID
and sr.srdate>@dtSummaryDate
group by  sr.srshopid, sr.sritemid
having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select convert(numeric(18,3),isnull(svdAvailStock-svdVerifiedStock, 0)) as svMinusQty,-1 mode
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0
and  svdshopid = @intShopID and svdItemid = @intItemID
and svhDate>@dtSummaryDate
and  left(svhFutureVc, 1) <> ''t''    -- Ref.No-03 added (taken from vwInquiryshopstock)
union all
-- Ref.No-06 start commented below and added (updated from vwShopBincardAudit)
----Total stockverification minus   <<Ref.No-04 >>
--select convert(numeric(18,3),isnull(svdAvailStock-svdVerifiedStock, 0)) as svMinusQty,-1 mode
--from  losstockverificationheader, losstockverificationdetail where
--svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
--and svhCancelled=0
--and  svdshopid = @intShopID and svdItemid = @intItemID
--and svhDate>@dtSummaryDate
--and  left(svhFutureVc, 1) <> ''tc''
----Total stockverification minus
select convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty, -1 mode
from losstockverificationheader,losstockverificationdetail
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0
and  svdshopid = @intShopID and svdItemid = @intItemID
and svhDate>@dtSummaryDate
and  left(svhFutureVc, 2) = ''tc''
-- Ref.No-06 ends
union all
--pos sales
select convert(numeric(18,3),isnull(posdquantity,0)) cashsales, -1 mode
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
and poshShopID = @intShopID and posditemid = @intItemID
and poshBilldate>@dtSummaryDate
union all
--credit invoice
select convert(numeric(18,3),isnull(idquantity,0)) as creditsales, -1 mode
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''I''
and ihshopid = @intShopID and iditemid = @intItemID
and ihInvoicedate>@dtSummaryDate
union all
--exchange out
select convert(numeric(18,3),isnull(sedquantity,0))  as exchangedout, -1 mode
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
and sehShopID = @intShopID and seditemid = @intItemID
and sehExchangeDate>@dtSummaryDate
union all
--special invoice return to shop
select convert(numeric(18,3),-(isnull(reqqty,0))) as SpecialReturn, 1 mode
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
-- transfinished added as stock is updated only after confirming
and IhShopid = @intShopID and iditemid = @intItemID
and ihInvoicedate>@dtSummaryDate
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select convert(numeric(18,3) , isnull(repinvdqty,0)), -1 as mode
from losinvoicedpartsreplacedetails, losserviceinvheader
where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
and serinvhShopid = @intShopID and repinvdpartsid = @intItemID
and serinvhdate>@dtSummaryDate
union all
--Re-Exporting
select convert(numeric(18,3),isnull(redquantity,0)) as creditsales, -1 mode
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''I''
and rehShopID = @intShopID and reditemid = @intItemID
and rehExportDate>@dtSummaryDate
union all
--MerGing minus
-- Ref.No.01---starts---
select convert(numeric(18,3), sum(lsdqty)) as mergeded, 1 as mode
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopid = mh.lshShopId
and lshCancelled=0
and lshShopID = @intShopID and lshItemID = @intItemID
and lshDate>@dtSummaryDate
Having Sum(lsdQty) <> 0
union all
--MerGing Add
select convert(numeric(18,3),sum(lsdqty)) as splitminus,-1 as mode
from losMergeDetails md, losMergeHeader mh
where md.lsdid = mh.lshid
and md.lsdShopID = mh.lshShopid
and lshCancelled = 0
and lshShopID = @intShopID and lsdItemID = @intItemID
and lshDate>@dtSummaryDate
Having Sum(lsdQty) <> 0
-- Ref.No.01---end---
union all
--Purchase Return
select convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, -1 mode
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid
and Ph.whcancelled=0 and Ph.whtransfinished=1
and Ph.whshopid=@intShopID and Pd.wditemid=@intItemID
and Ph.whdate>@dtSummaryDate
union all
--Warrenty Claim/Business promotion
select convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,-1 mode
from losWarrentyClaimDetail,losWarrentyClaimHeader
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0
and wchShopID = @intShopID and wcdItemID = @intItemID
and wchdate>@dtSummaryDate
union all
-----Hire Purchase Invoice
select 1 as Qty,-1 mode
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and
hpqhCancel=0 and hpqhType=''I'' and hpqhShopID = @intShopID and hpqdItemID = @intItemID
and hpqhQuotationDate>@dtSummaryDate
-- vwShopBinCardAudit portion ends
-----------------------------------------------------------------------------------------------
) a
if @intPackID <> 0   -- If Packing ID is given while calling the SP, find the Packing Qty
begin
-- TO FIND THE CAPACITY OF GIVEN PACKING TYPE
select @numPackCapacity = Quantity from aPackingTypeCapacityDetail
where PackingTypeID = @intPackID and UnitsID
in (select UnitsID from aItem where ItemID = @intItemID)
--------------------------------------------------------------------------------
-- TO FIND THE PACKAGE QUANTITY OF GIVEN ITEM
set @numPackQty = @numItemQty / @numPackCapacity
--------------------------------------------------------------------------------
end -- end of if statement
-- TO RETURN BOTH ITEM QTY AND PACKAGE QTY
select @numItemQty ItemQty, @numPackQty PackQty
--------------------------------------------------------------------------------
end -- End of Procedure' 
END
GO
/****** Object:  View [dbo].[newss]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[newss]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[newss]
as
select  isnull(openingstock,0) stock, 1 mode
from
mosshopstock
where shopid = 3 and itemid = 258
union all
-----------------------------------------------------------------------------------------------
-- vwShopBinCardAudit portion begins
--Arrival from godown
select convert(numeric(18,3),isnull(d.gadItemGoodQuantityArrived,0)) TransQty, 1 mode
from losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d
where
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and
h.gahtransfinished=1
and h.gahshopid = 3 and d.gaditemid = 258
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES
union all
select convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,
1 as mode
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0
and grn.grnhShopid = 3 and grd.GRNDItemID = 258
union all
--transfer in
select convert(numeric(18,3),isnull(d.TIDrecievedgoodqty,0)) as TinQty, 1 mode
from lostransferinheader h, lostransferindetail d
where
h.tihid=d.tidid and
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1
and h.tihshopid = 3 and d.tiditemid = 258
union all
--recovery add
select convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 1 Mode
from
losstockrecovery sr group by  sr.srshopid, sr.sritemid
having isnull(sum(sr.sraddstock),0) >0
and sr.srshopid = 3 and sr.sritemid = 258
union all
--stock verification add
select convert(numeric(18,3),isnull(svdVerifiedStock-svdAvailStock, 0)) as svAddQty, 1 mode
from  losstockverificationheader, losstockverificationdetail
where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock
and svhCancelled=0
and svdshopid = 3 and svdItemid = 258
union all
--exchange in
select convert(numeric(18,3),isnull(sedExchangeQty,0))  as exchangedin, 1 mode
from
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0
and isnull(sedExchangeQty,0) >0
and sehShopID = 3 and seditemid = 258
union all
--local purchase
select convert(numeric(18,3),isnull(lpdItemQuantity,0)) localpurchase, 1 mode
from loslocalpurchasedetail, loslocalpurchaseheader where lphBillId=lpdBillID and
lphShopID= lpdShopid and lphCancelled=0
and lphShopid = 3 and lpditemid = 258
union all
--write off
select convert(numeric(18,3),isnull(wd.wdWriteoffQty, 0)) as writeoffqty, -1 mode
from loswriteoffheader wh, loswriteoffdetail wd
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0
and wh.whshopid = 3 and wd.wditemid = 258
union all
--Despatch
select convert(numeric(18,3),isnull(dd.dgddespatchedgoodqty,0)) as despatchqty,-1 mode
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish
and dd.dgdshopid = 3 and dd.dgditemid = 258
union all
--Transferout
select convert(numeric(18,3),isnull(todissuedgoodqty,0)) as ToutQty , -1 mode
from mestransferoutheader , mestransferoutdetail
where
tohid=todid and Tohshopid=todshopid and tohcancelled=0
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish
and todshopid = 3 and toditemid = 258
union all
--recovery minus
select convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd,-1 Mode
from
losstockrecovery sr
where sr.srshopid = 3 and sr.sritemid = 258
group by  sr.srshopid, sr.sritemid
having sum(isnull(sr.srdedstock,0)) >0
union all
--stockverification minus
select convert(numeric(18,3),isnull(svdAvailStock-svdVerifiedStock, 0)) as svMinusQty,-1 mode
from  losstockverificationheader, losstockverificationdetail where
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock
and svhCancelled=0
and  svdshopid = 3 and svdItemid = 258
union all
--pos sales
select convert(numeric(18,3),isnull(posdquantity,0)) cashsales, -1 mode
from losposdetail,losposheader
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0
and poshShopID = 3 and posditemid = 258
union all
--credit invoice
select convert(numeric(18,3),isnull(idquantity,0)) as creditsales, -1 mode
from losinvoicedetail,losinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0
and ihType =''I''
and ihshopid = 3 and iditemid = 258
union all
--exchange out
select convert(numeric(18,3),isnull(sedquantity,0))  as exchangedout, -1 mode
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0
and sehShopID = 3 and seditemid = 258
union all
--special invoice return to shop
select convert(numeric(18,3),-(isnull(reqqty,0))) as SpecialReturn, 1 mode
from losspecialinvoicedetail, losspecialinvoiceheader
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1
and ihproforma=0 and ihTransFinished = 1
-- transfinished added as stock is updated only after confirming
and IhShopid = 3 and iditemid = 258
union all
--COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED
select convert(numeric(18,3) , isnull(repinvdqty,0)), -1 as mode
from losinvoicedpartsreplacedetails, losserviceinvheader
where serinvhid = repinvinvoiceid
and serinvhshopid = repinvdshopid AND serinvhcancelled=0
and serinvhShopid = 3 and repinvdpartsid = 258
union all
--Re-Exporting
select convert(numeric(18,3),isnull(redquantity,0)) as creditsales, -1 mode
from losexportdetail, losexportheader
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0
and rehType=''I''
and rehShopID = 3 and reditemid = 258'
GO
/****** Object:  View [dbo].[vwshopcustomercreditnotes]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopcustomercreditnotes]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshopcustomercreditnotes    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on  : 09/12/2002
--Modified by  : leo
--Comments  : v3
----------------------------------------------------------------------------------------------------------
--Ref.No:1
-- Modified By : AADYAKUMAR D V
-- Modified On : 16/02/2012
-- Comment     : Added losDCNDate
----------------------------------------------------------------------------------------------------------
CREATE view [dbo].[vwshopcustomercreditnotes] as
select dcn.losdcncompanyid, dcn.losdcnshopid, dcn.losdcnid, dcn.losdcnno, dcn.losdcncustomerid, dcn.losdcnamount,
isnull(sum(setamount),0) settled ,
dcn.losDCNDate--Ref.No:1
from losdebitcreditnote dcn
left outer join (select cs.companyid, cs.csid, cs.shopid, cs.losshopdcnid, sum(cd.SettlementAmount) setamount  from
customersettlementheader cs, customersettlementdetail cd where cs.csid = cd.csid and cs.cancelled =0
group by cs.companyid, cs.csid, cs.shopid, cs.losshopdcnid) csh
on dcn.losdcncompanyid = csh.companyid and dcn.losdcnshopid = csh.shopid and
dcn.losdcnid = csh.losshopdcnid
where losdcncancelled = 0 and losdcndebit =0 and losdcncustomerid is not null
group by dcn.losdcncompanyid, dcn.losdcnshopid, dcn.losdcnid, dcn.losdcnno,dcn.losdcncustomerid, dcn.losdcnamount,
dcn.losDCNDate--Ref.No:1'
GO
/****** Object:  View [dbo].[vwShopSerSettlementDetails]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSerSettlementDetails]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwShopSerSettlementDetails    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwShopSerSettlementDetails] as
SELECT csd.CompanyID, CSD.shopid, csd.losaccInvoiceID as InvoiceID, null departmentid,
max(csh.csdate) csdate, sum(isnull(csd.settlementamount,0)) as Amtsettled
FROM customersettlementdetail csd
left outer join customersettlementHeader csh
on csd.CSID = csh.CSID and csd.CompanyID = csh.CompanyID
WHERE csh.Cancelled = 0 and csd.losaccInvoiceID is not null
GROUP BY csd.CompanyID, csd.shopid, csd.losaccInvoiceID'
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockArrival]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SpUpdateShopStockArrival]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.SpUpdateShopStockArrival    Script Date: 18/01/2003 9:45:49 PM ******/
--Created By		:Lawrence.J
--Created On		:30-Dec-2002
--Purpose		:(V3) Updating Goods Arrival Stock in POS
--verified By 		: hariharan (02/01/2003)
CREATE proc [dbo].[SpUpdateShopStockArrival]( @Arrivalid int,
@ShopId int,@Type char(1) ) as
declare
@cur_arrivalid int,
@cur_shopId int,
@cur_itemid int,
@cur_itemgoodqty numeric(18,3),
@cur_cost numeric(18,2),
@cur_ShipmentID int,
@recCount as int
set nocount on
	declare cursor_Detail  cursor for
	select gadArrivalID,gadShopid,gadItemID, gadItemGoodQuantityArrived,
	gadcostprice,1 from LOsgoodsarrivaltoshopdetail
	where gadArrivalID = @Arrivalid and gadShopid = @ShopId
open cursor_Detail
fetch next from cursor_Detail into
@cur_arrivalid, @cur_shopId, @cur_itemid,
@cur_itemgoodqty,@cur_cost, @cur_ShipmentID
while @@fetch_status = 0
begin
	if @Type=''F''
begin
		select @recCount = count(*) from  mosshopstock where ItemID= @cur_itemid
		and ShopID = @cur_shopId
		if @recCount =0
			insert mosshopstock(ShopID,ShipmentID,ItemID,Stock,
			ItemCostPrice, StockDate) select @cur_shopId, 1, @cur_ItemID,
			@cur_itemgoodqty,@cur_Cost, getdate()
		else
			update mosshopstock set Stock = Stock + @cur_itemgoodqty
			where ItemID = @cur_itemid and ShopID = @cur_shopId
	 end
	fetch next from cursor_Detail into
	@cur_arrivalid, @cur_shopId, @cur_itemid,
	@cur_itemgoodqty,@cur_cost,@cur_ShipmentID
end
close cursor_Detail
deallocate cursor_Detail
return 0' 
END
GO
/****** Object:  View [dbo].[vwShopSerInvAndRecAmount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopSerInvAndRecAmount]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By 	: Hariharan
--Modified Date	: 04/08/2004
CREATE view [dbo].[vwShopSerInvAndRecAmount] as
select vwinv.companyid,vwinv.shopid, vwinv.aiinvoiceid, vwinv.AIdepartmentid, vwinv.invoiceno,
vwinv.aiinvoicedate,vwinv.duedate, vwinv.aicustomerid,vwinv.aiReferenceno refno,
vwinv.invoiceamt, (sum(isnull(vwrec.settledamt,0)) + sum(isnull(settleamt,0))) settled,
''PSI'' Type from vwshopsaleinvoiceamount vwinv left outer join
vwshopsaleinvoicereceipt vwrec on vwinv.companyid=vwrec.companyid and
vwinv.shopid = vwrec.shopid and vwinv.aiinvoiceid = vwrec.posaccountsinvoiceid
left outer join (Select CompanyId, DepartmentID, sum(amtSettled) settleamt, invoiceid,
shopid from vwshopsersettlementdetails group by CompanyId, DepartmentID, shopid,
invoiceid) csett on vwinv.companyid = csett.companyid and
vwinv.aiinvoiceid = csett.invoiceid and vwinv.shopid = csett.shopid
group by vwinv.companyid,vwinv.shopid, vwinv.aiinvoiceid, vwinv.AIdepartmentid,
vwinv.invoiceno, vwinv.aiinvoicedate,vwinv.duedate, vwinv.aicustomerid,
vwinv.aiReferenceno, vwinv.invoiceamt'
GO
/****** Object:  View [dbo].[vwShopCreditInvRecAmount]    Script Date: 10/06/2012 14:17:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopCreditInvRecAmount]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--Modified By  : Hariharan
--Modified Date : 04/08/2004
CREATE view [dbo].[vwShopCreditInvRecAmount] as
select vwinv.companyid,vwinv.shopid, vwinv.ihdepartmentid, vwinv.invoiceid, vwinv.invoiceno,
vwinv.invoicedate,vwinv.ihduedate, vwinv.customerid,vwinv.referenceno refno,
vwinv.amount, (sum(isnull(vwrec.settledamt,0)) + sum(isnull(settleamt,0))) settled , vwinv.Type from
vwshopcreditinvoice vwinv left outer join
vwshopcreditinvoicereceipt vwrec on vwinv.companyid=vwrec.companyid and
vwinv.shopid = vwrec.shopid
and vwinv.invoiceid = vwrec.posinvoiceid
left outer join (Select CompanyId, DepartmentID, sum(amtSettled) settleamt, invoiceid, shopid
from vwshopinvsettlementdetails group by CompanyId, DepartmentID, shopid, invoiceid) csett
on vwinv.companyid = csett.companyid and vwinv.invoiceid = csett.invoiceid and
vwinv.ShopId = csett.ShopId group by vwinv.companyid,vwinv.shopid, vwinv.ihdepartmentid,
vwinv.invoiceid, vwinv.invoiceno, vwinv.invoicedate,vwinv.ihduedate, vwinv.customerid,
vwinv.amount,vwinv.referenceno  ,vwinv.Type'
GO
/****** Object:  View [dbo].[vwGdnBinCardWithOpening]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardWithOpening]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwGdnBinCardWithOpening    Script Date: 18/01/2003 9:45:41 PM ******/
-- View created on 13/11/2002
-- Created by Kishore
-- Used in Godown Item Moving report
--Comments : v3
CREATE view [dbo].[vwGdnBinCardWithOpening] as
--
select gsGodownId, gsItemID, Null sDate , ''Opening'' TransNo, 0 TransId,
IsNull(gsOpeningStock, 0) TransQty,
''Opening'' Type, 1 Mode, gsStockDate UpdateTime
from MoiGodownStock
Union All
select GodownId, ItemId, gDate, TransNo, TransID, TransQty, Type, Mode,
UpdateTime
from vwGdnBinCard'
GO
/****** Object:  View [dbo].[vwGdnBinCardForGdnReport]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnBinCardForGdnReport]'))
EXEC dbo.sp_executesql @statement = N'
--View For Reports Only Godown Movements
Create View [dbo].[vwGdnBinCardForGdnReport] as
select * from vwGdnBinCard where (type = ''Despatch To Shop'' OR
type = ''Special Despatch'')'
GO
/****** Object:  View [dbo].[vwCustomerLedger]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomerLedger]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- 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
-----------------------------------------------------------------------------------------------
--Modified By: Nidheesh P V
--Modified on :20/03/20
--Comments : Added Fine Invoice 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 :03-06-10
--Modified by :SHINE DAS
--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
----------------------------------------------------------------------------------------
--Ref.No.1
--Modified on :17-08-201111
--Modified by :AADYAKUMAR D V
--Added a condition to solve duplication in reports
----------------------------------------------------------------------------------------
--Ref.No.2
--Modified on :22-11-2011
--Modified by :AADYAKUMAR D V
--Comment     :Added Tax in Account service invoice
----------------------------------------------------------------------------------------
--select * from vwCustomerLedger
---Ref.No.3
--Modified on :16-01-2012
--Modified by :jyothish
----------------------------------------------------------------------------------------
--Ref.No.4
--Modified on :18-02-2012 ,03-04-2012
--Modified by :BIJESH.B ,jyothish
--Ticket id   : FGJ-870028
--Comment     :Added Tax in POS-service invoice
----------------------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwCustomerLedger] 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)+isnull(ah.TaxAmount,0) End as invamt, --Ref.No.2
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)+isnull(ah.TaxAmount,0) cinvamt,--Ref.No.2
0.0 cpmtamt, ah.financialid, '''' chequedetails, c.debtoraccid,
convert(numeric(18,2),(isnull(sum(ServiceQty * Amount),0)-isnull(Discount,0))  * depexrate)+isnull(ah.TaxAmount,0) dinvamt,--Ref.No.2
0.0 dpmtamt,c.customercategory, isnull(c.custgroupname,'''') custgroupname, ah.exchangerates,
sum(isnull(vw.settledamt, 0)) SettledAmt,'''' shopid
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,
ah.TaxAmount--Ref.No.2
union all
--2 shop acc invoices
--Ref.No.4 -> included " + isnull(ah.aiTaxAmount,0) " in below query
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)
+ isnull(ah.aiTaxAmount,0)
else sum((siServiceQty * siAmount) + siClearingCommAmt) + isnull(ah.aiTaxAmount,0) 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)
+ isnull(ah.aiTaxAmount,0)) *
ah.aiexchangerate else (sum((siServiceQty * siAmount) + siClearingCommAmt)
+ isnull(ah.aiTaxAmount,0) ) *
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)
+ isnull(ah.aiTaxAmount,0) *
ah.aidepexrate else sum((siServiceQty * siAmount) + siClearingCommAmt)
+ isnull(ah.aiTaxAmount,0) *
ah.aidepexrate end )), 0.0 dpmtamt,
c.customercategory,isnull(c.custgroupname,'''')custgroupname,
ah.aidexchangerates, sum(isnull(vw.settledamt, 0)) settledamt,ah.aishopid
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
,isnull(ah.aiTaxAmount,0)  --Ref.No.4  ends
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
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
and type<>''fandb''    --Ref.No.1
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
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,''''
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,''''
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,''''
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,''''
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
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
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
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
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.ihinvoiceid 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
---ih.ihinvoiceid = d.returnedinvid refund condition is changed-Ref.No.3
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
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
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,''''
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,''''
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
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
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)
union all
---FINE INVOICE----
select f.fhCompanyID,f.fhDepartmentID,f.fhCustomerID,fhInvoiceDate,f.fhInvoiceNo,f.fhFineNo,'''' cr,''Fine Invoice'',
'''',f.fdFineAmount InvoiceAmount, 0 pmtamt,f.fdFineDate duedate,''''age,''''updatetime,stld.receiptdate,
isnull(f.fdFineAmount,0)*f.fhComExchangeRate ComInvAmnt,0.00 CpmtAmt,f.fhFinancialID,'''',debtoraccid,
isnull(f.fdFineAmount,0)*f.fhDepExchangeRate DepInvAmnt,0.00 DeppmtAmt,
c.customercategory, isnull(c.custgroupname,'''')custgroupname,'''',
settledamt,stld.shopid
from
(
select fhCompanyID,fhDepartmentID ,fhInvoiceNo,fhFineNo,fhInvoiceDate,fhDepExchangeRate, fhComExchangeRate,fhFinancialID,
fhFineID,sum(fdFineAmount*fhRespExchangeRate)fdFineAmount,fhCustomerID,fdFineDate from afineheader h inner join afinedetail d on h.fhFineID =d.fdFineID
where   isnull(fhInvoiceCancelled,0)=0  --- and fdFineDetailID=1
group by fhCompanyID,fhDepartmentID ,fhInvoiceNo,fhFineNo,fhInvoiceDate,fhDepExchangeRate, fhComExchangeRate,fhFinancialID,fhFineID,fhCustomerID,fdFineDate )f
left outer join
(
select
st.companyid, st.shopid, st.fineid, st.customerid, 0.0 as invoiceamount,
max(receiptdate) receiptdate, sum(settledamt) settledamt
from
(
select rh.companyid, rd.shopid, rd.fineid, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived)settledamt
from receiptvoucherdetails rd,receiptvoucherheader rh
where rd.receiptid = rh.receiptid and rd.companyid = rh.companyid
and cancelled = 0 and fineid is not null
group by rh.companyid, rd.shopid, rd.fineid, rh.customerid,ReceiptDate
union all
select ch.companyid, cd.shopid, cd.fineid , ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt
from customersettlementheader ch,customersettlementdetail cd where
ch.CSID=cd.CSID and ch.CompanyID=cd.CompanyID and
ch.cancelled=0 and cd.fineid is not null
group by ch.companyid, cd.shopid, cd.fineid, ch.customerid
)st
group by
st.companyid, st.shopid, st.fineid, st.customerid
)stld
on f.fhFineID=stld.fineid
inner join acustomermaster c on c.customerid=f.fhCustomerID'
GO
/****** Object:  View [dbo].[vwcustomeradvance]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomeradvance]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwcustomeradvance    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
CREATE view [dbo].[vwcustomeradvance] as
select companyid, customerid, sum(advance) advance from
(select companyid, customerid, sum(rptamt - settledamt) advance from
vwadvancepaidreceiptsamounts group by companyid, customerid
having sum(rptamt - settledamt)> 0
union all
select dcncompanyid companyid, dcncustomerid customerid, sum(rptamt - settledamt) advance
from vwadvancepaidCreditsAmounts group by dcncompanyid, dcncustomerid having
sum(rptamt - settledamt) > 0) one
group by companyid, customerid'
GO
/****** Object:  StoredProcedure [dbo].[sp_ssrsreptotaltax]    Script Date: 10/06/2012 14:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ssrsreptotaltax]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  procedure [dbo].[sp_ssrsreptotaltax](@dtStartDate datetime, @dtEndDate datetime,@DeptId int )  as
-- Modified by  : Jyothish S R
-- Date         : 17/11/2011
------------------------------------------------------------
--Modified By: Rajesh Kamalakshan
--Date :    25-11-2011
--Assigned the parameter @DeptId to another varibale @SPDeptId to reduce execution time from SSRS.
--Reason :The reason behind this modfication is .When an sp is caleed form SSRS , SQL Server was producing a
--convoluted execution plan when executed from the SSRS report due to ''parameter sniffing''.The workaround
--was to declare variables inside of the stored procedure and assign the incoming parameters to the
--variables. Then the query used the variables rather than the parameters. This caused the query to
--perform consistently whether called from SQL Server Manager or through the SSRS report
------------------------------------------------------------
-- Modified by  : Jyothish S R
-- Date         : 29/11/2011
---Out Of Scope of GST added
-- Modified by  : Jyothish S R
-- Date         : 03/12/2011
---taxcategory=0 filterarion is avoided
declare @SPDeptId as int
set @SPDeptId=   @DeptId
Begin
set nocount on
if @SPDeptId<>0
begin
select t.companyid,t.departmentid,d.DepartmentName,t.shopid,s.ShopName,t.poshBillNo,t.billdate,
t.amount,t.camount,t.damount,vw.Tamount,t.TaxPercentage,t.TaxAmount,t.CTaxAmount,t.DTaxAmount,
case when t.transtype=''p'' then ''cash sales'' else case when t.transtype=''d'' then ''special invoice''
else case when t.transtype=''C'' then ''Credit invoice'' else case when t.transtype=''I'' then ''invoice''
else case when t.transtype=''s'' or  t.transtype=''sbi'' then ''service invoice'' else case when
t.transtype=''hs'' then ''service invoice'' else case when t.transtype=''sb'' then ''booking advance''
else case when t.transtype=''lp'' then ''service Booking'' else case when t.transtype=''e'' then
''goods exchange'' else t.transtype end end end  end end end end end end   transtype,t.Type,
t.TrType,t.posdItemTaxCategory,
case when TaxType=0 and TaxPercentage=0 then ''Sales Non Taxable'' else
case when TaxType=3 then ''Out Of Scope of GST''
else ''Sales '' + convert(varchar(50),convert(decimal(8,2),(TaxPercentage))) + ''%Tax'' end end as Taxhead
from  vwTotalTax t
left outer join   ashops  s  on t.shopid=s.ShopID
left outer join aDepartmentMaster d on d.DepartmentID=t.departmentid
inner join (
select departmentid,shopid,poshBillNo,transtype, SUM(camount) Tamount from vwTotalTax
where billdate between @dtStartDate and @dtEndDate    and departmentid= @SPDeptId
group by departmentid,shopid,poshBillNo,transtype
) vw  on vw.departmentid=t.departmentid and vw.shopid=t.shopid and vw.poshBillNo=t.poshBillNo
and t.transtype=vw.transtype
where billdate between @dtStartDate and @dtEndDate and t.departmentid= @SPDeptId
end
else
begin
select t.companyid,t.departmentid,d.DepartmentName,t.shopid,s.ShopName,t.poshBillNo,t.billdate,
t.amount,t.camount,t.damount,vw.Tamount,t.TaxPercentage,t.TaxAmount,t.CTaxAmount,t.DTaxAmount,
case when t.transtype=''p'' then ''cash sales'' else case when t.transtype=''d'' then ''special invoice''
else case when t.transtype=''C'' then ''Credit invoice'' else case when t.transtype=''I'' then ''invoice''
else case when t.transtype=''s'' or t.transtype=''sbi'' then ''service invoice'' else case when
t.transtype=''hs'' then ''service invoice'' else case when t.transtype=''sb'' then '' booking advance''
else case when t.transtype=''lp'' then ''service Booking'' else case when t.transtype=''e'' then
''goods exchange'' else t.transtype end end end end end end end end end transtype,t.Type,
t.TrType,t.posdItemTaxCategory,
case when TaxType=0 and TaxPercentage=0 then ''Sales Non Taxable'' else
case when TaxType=3 then ''Out Of Scope of GST''
else ''Sales '' + convert (varchar(50),convert(decimal(8,2), (TaxPercentage))) + ''%Tax'' end end as Taxhead
from  vwTotalTax t
left outer join   ashops  s  on t.shopid=s.ShopID
left outer join aDepartmentMaster d on d.DepartmentID=t.departmentid
inner join  (
select departmentid,shopid,poshBillNo,transtype, SUM(camount) Tamount from vwTotalTax
where billdate between @dtStartDate and @dtEndDate
group by departmentid,shopid,poshBillNo,transtype
) vw  on vw.departmentid=t.departmentid and vw.shopid=t.shopid and vw.poshBillNo=t.poshBillNo
and t.transtype=vw.transtype
where billdate between @dtStartDate and @dtEndDate
end
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum_tem]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSum_tem]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--sp_helptext spdebtoragesum
-- 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
-----------------------------------------------------------------------------
--  spdebtoragesum '''',''20080101'','''',0,0,0,'''',''General''
CREATE PROCEDURE [dbo].[spDebtorAgeSum_tem] (@dtstartdate datetime,@dtinvdate datetime,
@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(7),
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=''''
select * into #tempvwInvoices from vwInvoices
select * into #tempvwsettlements from vwsettlements
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 *,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
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
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 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
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
drop table #tmpInvoices
drop table #tmpSettlements
drop table #tempvwInvoices
drop table #tempvwsettlements
end
set nocount off
set ansi_Warnings on' 
END
GO
/****** Object:  View [dbo].[vwServiceDetailsForCommision]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwServiceDetailsForCommision]'))
EXEC dbo.sp_executesql @statement = N'
--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
/****** Object:  View [dbo].[vwSalesAnalysisByWeek]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByWeek]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwSalesAnalysisByWeek    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwSalesAnalysisByWeek]  as
select companyid,departmentid, shopid, year(billdate) as tyear, month(billdate) as tmonth,
datepart(wk,billdate) tweek, datepart(wk,billdate)-1  weekdays, billdate,
accountid, actamount, actamount famount, damount, camount, cash, transtype from
vwcashsalestruncated'
GO
/****** Object:  View [dbo].[vwSalesAnalysisByMonth]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByMonth]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwSalesAnalysisByMonth    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwSalesAnalysisByMonth]  as
select companyid,departmentid, shopid, year(billdate) as tyear, month(billdate) as tmonth,
month(billdate) - 1 as MonthPrevious, billdate, accountid, actamount, actamount famount,
damount, camount, cash, transtype from vwcashsalestruncated'
GO
/****** Object:  View [dbo].[vwreexportinvoicesettled]    Script Date: 10/06/2012 14:17:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwreexportinvoicesettled]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By 	: Hariharan
--Modified Date	: 04/08/2004
CREATE view  [dbo].[vwreexportinvoicesettled]  as
select  h.companyid, rehdepartmentid departmentid, h. shopid,
h.invoiceid,  invoiceno, invoicedate, rehduedate , h.refno,
h.customerid, rehexportamount,
(sum(isnull(vwrec.settledamt,0)) + sum(isnull(settleamt,0))) settled, type
from vwreexportinvoices h left outer join
vwreexportsettlements vwrec on h.companyid = vwrec.companyid and
h.shopid = vwrec.shopid and h.invoiceid =  vwrec.invoiceid
left outer join (Select CompanyId, DepartmentID, sum(amtSettled) settleamt, invoiceid,
shopid from vwshopsplsettlementdetails group by CompanyId, DepartmentID, shopid,
invoiceid) csett on h.companyid = csett.companyid and
h.invoiceid = csett.invoiceid and h.ShopId = csett.ShopID
group by h.companyid, h.shopid, h.rehdepartmentid, h.invoiceid, h.invoiceno,
h.invoicedate, h.rehduedate, h.customerid, h.rehexportamount, type,h.refno'
GO
/****** Object:  View [dbo].[vwGoodReqDespArrDtlsPurReq]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodReqDespArrDtlsPurReq]'))
EXEC dbo.sp_executesql @statement = N'
-- View
--created by dheena
--created date 16022004
--comments :find the varience of goods arrival and desptch and receieve
-- Modified By: Regin Thangaraj
-- Modified On: 20-10-2010
-- Purpose: To fix error "The column ''rowguid'' was specified multiple times for ''ahd''"
-- RefNo-1
CREATE view [dbo].[vwGoodReqDespArrDtlsPurReq] as
select
ahd.*, hqdespatch.*,Mosgoodsrequest.*,aitem.ItemID,aitem.ItemCode,aitem.ItemDescription
,UnitID,UnitName,sShipmentID,sShipmentNO,sShipmentDate,
PackingTypeID,PackingTypeName
-- Mosgoodsrequest.grhrequestid,Mosgoodsrequest.grdshopid,Mosgoodsrequest.grditemid,
-- Mosgoodsrequest.grdgoodqty,Mosgoodsrequest.GRHrequestNO,Mosgoodsrequest.GRHrequestDate,
-- dhshopreqid, dhDespatchnoteID, ddDespatchnoteID, dditemid, dhshopid, ddshopid,
-- dhgodownid, ddgodownid,dnmDespatchNoteNo,dnmDespatchNoteDate ,ddQty,
-- gaharrivalid,gahshopid,gahshopreqid,gahhqdespatchid,gadItemGoodQuantity
from
aItem, aUnit u, aShipment, aPackingType,
vwitemdescription,
(select
-- Below line caused error since rowguid column duplicated when replicated.
-- So commented below line, and specified all columns explicitly except rowguid
-- By Regin Thangaraj On 20-10-2010 RefNo-1
-- a.*, b.*,
a.gahArrivalID, a.gahShopid, a.gahArrivalNo, a.gahArrivalDate, a.gahGodownDespatchID,
a.gahDespatchedGodownID, a.gahCancelled, a.gahCancelledRemarks, a.gahRecAddUser,
a.gahRecModifyUser, a.gahremarks, a.gahTransFinished, a.gahfuturevc, a.gahshopreqid,
a.gahposted, a.updatetime, a.gahdepartmentid, a.gahhqdespatchid, a.gahconexrate,
a.gahdepexrate, a.gahexchangerates, a.gahTime,
b.gadArrivalID, b.gadShopid, b.gadShipmentID, b.gadItemID, b.gadItemGoodQuantity,
b.gadItemBAdQuantity, b.gadItemGoodQuantityArrived, b.gadItemBadQuantityArrived,
b.gadcostprice, b.gadpackingtypeid, b.gadpackqty, b.gadreceivepackqty,
shopid,shopname
from
losgoodsarrivaltoshopdetail b , losgoodsarrivaltoshopheader a,ashops c
where
a.gaharrivalid=
b.gadarrivalid and
a.gahshopid=shopid and
a.gahshopid=b.gadshopid  ) ahd
left outer join
(select
dhshopreqid, dhDespatchnoteID, ddDespatchnoteID, dditemid, dhshopid, ddshopid,
dhgodownid, ddgodownid,dnmDespatchNoteNo,dnmDespatchNoteDate ,ddQty
from
ahqDespatchNotemain,ahqDespatchNoteHeader,ahqdespatchnotedetails
where
dhDespatchnoteID=ddDespatchnoteID and dhCancelled=0
and dnmDespatchNoteID=dhDespatchNoteMainID and
(dhGodownid=ddgodownid or dhshopid= ddshopid )) hqdespatch
on gahhqdespatchid=dhDespatchnoteID and
(dhshopid=gahShopid or dhGodownid=gahDespatchedGodownID)
and ahd.gaditemID =  dditemid
left outer join
(select
grhrequestid,grdrequestid,grdshopid,grhshopid,grditemid,grdgoodqty,
GRHrequestNO,GRHrequestDate
from
mosgoodsrequestheader ,mosgoodsrequestdetail
where
GRHrequestID=grdrequestid and GRHshopID =grdshopid and
GRHcancel =0) Mosgoodsrequest
on Mosgoodsrequest.GRHrequestID=dhShopReqId and dhshopid=Mosgoodsrequest.GRHshopID
and ahd.gaditemID = grditemid
where
ahd.gadpackingtypeid=aPackingType.PackingTypeID And
ahd.gaditemID = aitem.itemID and
ahd.gadshipmentID = ashipment.sshipmentID and
aitem.itemid=vwitemdescription.itemid  And aItem.UnitsId = u.UnitId
and gahdespatchedgodownid is Null and gahgodowndespatchid is Null'
GO
/****** Object:  View [dbo].[vwGoodReqDespArrDtls]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGoodReqDespArrDtls]'))
EXEC dbo.sp_executesql @statement = N'
--creeated by dhenea
--create date 16022004
--comments goods arrivaldesprequest
-- This view changed only for the Godown arrival which flow from Issuse on 030403
-- Modified By: Regin Thangaraj
-- Modified On: 20-10-2010
-- Purpose: To fix error "The column ''rowguid'' was specified multiple times for ''ahd''"
-- RefNo-1
CREATE  view [dbo].[vwGoodReqDespArrDtls] as
select
ahd.*, Hqissue.*,Mosgoodsrequest.*,MeiDespatch.*,
aitem.ItemID,aitem.ItemCode,aitem.ItemDescription
,UnitID,UnitName,sShipmentID,sShipmentNO,sShipmentDate,
PackingTypeID,PackingTypeName
-- Mosgoodsrequest.grhrequestid,Mosgoodsrequest.grdshopid,Mosgoodsrequest.grditemid,
-- Mosgoodsrequest.grdgoodqty,Mosgoodsrequest.GRHrequestNO,Mosgoodsrequest.GRHrequestDate,
-- dhshopreqid, dhDespatchnoteID, ddDespatchnoteID, dditemid, dhshopid, ddshopid,
-- dhgodownid, ddgodownid,dnmDespatchNoteNo,dnmDespatchNoteDate ,ddQty,
-- gaharrivalid,gahshopid,gahshopreqid,gahhqdespatchid,gadItemGoodQuantity
from
aItem, aUnit u, aShipment, aPackingType,
vwitemdescription,
(select
-- Below line caused error since rowguid column duplicated when replicated.
-- So commented below line, and specified all columns explicitly except rowguid
-- By Regin Thangaraj On 20-10-2010 RefNo-1
-- a.*, b.*,
a.gahArrivalID, a.gahShopid, a.gahArrivalNo, a.gahArrivalDate, a.gahGodownDespatchID,
a.gahDespatchedGodownID, a.gahCancelled, a.gahCancelledRemarks, a.gahRecAddUser,
a.gahRecModifyUser, a.gahremarks, a.gahTransFinished, a.gahfuturevc, a.gahshopreqid,
a.gahposted, a.updatetime, a.gahdepartmentid, a.gahhqdespatchid, a.gahconexrate,
a.gahdepexrate, a.gahexchangerates, a.gahTime,
b.gadArrivalID, b.gadShopid, b.gadShipmentID, b.gadItemID, b.gadItemGoodQuantity,
b.gadItemBAdQuantity, b.gadItemGoodQuantityArrived, b.gadItemBadQuantityArrived,
b.gadcostprice, b.gadpackingtypeid, b.gadpackqty, b.gadreceivepackqty,
shopid,shopname
from
losgoodsarrivaltoshopdetail b , losgoodsarrivaltoshopheader a,ashops c
where
a.gaharrivalid=
b.gadarrivalid and
a.gahshopid=shopid and
a.gahshopid=b.gadshopid and gahdespatchedgodownid is not null
and gahgodowndespatchid is not null
) ahd
left outer join
(select a.dhDespatchID,dhdespatchno,dhGodownID,dhShopID,dhIssueNoteID,dhCancelled,
ddDespatchID,ddLocationId,ddGodownID,ddShopId,ddItemBadQty,ddItemGoodQty,ddItemID,
dhdespatchdate,ddcostedprice
from
MEiDespatchToShopHeader a ,MEiDespatchToShopdetail b
where
dhDespatchID=ddDespatchId and dhGodownID = ddGodownID and
dhshopid=ddShopId and
dhCancelled =0) MeiDespatch
on dhShopID  =gahShopid  and
dhDespatchID =gahGodownDespatchID and
dhGodownID =gahDespatchedGodownID
and dditemid=gaditemid
left  outer join
(select INMIssuenoteID,INHissuenoteno,INMRequestID,INMShopID,INHIssuenoteID,INHGodownID,
INHToshopID,INHTogodownID,INDIssuenoteID,INDGodownid,INDItemID,INDQty,INDBadQty,
INDBadQtyRequested,INDgoodQtyRequested,INHShopReqId,INHshopreqno
from aHqIssueNoteMain a,ahqIssueNoteheader b,ahqIssueNotedetail c
where INMIssuenoteID=INHIssuenotemainID and INHIssuenoteID  = INDIssuenoteID and
INHCancelled =0  and INDGodownid =INHgodownID ) Hqissue on
dhIssueNoteID=INHissuenoteid and
INHGodownid=dhGodownID
and meidespatch.dditemID =  INDitemid
left outer join
(select
grhrequestid,grdrequestid,grdshopid,grhshopid,grditemid,grdgoodqty,
GRHrequestNO,GRHrequestDate
from
mosgoodsrequestheader ,mosgoodsrequestdetail
where
GRHrequestID=grdrequestid and GRHshopID =grdshopid and
GRHcancel =0 ) Mosgoodsrequest
on Mosgoodsrequest.GRHrequestno=INHshopreqno
and INMshopid=Mosgoodsrequest.GRHshopID
and inditemID = grditemid
where
ahd.gadpackingtypeid=aPackingType.PackingTypeID And
ahd.gaditemID = aitem.itemID and
ahd.gadshipmentID = ashipment.sshipmentID and
aitem.itemid=vwitemdescription.itemid  And aItem.UnitsId = u.UnitId'
GO
/****** Object:  View [dbo].[purchasecostingtracking]    Script Date: 10/06/2012 14:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[purchasecostingtracking]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[purchasecostingtracking] as
select co.chcostingid,co.chcostingno,co.chcostingdate,co.chcostingdoneby,
case convert(int,co.chcancelled) when 1 then ''Yes'' when 0 then ''No'' end cancelled,
case convert(int,co.chPosted) when 1 then ''Yes'' when 0 then ''No'' end posted ,
round(sum(isnull(cd.cdCostingPrice,0)*isnull(cd.cdItemQuantity,0)),8) shipmentcost,
vwp.pbhBillNo,vm.VendorName,vwp.QuotationNo,vwp.HQRequestNo,vwp.ShopRequetNO from LOaCostingHeader co, LOaCostingdetail cd,
avendormaster vm,vwpurchasebilltracking vwp where co.chcostingid=cd.cdcostingid and co.chBillID=vwp.pbhBillid and
co.chCompanyID = vwp.pbhCompanyID  and
vwp.pbhVendorID =vm.VendorID And vwp.pbhCompanyID = vm.CompanyID
group by  co.chcostingid,co.chcostingdate,co.chcostingno,co.chcostingdoneby,
convert(int,co.chcancelled),convert(int,co.chposted),vwp.pbhBillNo,vm.VendorName,vwp.QuotationNo,vwp.HQRequestNo,vwp.ShopRequetNO'
GO
/****** Object:  View [dbo].[vwAdvancePaidToRetriveCustomer]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwAdvancePaidToRetriveCustomer]'))
EXEC dbo.sp_executesql @statement = N'
-- Created By   : Hariharan
-- Created Date : 30/04/2003
-- For getting the advances received from customer which is still remaining
-- to be completely settled in customer settlement against any invoices
-- this view is written for MIS report only
-----------------------------------------------------------------------------
-- Created on V3 	: 12/06/2003
-- Created by		: Kishore
-----------------------------------------------------------------------------
CREATE VIEW [dbo].[vwAdvancePaidToRetriveCustomer] AS
-- view for taking the advance payments which are not settled completely
-- for advance payments done to supplier which is not yet settled 020704 hari
select r.rptamt, r.settledamt, r.rptamt - r.settledamt balance,
r.companyid, h.ReceiptId ,h.departmentid,  r.CustomerId, 0 shopid, 0 due, ReceiptDate,
ReceiptNo,  ''CustPaid'' type, h.remarks, CustomerName,
c.currencyname, c.currencyid, c.symbol, dp.departmentname, customercategory
from vwadvancepaidReceiptsAmounts r, ReceiptVoucherHeader h,
acurrencymaster c, aCustomerMaster vm, adepartmentmaster dp
where r.ReceiptId = h.ReceiptID
and r.companyid = h.companyid
and h.Customerid = vm.Customerid
and h.departmentid = dp.departmentid
and r.rptamt - r.settledamt > 0
and r.CustomerID is not null
and c.currencyid = vm.currencyid'
GO
/****** Object:  View [dbo].[vwadvancepaidtoretrive]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwadvancepaidtoretrive]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwadvancepaidtoretrive    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwadvancepaidtoretrive] as
--view for taking the advance payments which are not settled completely
--for advance payments done to supplier which is not yet settled 020704 hari
select r.Pmtamt, r.settledamt, r.Pmtamt - r.settledamt balance,
r.companyid, h.phpaymentid ,h.phdepartmentid,  r.vendorid, 0 shopid, 0 due, phpaymentdate,
phpaymentno,  ''vendpaid'' type, h.phremarks, vendorname,
c.currencyname, c.currencyid, c.symbol, dp.departmentname
from  vwadvancepaidpaymentsamounts r, ahqpaymentvoucherheader h ,
acurrencymaster c, avendormaster vm, adepartmentmaster dp where r.paymentid = h.phpaymentid and
r.companyid = h.phcompanyid and h.phvendorid = vm.vendorid and h.phdepartmentid = dp.departmentid
and  r.Pmtamt - r.settledamt >0 and r.vendorid is not null and c.currencyid = vm.currencyid'
GO
/****** Object:  View [dbo].[vwspecialinvrecamount]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwspecialinvrecamount]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By 	: Hariharan
--Modified Date	: 04/08/2004
CREATE view [dbo].[vwspecialinvrecamount] as
select vwinv.companyid,vwinv.shopid, vwinv.invoiceid, vwinv.ihdepartmentid,
vwinv.invoiceno,vwinv.referenceno refno, vwinv.invoicedate,vwinv.ihduedate,
vwinv.customerid, vwinv.amount,
(sum(isnull(vwrec.settledamt,0)) + sum(isnull(settleamt,0))) settled ,''PDI'' Type from
vwspecialinvoiceamount vwinv left outer join
vwspecialinvoicereceipt vwrec on vwinv.companyid=vwrec.companyid and
vwinv.shopid = vwrec.shopid and vwinv.invoiceid = vwrec.posspinvoiceid
left outer join (Select CompanyId, DepartmentID, sum(amtSettled) settleamt, invoiceid,
shopid from vwshopsplsettlementdetails group by CompanyId, DepartmentID, shopid,
invoiceid) csett on vwinv.companyid = csett.companyid and
vwinv.invoiceid = csett.invoiceid and vwinv.shopid = csett.Shopid
group by vwinv.companyid,vwinv.shopid, vwinv.invoiceid, vwinv.ihdepartmentid,
vwinv.invoiceno, vwinv.invoicedate,vwinv.ihduedate, vwinv.customerid,
vwinv.amount, vwinv.referenceno'
GO
/****** Object:  View [dbo].[vwArrivalGdnToshop]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwArrivalGdnToshop]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 18/01/2003 9:45:39 PM ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 31/07/2002 2:00:31 PM ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 20/11/2001 9:59:05 AM ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 17/11/2001 9:21:52 PM ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 16/06/2001 15:36:33 ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 09/03/2001 02:32:28 ******/
/****** Object:  View dbo.vwArrivalGdnToshop    Script Date: 12/05/00 1:40:15 PM ******/
CREATE view [dbo].[vwArrivalGdnToshop] as
select gadshopid,gaditemid,gaharrivalDate,sum(gadItemGoodQuantity) as arrivalqty from
LOSGoodsArrivalToShopHeader,LOSGoodsArrivalToShopdetail where gahShopId=gadShopid
and gadarrivalID=gaHArrivalID and gahCancelled=0 group by gadShopid,gaharrivalDate,gadItemid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateVendorOpeningBalance]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateVendorOpeningBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 06/01/2003
-- Modified by      	: leo
-- Comments		: v3
-- FinancialId hardcoded as 1 by hari 06012003
------------------------------------------------------------------------------------
-- Modified by		: Kishore
-- Modified on		: 13/06/2003
-- Comments		: sp corrected to take the correct opening financialid
--                        rather than taking the current financialid
--              	  (on comparison with V2)
------------------------------------------------------------------------------------
-- Modified by		: R Harikrishnan
-- Modified on		: 04/08/2003
-- Comments		: sp corrected to the amount was not conerting
------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateVendorOpeningBalance]
	@intCompanyId int,
	@intVendorId int
AS
begin
--	For testing commented by R Harikrishnan
--	Set @intCompanyId=1
--	Set @intVendorId =1
	set nocount on
	declare @inttradepayableacc as int,
		@dtfinstartdate as datetime,
		@numvendorbalance as numeric(18,2),
		@numvendorcbalance as numeric(18,2),
		@intdepid as int,@intcount as int,
		@intFinId as int,
		@intcreditorid as int,
		@numamount as numeric(18,2),
		@numactualamount as numeric(18,2),
		@numdepamount as numeric(18,2),
		@strExRates as varchar(250),
		@intBillVendorID as int,
		@creditorsaccid as varchar(250),
		@strsql as nvarchar(2000)
	create table #temp
	(
		creditorid  int,
		amount numeric(18,2),
		depamount numeric(18,2),
		actualamt numeric(18,2)
	)
	set @numvendorbalance = 0.0
	set @numvendorcbalance = 0.0
	
	-- balance of respective supplier	
	select
		@numvendorcbalance = isnull(isnull(sum(cbillamt),0) - isnull(sum(cpmtamt),0),0) ,
		@numvendorbalance = isnull(isnull(sum(billamt),0) - isnull(sum(pmtamt),0),0)
	from
		vwsupplierledger
	where
		CompanyId = @intCompanyId and VendorId = @intVendorId and FinancialId = 0
	-- updating the vendor balance comp cur in opdr, and resp in opcr
	update avendormaster set
		OpeningcreditBalance = @numvendorcbalance ,
		OpeningdebitBalance = @numvendorbalance
	where
		CompanyId = @intCompanyId and VendorId = @intVendorId
	--added by madhu 24-12-2001
	select
		@intFinId = Min(FinancialId)
	from
		aFinancialYear
	where
		FinancialId > 0
	declare cur_vend cursor for
	select
		isnull(isnull(sum(cbillamt),0) -
		isnull(sum(cpmtamt),0),0),isnull(isnull(sum(dbillamt),0) -
		isnull(sum(dpmtamt),0),0),isnull(isnull(sum(dbillamt),0) -
		isnull(sum(dpmtamt),0),0), departmentid, creditoraccid,
		exchangerates, vendorid
	from
		vwsupplierledger
	where
		CompanyId = @intCompanyId and FinancialId = 0
	group by
		departmentid, creditoraccid, exchangerates, vendorid
	select
		@creditorsaccid = creditorsaccid
	from
		asettings
	where
		companyID=@intCompanyID
	if isnull(@creditorsaccid,'''')=''''
		set @creditorsaccid=''0''
		
	set @strsql = N''update aaccountfinyearopening set
			Openingamount= 0, Openingactualamount = 0, openingdepamount = 0
			where accountid in ('' + @creditorsaccid + N'') and companyID='' +
			convert(varchar(10),@intCompanyID)
	exec sp_Executesql @strsql
	open cur_vend
	fetch next from
		cur_vend
	into
		@numamount, @numactualamount, @numdepamount, @intdepid,	
		@intcreditorid, @strExRates, @intBillVendorID
	while @@FETCH_STATUS=0
	begin
		select
			@intcount=count(*)
		from
			aaccountfinyearopening
		where
			departmentid=@intdepid and accountid= @intcreditorid and
			FinancialId=@intFinId and CompanyId = @intCompanyId
		exec spConvertequiamount @intBillVendorID, ''v'', @intcreditorid,
			''a'', @strExRates, @numactualamount, @numactualamount output,''''
		if @intcount>0 		
			update aaccountfinyearopening set
				Openingamount=Openingamount+@numamount,
				openingactualamount=openingactualamount+@numactualamount,
				openingdepamount=openingdepamount+@numdepamount
			where
				departmentid=@intdepid and accountid = @intcreditorid and
				FinancialId=@intFinId and CompanyId = @intCompanyId
		else
			insert into  aaccountfinyearopening
				(CompanyId, accountid, FinancialId, departmentid,
				openingamount, openingactualamount, openingdepamount)
			values
				(@intCompanyId,	@intcreditorid,@intFinId,@intdepid,@numamount,
				@numactualamount,@numdepamount)
		insert into
			#temp
		values
			(@intcreditorid, @numamount, @numdepamount, @numactualamount)
		
		fetch next from
			cur_vend
		into
			@numamount, @numactualamount, @numdepamount, @intdepid,
			@intcreditorid, @strExRates, @intBillVendorID
	end
	close cur_vend
	deallocate cur_vend
	-- updating the trade receivable control account
	update aaccountmaster set
		Openingamount = a.amount,
		openingdepamount = a.depamount,
		openingactualamount = a.actualamount
	from
		(select
			sum(isnull(amount,0)) amount, sum(isnull(depamount,0)) depamount,
			sum(isnull(actualamt,0)) actualamount,creditorid
		from
			#temp
		group by
			creditorid) a
	where
		companyid = @intcompanyid and accountid = creditorid
	Return 0
	set nocount off
	drop table #temp
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spVendorLedger]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spVendorLedger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec  spVendorLedger 1,''20070701'',''20100701'','''',0,''1''
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
-- Last Modified on  : 10/12/02, 18/11/2003, 25/11/2003
-- Modified by   : Kishore
-- Comments   : v3
-- Modified by   : venki 010903, hariharan
-- Comments   : added opening balance dept filteration
--   : Modified to consider the billamt + pmtamt <> 0 to avoid adjustment entries
--                      : Added PaidAmount column (25/11/2003)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified by : VinothMurugan V.
--Date : 25/06/2010
--RefNo:01
--Purpose: Adding Vendorgroup
----------------------------------------------------------
--Modified by : Nidheesh P V
--Date : 04/06/2011
--RefNo:02
--Modification : To avoid the error while generating report for a particular vandor category
--Increased the size of  @strvendorid & @strsql
--Modified area : Vendor Statement report
-----------------------------------------------------------
CREATE proc [dbo].[spVendorLedger] @intCompanyID as int, @strFromdate as varchar(10),
@strToDate as varchar(10),
@strvendorid as varchar(max),   -- --RefNo:02
@intdepartmentid as int,
@strVenGroupid as varchar(50)
as
begin
set nocount on
Set ansi_warnings off
create table #temp(
companyid  int,
vendorid  int,
opdebitamt  numeric(18,2),
opcreditamt  numeric(18,2)
)
declare @dtFromdate as datetime,
@dtTodate as datetime,
@intvenid as int,
@dtfinstartdate as datetime,
@numopeningcredit as numeric(18,2),
@numopeningdebit as numeric(18,2),
@strsql as nvarchar(max),
@bitason as bit
-----------------------------------------------------------------------  RefNo:01
if (@strvendorid = '''') and  (@strVenGroupid <> '''')
begin
--declare @strvendorid as varchar(1000)
declare @count as int
declare @index as int
create table #temp1 (id int identity(1,1), Venid int,VenGrpId int)
insert into #temp1 select vendorid, VenGroupId from avendormaster  where VenGroupId = @strVenGroupid
--drop table #temp1 select * from #temp1
set @count =(select count(*) from #temp1)
set @index = 1
set @strvendorid=''''
while(@index < = @count )
begin
----print len(@strvendorid)
if  len(@strvendorid) = 0
begin
set @strvendorid =(select Venid from #temp1  where VenGrpId = @strVenGroupid and id= @index )
end
else
begin
set @strvendorid = (convert(varchar(8000), @strvendorid) +'',''+ convert(varchar(8000),(select Venid from #temp1
where VenGrpId = @strVenGroupid and id = @index)))
end
set @index= @index + 1
end
drop table #temp1
end
-----------------------------------------------------------------------
if @strvendorid <> '' ''
Begin
set @strvendorid = '' and vw.vendorid in ('' + @strvendorid + '')''
End
if (@strfromdate <>'''')
begin
set @dtfromdate = convert(datetime,@strfromdate)
set @bitason =0
end
else
Begin
set @bitason =1
End
set @dttodate = convert(datetime,@strtodate)
if (@bitason =0)
begin -- if the statement is for a period
set @strsql =N''declare opcur cursor for
SELECT vendorid FROM vwsupplierledger vw
WHERE vw.companyid ='' + convert(varchar(5),@intcompanyid) +
'' and vw.tdate >='''''' + convert(varchar(10),@dtfromdate,101) + ''''''
and (BillAmt + pmtamt) <> 0
and vw.tdate <='''''' + convert(varchar(10),@dttodate,101) + '''''''' + @strvendorid +
'' group by vendorid''
--print @strsql
exec sp_executesql @strsql
if (@intdepartmentid = 0)
begin
open opcur
fetch next from opcur
into @intvenid
while @@fetch_status =0
begin
set @numopeningcredit =0.0
set @numopeningdebit = 0.0
-- getting the opeingcredit by suming the total bill amount
SELECT  @numOpeningCredit = isnull((SELECT sum(billamt) FROM
vwsupplierledger vw
WHERE vw.companyid = @intcompanyid and tdate < @dtFROMDate and
vendorid = @intvenid and (BillAmt + pmtamt) <> 0),0)
-- getting the opeingdebit by suming the total payment amount
SELECT  @numOpeningDebit = isnull((SELECT sum(pmtamt)  FROM
vwsupplierledger c
WHERE c.companyid = @intcompanyid and c.vendorid = @intvenid
and tdate < @dtfromdate and (BillAmt + pmtamt) <> 0),0)
insert into #temp values (@intcompanyid, @intvenid, @numopeningdebit,
@numopeningcredit)
fetch next from opcur into @intvenid
end -- end for while
close opcur
deallocate opcur
end -- end for opening balance calculation
else
begin
open opcur
fetch next from opcur
into @intvenid
while @@fetch_status =0
begin
set @numopeningcredit = 0.0
set @numopeningdebit = 0.0
-- getting the opeingcredit by suming the total bill amount
SELECT  @numOpeningCredit = isnull((SELECT sum(billamt) FROM
vwsupplierledger vw
WHERE vw.companyid = @intcompanyid and vw.departmentid=@intdepartmentid and tdate < @dtFROMDate and
vendorid = @intvenid),0)
-- getting the opeingdebit by suming the total payment amount
SELECT  @numOpeningDebit = isnull((SELECT sum(pmtamt)  FROM
vwsupplierledger c
WHERE c.companyid = @intcompanyid and c.departmentid=@intdepartmentid and c.vendorid = @intvenid
and tdate < @dtfromdate and (BillAmt + pmtamt) <> 0),0)
insert into #temp values (@intcompanyid, @intvenid, @numopeningdebit,
@numopeningcredit)
fetch next from opcur into @intvenid
end -- end for while
close opcur
deallocate opcur
end -- end for opening balance calculation
end
if (@intdepartmentid = 0)
Begin
if (@bitason =0)
Begin
set @strsql = N''select one.vendorname, one.address1, one.address2, one.address3,
vw.companyid, vw.departmentid, vw.vendorid, vw.tdate, vw.secref, vw.tno, vw.cr,
vw.type, vw.remarks, vw.billamt, vw.pmtamt, vw.duedate, case when vw.age <> 0 then datediff(dd,tdate,'''''' +
convert(varchar(10),@dttodate,101) + '''''') else vw.age end age, vw.updatetime, vw.setdate,
vw.cbillamt, vw.cpmtamt, #temp.opcreditamt, #temp.opdebitamt, one.currencyname, one.symbol, IsNull(PaidAmount, 0) PaidAmount
from vwsupplierledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.vendorid = #temp.vendorid
left outer join (select c.companyid, vendorid, vendorname, currencyname, symbol, address1, address2,
address3 from avendormaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.vendorid = one.vendorid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strvendorid + '' and (BillAmt + pmtamt) <> 0 order by
one.vendorname, vw.tdate, vw.updatetime''
end
else -- for with out from date
Begin
set @strsql = N''select one.vendorname, one.address1, one.address2, one.address3,
vw.companyid, vw.departmentid, vw.vendorid, vw.tdate, vw.secref, vw.tno, vw.cr,
vw.type, vw.remarks, vw.billamt, vw.pmtamt, vw.duedate, case when vw.age <> 0 then datediff(dd,tdate,'''''' +
convert(varchar(10),@dttodate,101) + '''''') else vw.age end age, vw.updatetime, vw.setdate,
vw.cbillamt, vw.cpmtamt, 0.0 opcreditamt, 0.0 opdebitamt, one.currencyname, one.symbol, IsNull(PaidAmount, 0) PaidAmount
from vwsupplierledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.vendorid = #temp.vendorid
left outer join (select c.companyid, vendorid, vendorname, currencyname, symbol, address1, address2,
address3 from avendormaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.vendorid = one.vendorid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strvendorid + '' and (BillAmt + pmtamt) <> 0 order by
one.vendorname, vw.tdate, vw.updatetime''
end
end
else -- for department
Begin
if (@bitason =0)
Begin
set @strsql = N''select one.vendorname, one.address1, one.address2, one.address3,
vw.companyid, vw.departmentid, vw.vendorid, vw.tdate, vw.secref, vw.tno, vw.cr,
vw.type, vw.remarks, vw.billamt, vw.pmtamt, vw.duedate, case when vw.age <> 0 then datediff(dd,tdate,'''''' +
convert(varchar(10),@dttodate,101) + '''''') else vw.age end age, vw.updatetime, vw.setdate,
vw.cbillamt, vw.cpmtamt, #temp.opcreditamt, #temp.opdebitamt, one.currencyname, one.symbol, IsNull(PaidAmount, 0) PaidAmount
from vwsupplierledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.vendorid = #temp.vendorid
left outer join (select c.companyid, vendorid, vendorname, currencyname, symbol, address1, address2,
address3 from avendormaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.vendorid = one.vendorid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strvendorid + '' and
vw.departmentid ='' + convert(varchar(3),@intdepartmentid) + '' and (BillAmt + pmtamt) <> 0 order by one.vendorname,vw.tdate, vw.updatetime''
end
else -- for as on date
Begin
set @strsql = N''select one.vendorname, one.address1, one.address2, one.address3,
vw.companyid, vw.departmentid, vw.vendorid, vw.tdate, vw.secref, vw.tno, vw.cr,
vw.type, vw.remarks, vw.billamt, vw.pmtamt, vw.duedate, case when vw.age <> 0 then datediff(dd,tdate,'''''' +
convert(varchar(10),@dttodate,101) + '''''') else vw.age end age, vw.updatetime, vw.setdate,
vw.cbillamt, vw.cpmtamt, 0.0 opcreditamt, 0.0 opdebitamt, one.currencyname, one.symbol, IsNull(PaidAmount, 0) PaidAmount
from vwsupplierledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.vendorid = #temp.vendorid
left outer join (select c.companyid, vendorid, vendorname, currencyname, symbol, address1, address2,
address3 from avendormaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.vendorid = one.vendorid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + ''and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strvendorid + '' and
vw.departmentid ='' + convert(varchar(3),@intdepartmentid) + '' and (BillAmt + pmtamt) <> 0 order by one.vendorname,vw.tdate, vw.updatetime''
End
End
--print @strsql
exec sp_executesql @strsql
set nocount off
Set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff_BackUp]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendorarriveexdiff_BackUp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Modified on  : 08/02/2004
--Modified by   : Hariharan
--Comments  : modified the vendor selection
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
--modified by      : jyothish
--modified Date     : 14/07/2010
CREATE proc [dbo].[spvendorarriveexdiff_BackUp]
@intcompanyid as int, @strexrates as varchar(250),
@strcurdate as varchar(10),@intDepartmentID as int=0, @DepWise as char(1) = ''d'' as
begin
set nocount on
declare @intcount as int,
@intvendorid as int,
@numdepbal as numeric(18,2),
@numconsbal as numeric(18,2),
@numresbal as numeric(18,2),
@strvendorname as varchar(250),
@intDepCurrID as int,
@intvenCurrID as int,
@intConsCurrID as int,
@numdepamount as numeric(18,2),
@numConsamount as numeric(18,2),
@straccounttype as char(1),
@bitjournalcredit as bit,
@numdiffamt as numeric(18,2)
CREATE table #temp1(
companyid int,
vendorid int,
vendorname varchar(250),
CurrencyID int
)
CREATE table #temp2(
companyid int,
vendorid int,
vendorname varchar(250),
DepBalance numeric(18,2),
consbalance numeric(18,2),
resbalance numeric(18,2),
depamount  numeric(18,2),
consamount  numeric(18,2),
journalcredit bit
)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the vendor other than company currency are taken into the temp table
if @DepWise =''d''
Begin
-- insert into #temp1
--select v.companyid, v.vendorid, vendorname,currencyid from avendormaster v,
--ASHOPVENDORDETAILS s where v.companyid =@intcompanyid and currencyid <> @intDepCurrID
--and v.vendorid = s.vendorid and s.shopid in
--(Select shopid from ashops where departmentid = @intDepartmentid and
--companyid = @intCOmpanyId)
---jyothish modifed querry
insert into #temp1
select v.companyid, v.vendorid, vendorname,currencyid from avendormaster v, vwsupplierledger led
where v.VendorID=led.VendorId and DepartmentId=@intDepartmentid and v.companyid =@intcompanyid
End
Else
Begin
insert into #temp1
select V.companyid, V.vendorid, vendorname,currencyid from avendormaster v
, ASHOPVENDORDETAILS s
where v.companyid =@intcompanyid and currencyid <> @intConsCurrID
and v.vendorid = s.vendorid and s.shopid in
(Select shopid from ashops where departmentid = @intDepartmentid and
companyid = @intCOmpanyId)
End
select @intcount = count(*) from #temp1
while @intcount <> 0
begin -- for while
select @intvendorid = vendorid, @strvendorname = vendorname,
@intvenCurrID=currencyid from #temp1
set @numconsbal =0.0
set @numresbal =0.0
if @DepWise =''d''
select @numresbal = sum(billamt) - sum(pmtamt), @numdepbal = sum(dbillamt) - sum(dpmtamt)
from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid
and departmentID=@intDepartmentID
and tDate <= @strcurdate
else
select @numresbal = sum(billamt) - sum(pmtamt), @numdepbal = sum(cbillamt) - sum(cpmtamt)
from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid
and departmentID=@intDepartmentID
and tDate <= @strcurdate
if @DepWise =''d''
exec spConvertequiamount @intvenCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
else
exec spConvertequiamount @intvenCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
if abs(@numdepbal - @numdepamount) >= 1 -- this has the exchange difference
begin
if (@numdepamount > @numDepbal)
set @bitjournalcredit =1
if (@numdepamount < @numDepbal)
set @bitjournalcredit =0
set @numdiffamt  = abs(@numdepamount - @numDepbal)
if @DepWise =''d''
Begin
exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
@numConsbal,@numresbal,@numdepamount,@numConsamount , @bitjournalcredit)
End
else
Begin
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
@numConsbal,@numresbal,@numConsamount ,@numdepamount, @bitjournalcredit)
End
end
delete from #temp1 where vendorid = @intvendorid
select @intcount = count(*) from #temp1
end -- for while
select * from #temp2
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spvendorarriveexdiff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Modified on  : 08/02/2004
--Modified by   : Hariharan
--Comments  : modified the vendor selection
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Client DB)
----modified by      : jyothish
--modified Date     : 15/12/2011
/*
This SP modified and send to SIMDI as emergency. So to keep a back up I changed name of SP and placed in same server.
*/
/*
Ref No : 01
Modified	on : 18-04-2012
Modifed		By : Shine Das
Comments	   : Department wise TB was not tallying when adjustment done.
Corrected it. (For consolidation option only)
*/
CREATE proc [dbo].[spvendorarriveexdiff]
@intcompanyid as int, @strexrates as varchar(250),
@strcurdate as varchar(10),@intDepartmentID as int=0, @DepWise as char(1) = ''d'' as
begin
set nocount on
declare @intcount as int,
@intvendorid as int,
@numdepbal as numeric(18,2),
@numconsbal as numeric(18,2),
@numresbal as numeric(18,2),
@strvendorname as varchar(250),
@intDepCurrID as int,
@intvenCurrID as int,
@intConsCurrID as int,
@numdepamount as numeric(18,2),
@numConsamount as numeric(18,2),
@straccounttype as char(1),
@bitjournalcredit as bit,
--@numdiffamt as numeric(18,2),
@numdiffamtDep as numeric(18,2),
@numdiffamtCon as numeric(18,2),
@numEquiAmnt as numeric(18,2),
@numResBalInConsCurrency as numeric(18,2)    --Ref No : 01
CREATE table #temp1(
companyid int,
vendorid int,
vendorname varchar(250),
CurrencyID int
)
CREATE table #temp2(
companyid int,
vendorid int,
vendorname varchar(250),
DepBalance numeric(18,2),
consbalance numeric(18,2),
resbalance numeric(18,2),
depamount  numeric(18,2),
consamount  numeric(18,2),
journalcredit bit
)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the vendor other than company currency are taken into the temp table
if @DepWise =''d''
Begin
insert into #temp1
select v.companyid, v.vendorid, vendorname,currencyid from avendormaster v, vwsupplierledger led
where v.VendorID=led.VendorId and DepartmentId=@intDepartmentid and v.companyid =@intcompanyid
--select distinct v.companyid, v.vendorid, vendorname,currencyid from avendormaster v left outer join
--ASHOPVENDORDETAILS s on v.vendorid = s.vendorid and v.companyid =@intcompanyid and currencyid <> @intDepCurrID
--left outer join ashops sh on s.ShopID=sh.ShopID and sh.companyid =v.companyid
--and sh.departmentid = @intDepartmentid
---jyothish modifed querry  15/12/2011
End
Else
Begin
insert into #temp1
select distinct V.companyid, V.vendorid, vendorname,currencyid from avendormaster v left outer join
ASHOPVENDORDETAILS s  on v.vendorid = s.vendorid and v.companyid =@intcompanyid and currencyid <> @intConsCurrID
left outer join ashops sh on s.ShopID=sh.ShopID and sh.companyid =v.companyid
and sh.departmentid = @intDepartmentid
End
select @intcount = count(*) from #temp1
while @intcount <> 0
begin -- for while
select @intvendorid = vendorid, @strvendorname = vendorname,
@intvenCurrID=currencyid from #temp1
set @numconsbal = 0.0
set @numdepbal = 0.0
set @numresbal = 0.0
set @numEquiAmnt = 0.0
set @numdiffamtDep  = 0.0
set @numdiffamtCon  =0.0
if @DepWise =''d''
BEGIN
select @numresbal = sum(billamt) - sum(pmtamt), @numdepbal = sum(dbillamt) - sum(dpmtamt),@numconsbal = sum(cbillamt) - sum(cpmtamt)
from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid
and departmentID=@intDepartmentID and tDate <= @strcurdate
END
else
BEGIN
select @numresbal = sum(billamt) - sum(pmtamt), @numconsbal = sum(cbillamt) - sum(cpmtamt),@numdepbal = sum(dbillamt) - sum(dpmtamt)
from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid
and departmentID=@intDepartmentID and tDate <= @strcurdate
END
---------------------------------------------------------------
if @DepWise =''d''
BEGIN
set @numEquiAmnt=@numdepbal
exec spConvertequiamount @intvenCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
END
else
BEGIN
set @numEquiAmnt=@numconsbal
--Ref No : 01 Commented Below
--exec spConvertequiamount @intvenCurrID, ''m'', @intConsCurrID,
--''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
--Ref No : 01  Added Below
exec spConvertequiamount @intvenCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numresbal, @numResBalInConsCurrency output,  ''r''
END
---------------------------------------------------------------
--Ref No : 01 Commented Below
/*
--------if abs(@numEquiAmnt - @numdepamount) >= 1 -- this has the exchange difference
--------BEGIN
--------if (@numdepamount > @numEquiAmnt)
--------BEGIN
-------- set @bitjournalcredit =1
--------END
--------if (@numdepamount < @numEquiAmnt)
--------BEGIN
-------- set @bitjournalcredit =0
--------END
*/ --Ref No : 01 End
if abs(@numEquiAmnt - @numResBalInConsCurrency) >= 1 -- this has the exchange difference
BEGIN
if (@numResBalInConsCurrency > @numEquiAmnt)
BEGIN
set @bitjournalcredit =1
END
if (@numResBalInConsCurrency < @numEquiAmnt)
BEGIN
set @bitjournalcredit =0
END
------------------------
if @DepWise =''d''
begin
set @numdiffamtDep  = abs(@numdepamount - @numEquiAmnt)
set @numdiffamtCon  = abs(@numdepamount - @numconsbal)
end
else
begin
set @numdiffamtDep  = abs(@numdepamount - @numdepbal)
--set @numdiffamtCon  = abs(@numdepamount - @numEquiAmnt)        --Ref No : 01 Commented
set @numdiffamtCon  = abs(@numResBalInConsCurrency - @numconsbal)
end
-------------------------
if @DepWise =''d''
BEGIN
---exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
---''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
---insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
---@numConsbal,@numresbal,@numdepamount,@numConsamount , @bitjournalcredit)
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
@numConsbal,@numresbal,@numdiffamtDep,@numdiffamtCon, @bitjournalcredit)
END
else
BEGIN
--Ref No : 01 Commented Below
---exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
---''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
--Ref No : 01 Added Below
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamtCon, @numdiffamtDep output,  ''r''
---insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
---@numConsbal,@numresbal,@numConsamount ,@numdepamount, @bitjournalcredit)
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,
@numConsbal,@numresbal,@numdiffamtDep,@numdiffamtCon , @bitjournalcredit)
END
END  ---END OF exchange difference
delete from #temp1 where vendorid = @intvendorid
select @intcount = count(*) from #temp1
end -- for while
select * from #temp2
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spULshopGoodsArrival]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULshopGoodsArrival]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on : 17/07/2002
-- modified by      : leo
----------------------------------------------------------------------------
-- Modified on      : 02/01/2002, 01/10/2003
-- Modified by      : Kishore, Hariharan R
-- Comment          : Added code to insert dep amount and to convert amount
--verified by Hariharan on 07/01/2003
--for direct despatch to shop, stock transfer control account is debited from
--the department in which it is costed
----------------------------------------------------------------------------
--Modified on : 26/05/2010
--Modified By : Nidheesh P V
--Comment : while converting to equi. amount(spConvertequiamount) the fromaccountid
--was selected as of the customermaster.But included a case(for companymaster) in the
--(spConvertequiamount)and passed that type from here to get fromaccountid as inventory accountid
----------------------------------------------------------------------------
--Ref No1
--Modified on : 30/12/2011
--Modified By : MANUNADH.U
--Comment : Stock Transfer Control Account is not posted correctly
----------------------------------------------------------------------------
CREATE proc [dbo].[spULshopGoodsArrival] @intCompanyID as int, @intshopid as int as
begin
set nocount on
Declare @intJournalID as int
Declare @intJournalDetailID as int
Declare @intFinancialID as int
Declare @dtgaDate as datetime
Declare @strgaNo as varchar(50)
Declare @intgaid as int
Declare @strRemarks as varchar(250)
Declare @numTotalValue as numeric(18,2)
Declare @intinventoryaccid as int
Declare @intstocktransferaccid as int
declare @intcomcurid as int
declare @inttodepid as int
declare @dtutime as datetime
declare @intFailcount as int -- for getting the count of items with item rate 0 or null in detail and itemmaster tables
declare @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),@intFromDepId as int,@intHQDespatchID as int,@numothdepamount as numeric(18,2),
@numCompamount as numeric(18,2)
set @numDepExRate = 0.00
set @numConExRate = 0.00
set @intCurrencyId = 0.00
set @strExRates = 0.00
set @numAccExRate = 0.00
set @numTransEr = 0.00
set @numAaccAmt = 0.00
set @intFromDepId  = 0
set @intHQDespatchID = 0
set @numothdepamount = 0.0
/*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 @intInventoryaccid = inventoryid, @intstocktransferaccid = stocktransfercontrolacc,
@strzerorate = substring(isnull(futurevc,''''),1,1)
from apackagesettings where companyid = @intcompanyid
set @intJournalID = @intJournalID + 1
Declare garrcur cursor for
SELECT gahArrivalID, gahArrivalDate, gahArrivalNo, gahremarks,gahdepartmentid todep, updatetime, gahConExRate,
gahDepExRate,gahExchangeRates, gahhqdespatchid
FROM  LosGoodsArrivaltoShopHeader ga
WHERE  gahCancelled = 0 and gahposted = 0 and ga.gahShopid = @intshopid and gahTransFinished = 1
open garrcur
fetch next FROM garrcur into @intgaid, @dtgadate, @strgano,@strremarks, @inttodepid, @dtutime, @numConExRate,
@numDepExRate, @strExRates, @intHQDespatchID
while @@Fetch_status = 0
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 @dtgadate 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 losgoodsarrivaltoshopdetail, aitem where
gadarrivalid= @intgaid and gadshopid = @intshopid and gaditemid = itemid
and (gadcostprice=null or gadcostprice=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
begin
-- to update the item rate to the gadcostprice
update losgoodsarrivaltoshopdetail set gadcostprice = itemrate from aitem
where (gadcostprice=null or gadcostprice=0) and gadarrivalid= @intgaid and gadshopid = @intshopid and
gaditemid = itemid
SELECT @numTotalValue = sum(gadItemGoodQuantityArrived * gadcostprice)
FROM LOsGoodsArrivaltoShopdetail
WHERE gadShopid  = @intshopid and gadArrivalID = @intgaid group by gadShopid  , gadArrivalID
insert into moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno, remarks,financialID,Type,
CurrencyID,chequedate,updatetime)
values(@intJournalID, @intCompanyID, @dtgaDate, @strgaNo,@strremarks, @intFinancialID,''sga'',
@intCurrencyId,@dtgadate, @dtutime)
--FOR POSTING THE DIRECT DIESPATCHES OPPOSITE ENTRIES
select @intFromDepId = ch.pbhdepartmentid from losGoodsArrivaltoShopHeader ah,
ahqdespatchnoteheader dh,ahqdespatchnotemain dnm, losppurchasebillheader ch
where ah.gahshopid = dh.dhshopId and ah.gahhqdespatchid = dh.dhDespatchnoteID
and dh.dhDespatchNoteMainID = dnm.dnmDespatchNoteID and dnm.dnmbillid = ch.pbhBillID
and ch.pbhcancelled =0 and dnm.dnmcancelled = 0 and ah.gahArrivalId = @intgaid
and ah.gahshopid = @intShopID
set @intJournalDetailID = 1
/* debiting the inventory account with the full */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount, DepAmount,departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intInventoryaccid,
@numTotalValue * @numConExRate, @numTotalValue,@numTotalValue * @numDepExRate, @inttoDepID)
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intstocktransferaccid
exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output
--select * from sysobjects where type=''p'' and name like ''%convertcurr%''
exec spConvertCurrency @numTransEr, @numAccExRate,@numTotalValue,@numAaccAmt output
/* debiting the Stock account with the full */
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID, Amount,
actualAmount,DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intstocktransferaccid,
@numTotalValue * @numConExRate,@numaAccAmt, @numTotalValue * @numDepExRate, @inttoDepID  )
---*****finish of the direct despatch posting of costed department
if @intHQDespatchID >0
Begin
select @intCurrencyId = CurrencyId from aAccountMaster
where AccountId = @intInventoryAccId  and CompanyId = @intCompanyId
--<<Ref No1>>
--<old code is commented
-- exec spConvertequiamount @intCurrencyId, ''co'', @intFromDepId, ''d'', @strExRates,
--@numTotalValue, @numothdepamount output, ''n''
-- exec spConvertequiamount @intCurrencyId, ''co'', @intcomcurid, ''m'', @strExRates,
--@numTotalValue, @numCompamount  output, ''n''
-->old code is commented
--<<Ref No1>>
set @intJournalDetailID = @intJournalDetailID + 1
/* Crediting the inventory account of costed department with the full */
--<<Ref No1>>
-- insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
--Amount, actualAmount, DepAmount,departmentID)
-- values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intInventoryaccid, @numCompamount,
--@numTotalValue,@numothdepamount, @intFromDepId)
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
Amount, actualAmount, DepAmount,departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intInventoryaccid,
@numTotalValue * @numConExRate,@numTotalValue,@numTotalValue * @numDepExRate, @intFromDepId)
--<<Ref No1>>
set @intJournalDetailID = @intJournalDetailID + 1
-- for converting the amount --->
select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intstocktransferaccid
exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output
exec spConvertCurrency @numTransEr, @numAccExRate,@numTotalValue,@numAaccAmt output
/* debiting the Stock transfer account of costed department with the full amount */
--<<Ref No1>>
-- insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
--Amount, actualAmount,DepAmount, departmentID)
-- values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intstocktransferaccid,@numcompamount,
--@numaAccAmt, @numothdepamount, @intFromDepId )
insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit, AccountID,
Amount, actualAmount,DepAmount, departmentID)
values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intstocktransferaccid,
@numTotalValue * @numConExRate,@numaAccAmt, @numTotalValue * @numDepExRate, @intFromDepId )
--<<Ref No1>>
End ---*****finish of the direct despatch posting of costed department
/* mark the record as postED */
update LOsGoodsArrivaltoShopHeader set gahposted  = 1
WHERE gahshopid = @intshopid and gaharrivalid = @intgaid
set @intJournalID = @intJournalID + 1
set @intHQDespatchID = 0
end  -- finish of block if the transaction is posted based on the if condition *** hari 011211
fetch next FROM garrcur into @intgaid, @dtgadate, @strgano,@strremarks, @inttodepid,  @dtutime,@numConExRate,
@numDepExRate, @strExRates, @intHQDespatchID
end
Close garrcur
Deallocate garrcur
set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spopeningvendorbalanceperiod]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spopeningvendorbalanceperiod]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spopeningvendorbalanceperiod    Script Date: 18/01/2003 9:45:49 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
CREATE proc [dbo].[spopeningvendorbalanceperiod] (@intcompanyid as int, @intvendorid as int,
@strfromdate as varchar(10)) as
begin
	declare @dtfromdate as datetime
	declare @numbalance as numeric(18,2)
	
	set @dtfromdate = convert(datetime, @strfromdate)
	set @numbalance = 0.0
	select @numbalance = @numbalance + (sum(billamt) - isnull(sum(pmtamt),0)) from
	vwsupplierledger
	where tdate < @dtfromdate and companyid = @intcompanyid
	 and vendorid = @intvendorid
	group by companyid, vendorid
	select @numbalance Balance
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spOpeningstockondate]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spOpeningstockondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--Modified by  : 18/05/04
--Comments  : added Costprice
CREATE procedure [dbo].[spOpeningstockondate] ( @intItemId as int, @fromdate as varchar(10),
@intGodownID as int,@intdepartmentid as int =0,@intcompanyid as int=1 ,@outputopenstock as numeric(18,3)=0 output)as
declare
@Curstock as numeric(18,3),
@openingstock as numeric(18,3),
@transqty as numeric(18,3),
@dtFromDate as datetime,
@transcostprice as numeric(18,2),
@costprice as numeric(18,2),
@Itemctr as numeric(16,2),
@opencostprice as numeric(18,2),
@ToCurr as integer,
@invCurrid as integer,
@exrate as numeric(18,2)
set nocount on
begin
SET @Curstock = 0.0
SET @openingstock = 0.0
set @transqty = 0.0
set @transcostprice =0.0
set @costprice =0.0
set @Itemctr =0.0
set @opencostprice =0.00
set @dtFromDate = convert(datetime,@fromdate,101)
Select @openingstock = sum(isnull(gsopeningstock,0.0)) from moigodownstock where
gsitemid=@intItemid and gsgodownid=@intgodownid
select @invCurrid=b.currencyid from apackagesettings a,acurrencymaster b,
aaccountmaster c where accountid=inventoryid and a.companyid=b.companyid and
c.CurrencyID=b.currencyid
if @intdepartmentid =0
begin --Getting Company Curr
select @Tocurr= a.currencyid from acurrencymaster a,
acompanymaster b where a.companyid=b.companyid  and
a.CurrencyID=b.currencyid
end
else
begin ----Getting dep Curr
select  @Tocurr= a.currencyid from acurrencymaster a,
adepartmentmaster b where a.companyid=b.companyid  and
a.CurrencyID=b.depcurrencyid and departmentid=@intdepartmentid
end
exec spGetExchangeRate @intcompanyid,@invCurrid,@Tocurr, @ExRate output
select @itemctr=count(cditemid),@opencostprice=sum(cdNewItemCostPrice*@ExRate) from loacostingheader,
loacostingdetail where chcostingid=cdcostingid and chcancelled=0 and cdItemID=@intitemid
and chcostingid=0
if @itemctr=0
begin
select top 1 @opencostprice=cdOldItemCostPrice*@ExRate from loacostingheader,loacostingdetail
where chcostingid=cdcostingid and chcancelled=0 and
cdItemID=@intitemid and chcostingid<>0 order by chCostingDate asc
end
if @intdepartmentid =0
begin
select  @transcostprice=isnull(sum(concostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid and godownid=@intgodownid
end
else
begin
select  @transcostprice=isnull(sum(depcostprice * isnull(Transqty*mode,0.0)),0.00), @transqty = isnull(sum(TRansqty*mode),0.0) from  vwgdnbincard where
gdate< @dtFromDate and itemid=@intitemid and godownid=@intgodownid
end
set @curstock= isnull(@openingstock,0.0) + isnull(@transqty,0.0)
set @costprice = isnull(@opencostprice * @openingstock,0.0)+isnull(@transcostprice,0.0)
if @curstock = 0
set @costprice = 0.0
if @outputopenstock =1
begin
set @outputopenstock = @curstock
end
else
select @intItemid itemid,@curstock openstock,@costprice costprice
end' 
END
GO
/****** Object:  View [dbo].[vwimportqty]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwimportqty]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwimportqty    Script Date: 18/01/2003 9:45:41 PM ******/
/****** Object:  View dbo.vwimportqty    Script Date: 14/09/2002 12:48:10 AM ******/
/****** Object:  View dbo.vwimportqty    Script Date: 31/07/2002 2:00:31 PM ******/
CREATE view [dbo].[vwimportqty] as
select itemid, GDate, mode, sum(Transqty) transqty from
vwgdnbincard where type=''Shipment Arrival'' group by GDate, itemid, mode'
GO
/****** Object:  View [dbo].[vwHQserinvandrecamount]    Script Date: 10/06/2012 14:17:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHQserinvandrecamount]'))
EXEC dbo.sp_executesql @statement = N'
--Modified By  : Hariharan
--Modified Date : 04/08/2004
CREATE view [dbo].[vwHQserinvandrecamount] as
select vwinv.companyid,null as shopid, vwinv.invoiceid,vwinv.departmentid, vwinv.invoiceno,vwinv.ReferenceNo,
vwinv.invoicedate,vwinv.duedate, vwinv.customerid, vwinv.amount,
(sum(isnull(vwrec.settledamt,0)) + sum(isnull(Settleamt,0))) settled, ''HQI'' Type from
vwHQSerinvoice vwinv left outer join
vwHQinvoicereceipt vwrec on vwinv.companyid=vwrec.companyid
and vwinv.invoiceid = vwrec.HQaccountsinvoiceid
left outer join (Select CompanyId, DepartmentID, sum(amtSettled) settleamt, invoiceid
from vwRecSettlementDetails group by CompanyId, DepartmentID, invoiceid) csett
on vwinv.companyid = csett.companyid and vwinv.invoiceid = csett.invoiceid
group by vwinv.companyid,vwinv.invoiceid,vwinv.departmentid, vwinv.invoiceno,
vwinv.invoicedate,vwinv.duedate, vwinv.customerid,
vwinv.amount,vwinv.ReferenceNo'
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionDay]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDailySalesCollectionDay]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------
-- Created by   : Kishore
-- Created on   : 01/04/2003 (on international fools'' day)
-- Comments     : Created from view vwDailySalesCollection
--                In order to make it faster
--		Hari created for day end
-------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spDailySalesCollectionDay] (@dtFrom AS Varchar(10), @dtTo AS Varchar(10))  AS
BEGIN
	SELECT Summary.CompanyId, Summary.DepartmentId, Summary.ShopId, BillDate,
	CONVERT(numeric(18,2), SUM(Cashsales)) CashSales,
	CONVERT(numeric(18,2), SUM(receipts)) Receipts,
	CONVERT(numeric(18,2), SUM(payments)) Payments ,
	CONVERT(numeric(18,2), SUM(creditsales)) CreditSales,
	CONVERT(numeric(18,2), SUM(creditcard)) CreditCard,
	CONVERT(numeric(18,2), SUM(debitcard)) DebitCard,
	CONVERT(numeric(18,2), SUM(LocalPurchase)) LocalPurchase,
	MIN(ISNULL(aShops.ShopName, '''')) ShopName,
	MIN(ISNULL(aDepartmentMaster.DepartmentName, '''')) DepartmentName
	FROM
	(SELECT cs.companyid ,departmentid, shopid, billdate,
	SUM(actamount) Cashsales, 0.0 AS creditcard, 0.0 AS debitcard,
	0.0 AS receipts, 0.0 AS payments ,
	0.0 AS creditsales,0.0 AS LocalPurchase
	FROM vwCashsalestruncated cs, aaccountMaster am
	WHERE am.misc = ''CA''
	AND cs.accountid = am.accountid
	AND cs.companyid = am.companyid
	AND Cash = 1
	AND BillDate BETWEEN @dtFrom AND @dtTo
	GROUP BY cs.companyid ,departmentid, shopid, billdate
	UNION ALL
	SELECT cs.companyid ,departmentid, shopid, billdate,
	0.0 Cashsales, CONVERT(numeric(18,2),SUM(actamount)) AS creditcard,
	0.0 AS debitcard, 0.0 AS receipts, 0.0 AS payments ,
	0.0 AS creditsales,0.0 AS LocalPurchase
	FROM vwCashsalestruncated cs, aaccountMaster am
	WHERE am.misc = ''CC''
	AND cs.accountid = am.accountid
	AND cs.companyid = am.companyid
	AND Cash = 1
	AND BillDate BETWEEN @dtFrom AND @dtTo
	GROUP BY cs.companyid ,departmentid, shopid, billdate	--creditcard sales
	UNION ALL
	SELECT cs.companyid,departmentid, shopid, billdate,
	0.0 Cashsales, 0.0 AS creditcard,
	CONVERT(numeric(18,2), SUM(actamount)) AS debitcard, 0.0 AS receipts,
	0.0 AS payments ,
	0.0 AS creditsales,0.0 AS LocalPurchase
	FROM vwCashsalestruncated cs, aaccountMaster am
	WHERE am.misc = ''DC''
	AND cs.accountid = am.accountid
	AND cs.companyid = am.companyid
	AND Cash = 1
	AND BillDate BETWEEN @dtFrom AND @dtTo
	GROUP BY cs.companyid,departmentid, shopid, billdate	--debit card sales
	UNION ALL
	SELECT drcompanyid,drdepartmentid, drshopid, drdate, 0.0 AS Cashsales,
	0.0 AS creditcard, 0.0 AS debitcard,
	CONVERT(numeric(18,2),SUM(drAmount)) receipts, 0.0 AS payments,
	0.0 AS creditsales,0.0 AS LocalPurchase
	FROM losDummyReceiptHeader rh, acustomerMaster cm
	WHERE drcancelled = 0
	AND rh.drcustomerid = cm.customerid
	AND rh.drcompanyid = cm.companyid
	AND drDate BETWEEN @dtFrom AND @dtTo
	GROUP BY drcompanyid, drdepartmentid, drshopid, drdate
	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
	--shopid made to "0" to get the collection on the particular department of each shop particular day - hari 030304
	SELECT rh.companyid,rh.departmentid, 0, rh.receiptdate, 0.0 AS Cashsales,
	0.0 AS creditcard, 0.0 AS debitcard,
	CONVERT(numeric(18,2),SUM(rh.amount*exchangerate)) receipts,
	0 AS payments, 0 AS creditsales,0 AS LocalPurchase FROM
	receiptvoucherheader rh
	WHERE rh.cancelled = 0
	AND ((rh.dummyreceiptid is null AND rh.recshopid is null) or
	(rh.dummyreceiptid=0 AND rh.recshopid=0) )
	AND rh.Customerid is not null
	AND rh.ReceiptDate BETWEEN @dtFrom AND @dtTo
	GROUP BY rh.companyid,rh.departmentid, rh.receiptdate
	UNION ALL
	SELECT phcompanyid,phdepartmentid, phshopid, phPaymentDate,
	0.0 AS Cashsales, 0.0 AS creditcard,
	0.0 AS debitcard ,0.0 AS receipts,
	CONVERT(numeric(18,2),SUM(phAmount)) AS payments, 0.0 AS creditsales ,
	0.0 AS LocalPurchase
	FROM losPaymentVoucherHeader ph
	WHERE phcancelled = 0
	AND phPaymentDate BETWEEN @dtFrom AND @dtTo
	GROUP BY phcompanyid, phdepartmentid, phshopid, phPaymentDate
	UNION ALL
	--credit sales
	SELECT cs.companyid ,departmentid, shopid, billdate, 0.0 Cashsales,
	0.0 AS creditcard, 0.0 AS debitcard,
	0.0 AS receipts, 0.0 AS payments ,
	CONVERT(numeric(18,2),SUM(actamount)) AS creditsales, 0.0 AS LocalPurchase
	FROM vwCashsalestruncated cs
	WHERE Cash = 0
	AND BillDate BETWEEN @dtFrom AND @dtTo	
	GROUP BY cs.companyid ,departmentid, shopid, billdate
	UNION ALL
	--local purchASe - madhu 23/08/01
	SELECT lh.lphcompanyid, lh.lphdepartmentid, lh.lphshopid,
	lh.lphbilldate,0.0 Cashsales,0.0 AS creditcard,
	0.0 AS debitcard,0.0 AS receipts,0.0 AS payments,0.0 AS creditsales,
	CONVERT(numeric(18,2),SUM(lphbillamount)) AS LocalPurchase
	FROM losLocalPurchaseheader lh, adepartmentMaster d
	WHERE lh.lphDepartmentID = d.departmentid
	AND lh.lphCashpurchase = 1
	AND lphcancelled = 0
	AND lh.lphBillDate BETWEEN @dtFrom AND @dtTo		
	GROUP BY lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate) Summary
	LEFT OUTER JOIN aShops
	ON Summary.ShopId = aShops.ShopId
	LEFT OUTER JOIN aDepartmentMaster
	ON Summary.DepartmentId = aDepartmentMaster.DepartmentId
	AND Summary.CompanyId = aDepartmentMaster.CompanyId
	GROUP BY Summary.companyid, Summary.departmentid, Summary.shopid, billdate
END
-------------------------------------------------------------------' 
END
GO
/****** Object:  View [dbo].[vwCreditSales]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditSales]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on           : 08/05/2004, 27/05/2004
--Modified by           : Hariharan R
--Comments              : Additional table loscallbookingheader is added for credit service booking invoices 020321
--                      : Additional table losserviceinvheader is added for credit service booking invoices 020321
--   : specialinvoice confirmed finish check is given
--   : for service sector invoice, customerid is taken from invoice table
--   : as in booking and estimation CustomerId is removed of mandatory check
--   : Other charges given in group by clause to avoid doubling in Invoice queries
--   : benzigar 15/06/2009 Changed special invoice
--   : sebin 22/06/09 for updating special invoice
------------------------------------------------------
--Modified By : Nidheesh P V
--Modified on : 07/12/2010
--Comments : Added F&B credit type
-------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwCreditSales] as
select
ihcompanyid, ihshopid, ihCustomerID, ihinvoicedate, ihinvoiceno, 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, convert(numeric(18,2),ihsettledamount) settledamount,
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 ihproforma = 0 and ih.ihtype =''i''
and ihShopId = s.ShopId and ihCompanyID = s.Companyid
group by
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihinvoiceno , ihCustomerID,
ihbankcashaccid,ihexchangerate, ihdepartmentid, ihsettledamount , ihdepexrate,
ocd.ioAmount, s.futurevarchar, ih.ihdutypaidby
union all
--select
-- ihcompanyid, ihshopid, ihCustomerID, ihinvoicedate, ihinvoiceno, ihbankcashaccid,
-- convert(numeric(18,2),sum(vw.idunitprice)  ) as amount,
-- convert(numeric(18,2),sum(vw.idunitprice) * ihdepexrate) as damount,
-- convert(numeric(18,2),sum(vw.idunitprice) * ihexchangerate) as camount, 0 ihcashinvoice,
-- convert(numeric(18,2),ih.ihsettledamount) Settledamount, ihdepartmentid departmentid
--from
-- losspecialinvoiceheader ih, losspecialinvoicedetail invd, vwShopSplInvItemAmount vw
--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
-- ihproforma = 0 and ihTransfinished = 1
--group by
-- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid,ihinvoiceno, ihCustomerID,
-- ihbankcashaccid,ihexchangerate, ihdepartmentid, ihsettledamount, ihdepexrate
select
ihcompanyid, ihshopid, ihCustomerID, ihinvoicedate, ihinvoiceno, ihbankcashaccid,
convert(numeric(18,2),max(ih.ihinvoiceamount)  ) as amount,
case when ihNoofOCDetails > 0 then -convert(numeric(18,2),sum(invd.idUnitPrice) * ihdepexrate)
when idRateType=1 then -convert(numeric(18,2),sum(invd.idUnitPrice) * ihdepexrate)
else  convert(numeric(18,2),sum(invd.idUnitPrice) * ihdepexrate) end damount,
case when ihNoofOCDetails > 0 then -convert(numeric(18,2),sum(invd.idUnitPrice) * ihexchangerate)
when idRateType=1 then -convert(numeric(18,2),sum(invd.idUnitPrice) * ihexchangerate)
else convert(numeric(18,2),sum(invd.idUnitPrice) * ihexchangerate) end camount,
0 ihcashinvoice,
convert(numeric(18,2),ih.ihsettledamount) Settledamount, ihdepartmentid departmentid
from
losspecialinvoiceheader ih, losspecialinvoicedetail invd
where
ih.ihshopid = invd. idshopid and
ih.ihinvoiceid = invd.idinvoiceid and ihcancelled=0 and ihcashinvoice =0 and
ihproforma = 0 and ihTransfinished = 1  --and ihinvoicedate=''20090803'' and ihshopid =6
group by
ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid,ihinvoiceno, ihCustomerID,
ihbankcashaccid,ihexchangerate, ihdepartmentid, ihsettledamount, ihdepexrate,ihNoofOCDetails,idRateType
union all
select
vws.sicompanyid, vws.sishopid, lah.aicustomerid, vws.siinvoicedate, vws.aiinvoiceno,
lah.aibankcashid , convert(numeric(18,2),vws.siamount ),
convert(numeric(18,2),vws.siamount * aidepexrate),
convert(numeric(18,2),vws.siamount * aiexchangerate),  lah.aicashinvoice ,
convert(numeric(18,2),vws.Settledamount) Settledamount, aidepartmentid departmentid
from
vwshopservicesales vws , LOsAccountsInvoiceHeader lah
where
aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and
aishopid = sishopid and aicashinvoice = 0
union all
select
ai.CompanyID, null, ai.customerid, ai.invoicedate, ai.invoiceno, ai.bankcashid,
convert(numeric(18,2),sum(serviceqty * amount) ),
convert(numeric(18,2),sum(serviceqty * amount) * depexrate),
convert(numeric(18,2),sum(serviceqty * amount) * exchangerate), 0,
convert(numeric(18,2),isnull(sd.settledamt,0)), ai.departmentid
from
serviceinvoicedetails ser, accountsinvoiceheader ai
left outer join vwaccountinvsettledamount sd
on ai.companyid = sd.companyid and ai.invoiceid = sd.accid
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.customerid, ai.invoicedate,ai.invoiceno, ai.exchangerate,
ai.bankcashid,ai.departmentid, sd.settledamt, ai.depexrate
union all
--for credit service booking invoices 020321
Select
inv.serinvhcompanyid, inv.serinvhshopid, serinvhCustomerId serbookhcustomerid,
inv.serinvhdate, serinvno, serinvhcashacc, convert(numeric(18,2), inv.serinvhamount ),
convert(numeric(18,2), inv.serinvhamount * inv.seinvhdepexrate),
convert(numeric(18,2), inv.serinvhamount * inv.serinvhcmpexrate), 0 ,
convert(numeric(18,2),isnull(sd.settledamt,0)), serinvhdepartmentid
from
losserviceinvheader inv  Left Outer join  vwbookservicesettlements sd  on
inv.serinvhid = sd.serviceinvoiceid and inv.serinvhcompanyid = sd.companyid
and  inv.serinvhshopid = sd.shopid
where
serinvhcashacc is null and inv.serinvhamount >0 and serinvhCashInv = 0
and serinvhcancelled = 0
union all
select
grncompanyid, grnhshopid, grnhcustomerid, GrnhGoodsreturnnoteDate,
GrnhGoodsreturnnoteNO,GrnReturnAccID,
convert(numeric(18,2),-sum(grndunitprice)) as amount,
convert(numeric(18,2),-sum(grndunitprice)*grnhdepexrate) as damount,
convert(numeric(18,2),-sum(grndunitprice)*grnhexchangerate) as camount,0,0.0,
grnhdepartmentid
from
LosGoodsReturnNoteHeader grh, LosGoodsReturnNotedetail grd
where
grh.grnhshopid = grd.grndshopid and grh.grnhgoodsreturnnoteid=grd.grndreturnnoteid and
GrnhCancel =0
group by
grncompanyid, grnhshopid, grnhcustomerid, GrnhGoodsreturnnoteDate,
GrnhGoodsreturnnoteNO,grnhexchangerate, GrnReturnAccID, grnhdepartmentid,
grnhdepexrate
union all
--Re Exporting
select
rehcompanyid, rehshopid, rehCustomerID, rehExportdate, rehExportNo, rehbankcashaccid,
convert(numeric(18,2),sum( redunitprice) ) as amount,
convert(numeric(18,2),sum( redunitprice)* rehdepexrate) as damount,
convert(numeric(18,2),sum( redunitprice)*rehexchangerate) as camount, 0 rehcashinvoice,
convert(numeric(18,2), rehsettledamount) settledamount, rehdepartmentid departmentid
from
losexportheader ih, losExportDetail invd
where
ih.rehshopid = invd.redshopid and ih.rehExportID = invd.redExportID and
rehcancelled=0 and rehcashinvoice =0 and rehproforma = 0 and ih.rehtype =''i''
group by
rehcompanyid, rehshopid, rehExportDate, rehExportID, rehExportNo , rehCustomerID,
rehbankcashaccid, rehexchangerate, rehdepartmentid, rehsettledamount , rehdepexrate
union all
select poshcompanyid,h.poshShopID,poshcustomerid,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,
poshBillNo,poshSalesAccID,
case when poshBillType=''CR'' then COnvert(numeric(18,2),(poshbillamount))
when poshBillType=''VCR'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt))end Amount,
case when poshBillType=''CR'' then COnvert(numeric(18,2),(poshbillamount)*poshdepexrate)
when poshBillType=''VCR'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt)*poshdepexrate)end Depamount,
case when poshBillType=''CR'' then COnvert(numeric(18,2),(poshbillamount)*poshExchangeRate)
when poshBillType=''VCR'' then COnvert(numeric(18,2),(poshbillamount-poshVoucherAmt)*poshExchangeRate)end Comamount,
0,0,poshDepartmentid
from  losposfandbheader h
where poshCancelled=0 and poshBillType in(''CR'',''VCR'')'
GO
/****** Object:  View [dbo].[vwcreditinvoicesettlecommision]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcreditinvoicesettlecommision]'))
EXEC dbo.sp_executesql @statement = N'
--last modified on : 10/06/2003
--modified by    : leo
--comments     : inclueded max settled date
-----------------------------------------------------------------------
--last modified on : 13/06/2003, 01/08/2003, 05/05/2004
--modified by    : R Harikrishnan, Hariharan
--comments     : Added customer Type and DutyAmt, Added CostPrice
--     : added Cash Sales and included margin pecentage instead of margin amt
-----------------------------------------------------------------------
--Ref.No.1
--modified on:05/07/2011
--Modified by:Aadyakumar.D.V
--Comment    :Added POS transaction
-----------------------------------------------------------------------
--Ref.No.2
--Modified on :29-02-2012
--Modified by :AADYA KUMAR.D.V
--Ticket id   :FGY-413407
--Comment     :Added new column TaxAmount
----------------------------------------------------------------------------------------
CREATE view [dbo].[vwcreditinvoicesettlecommision] as
select
inv.companyid, inv.shopid, inv.departmentid, inv.customerid, inv.invoicedate,
sum(inv.depExRate * isnull(stl.settledamt,0)) settledamount,
max(inv.depExRate * inv.InvAmt) invoiceamount, 0 rebateamount ,
inv.type,inv.SalesPersonID ihSalesPersonID, sm.spername, inv.invoiceid, inv.invoiceno,
cs.customername,inv.InterfaceID, max(stl.settleddate) settleddate,
case when sum(isnull(stl.settledamt,0))=0 then 0 else
datediff(d,inv.invoicedate,max(stl.settleddate)) end SettleDays,
inv.customerType, max(inv.depExRate * inv.DutyAmt) DutyAmt, Max(stl.ReceiptNo) ReceiptNo,
max(inv.depExRate * inv.Costprice) Costprice,Max(sh.SalesCommMarginPer) ShopSCMargin,
convert(numeric(18,2),Max(((inv.depExRate * inv.InvAmt) - (inv.depExRate * inv.Costprice))/(inv.depExRate * inv.InvAmt)) * 100) SalesMarginAmt,
TaxAmount --Ref.No.2
from
vwinvoices inv
left outer join vwsettlements stl
on inv.companyid = stl.companyid and inv.shopid = stl.shopid
and inv.invoiceid = stl.invoiceid and inv.type = stl.type ,
asalespersonmaster sm, acustomermaster cs,aShops sh
where
inv.salespersonid = sm.sperid and cs.customerid = inv.customerid and
inv.ShopID=sh.ShopID and inv.InvAmt <> 0
group by
inv.companyid, inv.shopid, inv.departmentid, inv.customerid, inv.invoiceid,
inv.invoiceno, cs.customername, inv.type, inv.invoicedate, inv.salespersonid,
sm.spername,inv.InterfaceID,inv.customerType,
TaxAmount  --Ref.No.2
--  FOR INCLUDING CASH INVOICES FOR SALES COMMISSION
UNION ALL
Select
inv.companyid, inv.shopid, inv.departmentid, inv.customerid, inv.invoicedate,
max(inv.depExRate * inv.InvAmt) settledamount,
max(inv.depExRate * inv.InvAmt) invoiceamount, 0 rebateamount ,
inv.type,inv.SalesPersonID ihSalesPersonID, sm.spername, inv.invoiceid, inv.invoiceno,
cs.customername,inv.InterfaceID, inv.invoicedate settleddate,
0 SettleDays, inv.customerType, 0 DutyAmt,
'''' ReceiptNo, max(inv.depExRate * inv.Costprice) Costprice,
Max(sh.SalesCommMarginPer) ShopSCMargin,
convert(numeric(18,2),Max(((inv.depExRate * inv.InvAmt)
- (inv.depExRate * inv.Costprice))/(inv.depExRate * inv.InvAmt)) * 100) SalesMarginAmt,
TaxAmount --Ref.No.2
from
vwCashinvoices inv,
asalespersonmaster sm, acustomermaster cs,aShops sh
where
inv.salespersonid = sm.sperid and cs.customerid = inv.customerid and
inv.ShopID=sh.ShopID and inv.SalesPersonId is not null
and inv.InvAmt <> 0
group by
inv.companyid, inv.shopid, inv.departmentid, inv.customerid, inv.invoiceid,
inv.invoiceno, cs.customername, inv.type, inv.invoicedate, inv.salespersonid,
sm.spername,inv.InterfaceID,inv.customerType,
TaxAmount  --Ref.No.2
--Ref.No.1---start----
UNION ALL
select inv.poshCompanyID,inv.poshShopID,inv.poshDepartmentid,
inv.poshcustomerid,inv.poshBillDate invoicedate,inv.poshdepexrate*inv.poshBillAmount settledamount,
inv.poshdepexrate*inv.poshBillAmount invoiceamount,0 rebateamount ,''POS'' type,
inv.poshsalespersonid ihSalesPersonID,sm.spername,inv.poshBillID,inv.poshBillNo,
case when cs.customername is null then ''Cash Customer in POS'' else cs.customername end,1502 InterfaceID,inv.poshBillDate settleddate,
0 SettleDays,'''' customerType, 0 DutyAmt,'''' ReceiptNo,
max(inv.poshdepexrate * ind.posdcostprice) Costprice,
Max(sh.SalesCommMarginPer) ShopSCMargin,
convert(numeric(18,2),Max(((inv.poshdepexrate * inv.poshBillAmount) - (inv.poshdepexrate * ind.posdcostprice))
/(inv.poshdepexrate *  case when (inv.poshBillAmount)=0 then 1 else inv.poshBillAmount end ) * 100)) SalesMarginAmt,
sum(ISNULL(posdItemTaxAmount,0)) TaxAmount --Ref.No.2
from
LOsPosHeader inv
inner join LOsPosdetail ind on
inv.poshBillID=ind.posdBillID and ind.posdShopID=inv.poshShopID  and poshCancelled=0
inner join aShops sh on inv.poshShopID=sh.ShopID and sh.DepartmentID=poshDepartmentid
left outer join acustomermaster cs on inv.poshcustomerid=cs.CustomerID
left outer join asalespersonmaster sm on sm.Sperid=inv.poshsalespersonid
group by poshCompanyID,inv.poshShopID,poshDepartmentid,poshcustomerid,poshBillID,poshBillNo,CustomerName,
poshBillDate,poshsalespersonid,Spername,inv.poshBillID,customerType,poshdepexrate,poshBillAmount
--Ref.No.1---end----'
GO
/****** Object:  View [dbo].[vwnetcashinflow]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnetcashinflow]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwnetcashinflow    Script Date: 18/01/2003 9:45:41 PM ******/
/****** Object:  View dbo.vwnetcashinflow    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwnetcashinflow    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwnetcashinflow    Script Date: 20/11/2001 9:59:08 AM ******/
/****** Object:  View dbo.vwnetcashinflow    Script Date: 17/11/2001 9:22:03 PM ******/
/****** Object:  View dbo.vwnetcashinflow    Script Date: 16/06/2001 15:36:34 ******/
CREATE view [dbo].[vwnetcashinflow] as
select netcash.companyid, netcash.shopid, netcash.billdate, sum(netcash.cashsales)cashsales,
sum(netcash.receipts) receipts, sum(netcash.payments) payments from
--cashsales
(select companyid, shopid, billdate , sum(actamount) cashsales, 0 as receipts, 0 as payments
from vwcashsalestruncated where cash=1 group by shopid, billdate, companyid
union all
--dummy receipts
select drcompanyid, drshopid, drdate, 0 as cashsales, sum(dramount) as receipts, 0 as payments
from losdummyreceiptheader where drcancelled=0 group by drcompanyid, drshopid, drdate
union all
--petty payments
select phcompanyid, phshopid, phpaymentdate, 0 as cashsales, 0 as receipts,
sum(phamount) payments from lospaymentvoucherheader where phcancelled=0 group by
phcompanyid, phshopid, phpaymentdate)
netcash group by netcash.companyid, netcash.shopid, netcash.billdate'
GO
/****** Object:  View [dbo].[vwshipmentwisestock]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshipmentwisestock]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwshipmentwisestock    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on 	: 09/12/2002
--Modified by		: leo
--Comments		: v3
CREATE VIEW [dbo].[vwshipmentwisestock] as
select locationid, itemid, shipmentid, stock, openingstock, badstock, openingbadstock ,
shipcost, itemcategoryid from
(select gsgodownid locationid, gs.gsitemid itemid, gs.gsshipmentid shipmentid, gs.gsstock stock,
gs.gsopeningstock openingstock, gs.gsbadstock badstock, gs.gsopeningbadstock openingbadstock ,
gs.shipcost, ''g'' as location, itemcategoryid  from vwshipmentwisegodownstock gs
union all
select shopid locationid, itemid, shipmentid, stock, openingstock, badstock, openingbadstock ,
shipcost, ''s'' as location , itemcategoryid from vwshipmentwiseshopstock ) shipwisestock
where stock <> 0 or badstock <> 0'
GO
/****** Object:  View [dbo].[vwsalesyearmonthdaywise]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwsalesyearmonthdaywise]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwsalesyearmonthdaywise    Script Date: 18/01/2003 9:45:41 PM ******/
/****** Object:  View dbo.vwsalesyearmonthdaywise    Script Date: 14/09/2002 12:48:11 AM ******/
/****** Object:  View dbo.vwsalesyearmonthdaywise    Script Date: 31/07/2002 2:00:32 PM ******/
/****** Object:  View dbo.vwsalesyearmonthdaywise    Script Date: 20/11/2001 9:59:09 AM ******/
/****** Object:  View dbo.vwsalesyearmonthdaywise    Script Date: 17/11/2001 9:22:04 PM ******/
CREATE view [dbo].[vwsalesyearmonthdaywise] as
select companyid, shopid, year(billdate) as tyear, month(billdate) as tmonth,
datepart(wk,billdate) tweek,  billdate, accountid, actamount,actamount famount, cash, transtype
from vwcashsalestruncated'
GO
/****** Object:  View [dbo].[vwSalesAnalysisByYear]    Script Date: 10/06/2012 14:17:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSalesAnalysisByYear]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwSalesAnalysisByYear    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on 	: 13/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwSalesAnalysisByYear]  as
select companyid,departmentid, shopid, year(billdate) as tyear,year(billdate) - 1 as
YearPrevious,  billdate, accountid, actamount, actamount famount, damount, camount,
cash, transtype from vwcashsalestruncated'
GO
/****** Object:  View [dbo].[vwPORequestFlow]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPORequestFlow]'))
EXEC dbo.sp_executesql @statement = N'
Create View [dbo].[vwPORequestFlow] As
select grhRequestID,grhShopId,ShopName,grhRequestNo,grhRequestDate,grhRemarks,B.* from mosGoodsRequestHeader
Left Outer Join aShops On ShopID=grhShopId
Right Outer Join vwPOBillCostingDespatchArrival b
ON grhRequestID=RequestIDPO And grhShopId=ShopIdPO
Where GRHCancel=0 And grhRequestType=''P''
Union All
select grhRequestID,grhShopId,ShopName,grhRequestNo,grhRequestDate,grhRemarks,B.* from mosGoodsRequestHeader
Left Outer Join aShops On ShopID=grhShopId
Right Outer Join vwPOBillCostingDespatchArrival b
ON grhRequestID=RequestIDQut And grhShopId=ShopIdQut
Where GRHCancel=0 And grhRequestType=''P''
Union All
select grhRequestID,grhShopId,ShopName,grhRequestNo,grhRequestDate,grhRemarks,B.* from mosGoodsRequestHeader
Left Outer Join aShops On ShopID=grhShopId
Right Outer Join vwPOBillCostingDespatchArrival b
ON grhRequestID=RequestIDReq And grhShopId=ShopIdReq
Where GRHCancel=0 And grhRequestType=''P'''
GO
/****** Object:  View [dbo].[vwDebtorAge]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwDebtorAge]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on		: 22/12/2002
--Modified by	 	: Hariharan R
--Comments		: v3
--Added the rexport related objects for customer rexpoert invoices - 22/12/2002
------------------------------------------------------------------------------------
--Modified on 		: 07/08/2003
--Modified by		: R Harikrishnan
--Comments		: Other charges changes
--Modified on 		: 18/12/2003
--Modified by		: venki
--Comments		: added special invoice transfinished chking
--			: Other charges given in group by clause to avoid doubling in Invoice queries
------------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwDebtorAge] as
--1. HQ  SERVICE INVOICE
SELECT
	AIH.CompanyID, null shopid, AIH.DepartmentID, AIH.InvoiceID,
	AIH.customerid, AIH.invoicedate,case when isnull(max(air.settledamt),0) > 0 then max(air.ReceiptDate)
	when isnull(max(RSD.AmtSettled),0) > 0 then max(rsd.CSDATE) else null end settleddate,
	AIH.invoiceno, aih.remarks,isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,
	isnull(max(AIR.settledamt),0)+ isnull(max(RSD.AmtSettled),0) as AmtReceived,
	''0 - 30'' as Due  , ''AI'' AS Type ,aih.updatetime
FROM
	AccountsInvoiceHeader AIH
	Left outer join ServiceInvoiceDetails SID
	on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID
	Left outer join vwhqinvoicereceipt AIR
	on AIH.CompanyID = AIR.CompanyID and AIH.InvoiceID = AIR.HQaccountsinvoiceid
	left outer join vwRecSettlementDetails RSD
	on AIH.CompanyID=RSD.CompanyID and AIH.InvoiceID =RSD.InvoiceID
WHERE
	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.DepartmentID, AIH.InvoiceID , SID.InvoiceID, AIH.customerid,
	AIH.invoicedate, aih.updatetime, AIH.invoiceno, aih.remarks,AIH.Discount
UNION ALL
SELECT
	AIH.CompanyID, null shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,
	AIH.invoicedate,case when isnull(max(air.settledamt),0) > 0 then max(air.ReceiptDate)
	when isnull(max(RSD.AmtSettled),0) > 0 then max(rsd.CSDATE) else null end settleddate,
	AIH.invoiceno, aih.remarks,
	isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,
	isnull(max(AIR.settledamt),0)+ isnull(max(RSD.AmtSettled),0) as AmtReceived,
	''31 - 60'' as Due  , ''AI'' AS Type ,aih.updatetime
FROM
	AccountsInvoiceHeader AIH
	Left outer join ServiceInvoiceDetails SID
	on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID
	Left outer join vwhqinvoicereceipt AIR
	on AIH.CompanyID = AIR.CompanyID and AIH.InvoiceID = AIR.HQaccountsinvoiceid
	left outer join vwRecSettlementDetails RSD
	on AIH.CompanyID=RSD.CompanyID and AIH.InvoiceID =RSD.InvoiceID
WHERE
	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.DepartmentID, AIH.InvoiceID , SID.InvoiceID, AIH.customerid,
	AIH.invoicedate, aih.updatetime, AIH.invoiceno, aih.remarks,AIH.Discount
union all
SELECT
	AIH.CompanyID, null shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,
	AIH.invoicedate,case when isnull(max(air.settledamt),0) > 0 then max(air.ReceiptDate)
	when isnull(max(RSD.AmtSettled),0) > 0 then max(rsd.CSDATE) else null end settleddate,
	AIH.invoiceno, aih.remarks,
	isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,
	isnull(max(AIR.settledamt),0)+ isnull(max(RSD.AmtSettled),0) as AmtReceived,
	''61 - 90'' as Due  , ''AI'' AS Type , aih.updatetime
FROM
	AccountsInvoiceHeader AIH
	Left outer join ServiceInvoiceDetails SID
	on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID
	Left outer join vwhqinvoicereceipt AIR
	on AIH.CompanyID = AIR.CompanyID and AIH.InvoiceID = AIR.HQaccountsinvoiceid
	left outer join vwRecSettlementDetails RSD
	on AIH.CompanyID=RSD.CompanyID and AIH.InvoiceID =RSD.InvoiceID
WHERE
	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.DepartmentID, AIH.InvoiceID , SID.InvoiceID, AIH.customerid,
	AIH.invoicedate, aih.updatetime, AIH.invoiceno, aih.remarks, AIH.Discount
union all
SELECT
	AIH.CompanyID, null shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,
	AIH.invoicedate,case when isnull(max(air.settledamt),0) > 0 then max(air.ReceiptDate)
	when isnull(max(RSD.AmtSettled),0) > 0 then max(rsd.CSDATE) else null end settleddate,
	AIH.invoiceno, aih.remarks,
	isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,
	isnull(max(AIR.settledamt),0)+ isnull(max(RSD.AmtSettled),0) as AmtReceived,
	'' > 90''  as Due  , ''AI'' AS Type , aih.updatetime
FROM
	AccountsInvoiceHeader AIH
	Left outer join ServiceInvoiceDetails SID
	on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID
	Left outer join vwhqinvoicereceipt AIR
	on AIH.CompanyID = AIR.CompanyID and AIH.InvoiceID = AIR.HQaccountsinvoiceid
	left outer join vwRecSettlementDetails RSD
	on AIH.CompanyID=RSD.CompanyID and AIH.InvoiceID =RSD.InvoiceID
WHERE
	AIH.CashInvoice = 0 and AIH.Proforma = 0 and AIH.Cancelled = 0 and
	(datediff(dd,aIH.InvoiceDate,getdate())   > 90)
GROUP BY
	AIH.CompanyID, AIH.DepartmentID, AIH.InvoiceID , SID.InvoiceID, AIH.customerid,
	AIH.invoicedate, aih.updatetime, AIH.invoiceno, aih.remarks,AIH.Discount
union all
--2. SHOP SERVICE INVOICE
SELECT
	AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,
	AIH.aiinvoicedate, case when max(isnull(AIR.settledamt,0))> 0 then max(air.receiptdate)
	when max(isnull(SD.AmtSettled,0)) > 0 then max(sd.csdate) else null end settleddate,
	AIH.aiinvoiceno, aih.airemarks, sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) as InvAmt,
	max(isnull(AIR.settledamt,0))+ max(isnull(SD.AmtSettled,0)) as AmtReceived,
	''0 - 30'' as Due  , ''PSI'' as type, aih.updatetime
FROM
	losAccountsInvoiceHeader AIH
	Left outer join losServiceInvoiceDetails SID
	on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid
	Left outer join vwshopsaleinvoicereceipt AIR
	on AIH.aiCompanyID = AIR.CompanyID and AIH.aiInvoiceID = AIR.posaccountsinvoiceid and AIH.aishopid=AIR.shopid
	left outer join vwshopsersettlementdetails SD
	on AIH.aiCompanyID=SD.CompanyID and AIH.aiInvoiceID = SD.InvoiceID and aih.aishopid=sd.shopid
WHERE
	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.aiDepartmentID, AIH.aiInvoiceID ,
	SID.siInvoiceID, AIH.aicustomerid, AIH.aiinvoicedate, aih.updatetime,
	AIH.aiinvoiceno, aih.airemarks, AIH.aiDiscount
union all
SELECT
	AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,
	AIH.aiinvoicedate, case when max(isnull(AIR.settledamt,0))> 0 then max(air.receiptdate)
	when max(isnull(SD.AmtSettled,0)) > 0 then max(sd.csdate) else null end settleddate,
	AIH.aiinvoiceno, aih.airemarks, sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) as InvAmt,
	max(isnull(AIR.settledamt,0))+ max(isnull(SD.AmtSettled,0)) as AmtReceived,
	''31 - 60'' as Due  , ''PSI'' as type, aih.updatetime
FROM
	losAccountsInvoiceHeader AIH
	Left outer join losServiceInvoiceDetails SID
	on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid
	Left outer join vwshopsaleinvoicereceipt AIR
	on AIH.aiCompanyID = AIR.CompanyID and AIH.aiInvoiceID = AIR.posaccountsinvoiceid and AIH.aishopid=AIR.shopid
	left outer join vwshopsersettlementdetails SD
	on AIH.aiCompanyID=SD.CompanyID and AIH.aiInvoiceID = SD.InvoiceID and aih.aishopid=sd.shopid
WHERE
	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.aiDepartmentID, AIH.aiInvoiceID ,
	SID.siInvoiceID, AIH.aicustomerid, AIH.aiinvoicedate, aih.updatetime,
	AIH.aiinvoiceno, aih.airemarks, AIH.aiDiscount
union all
SELECT
	AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,
	AIH.aiinvoicedate, case when max(isnull(AIR.settledamt,0))> 0 then max(air.receiptdate)
	when max(isnull(SD.AmtSettled,0)) > 0 then max(sd.csdate) else null end settleddate,
	AIH.aiinvoiceno, aih.airemarks, sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) as InvAmt,
	max(isnull(AIR.settledamt,0))+ max(isnull(SD.AmtSettled,0)) as AmtReceived,
	''61 - 90''  as Due  , ''PSI'' as type, aih.updatetime
FROM
	losAccountsInvoiceHeader AIH
	Left outer join losServiceInvoiceDetails SID
	on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid
	Left outer join vwshopsaleinvoicereceipt AIR
	on AIH.aiCompanyID = AIR.CompanyID and AIH.aiInvoiceID = AIR.posaccountsinvoiceid and AIH.aishopid=AIR.shopid
	left outer join vwshopsersettlementdetails SD
	on AIH.aiCompanyID=SD.CompanyID and AIH.aiInvoiceID = SD.InvoiceID and aih.aishopid=sd.shopid
WHERE
	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.aiDepartmentID, AIH.aiInvoiceID ,
	SID.siInvoiceID, AIH.aicustomerid, AIH.aiinvoicedate, aih.updatetime,
	AIH.aiinvoiceno, aih.airemarks, AIH.aiDiscount
union all
SELECT
	AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,
	AIH.aiinvoicedate, case when max(isnull(AIR.settledamt,0))> 0 then max(air.receiptdate)
	when max(isnull(SD.AmtSettled,0)) > 0 then max(sd.csdate) else null end settleddate,
	AIH.aiinvoiceno, aih.airemarks, sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) as InvAmt,
	max(isnull(AIR.settledamt,0))+ max(isnull(SD.AmtSettled,0)) as AmtReceived,
	'' > 90'' as Due  , ''PSI'' as type, aih.updatetime
FROM
	losAccountsInvoiceHeader AIH
	Left outer join losServiceInvoiceDetails SID 	
	on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid
	Left outer join vwshopsaleinvoicereceipt AIR
	on AIH.aiCompanyID = AIR.CompanyID and AIH.aiInvoiceID = AIR.posaccountsinvoiceid and AIH.aishopid=AIR.shopid
	left outer join vwshopsersettlementdetails SD
	on AIH.aiCompanyID=SD.CompanyID and AIH.aiInvoiceID = SD.InvoiceID and aih.aishopid=sd.shopid
WHERE
	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.aiDepartmentID, AIH.aiInvoiceID ,
	SID.siInvoiceID, AIH.aicustomerid, AIH.aiinvoicedate, aih.updatetime,
	AIH.aiinvoiceno, aih.airemarks, AIH.aiDiscount
union all
--3. SHOP CREDIT INVOICE
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks,(sum(isnull(SID.idunitprice,0)) + isnull(ocd.ioAmount,0)) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''0 - 30'' as Due  , ''PCI'' as type, ih.updatetime
FROM
	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
	Left outer join vwshopcreditinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopinvsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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.ihDepartmentID, IH.ihInvoiceID , sID.idInvoiceID,
	IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno,
	ih.ihremarks, IH.ihDiscount, ocd.ioAmount
UNION ALL
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks,(sum(isnull(SID.idunitprice,0))+ isnull(ocd.ioAmount,0)) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''31 - 60'' as Due  , ''PCI'' as type, ih.updatetime
FROM
	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
	Left outer join vwshopcreditinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopinvsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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.ihDepartmentID, IH.ihInvoiceID ,
	sID.idInvoiceID, IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno,
	ih.ihremarks, IH.ihDiscount, ocd.ioAmount
UNION ALL
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks,(sum(isnull(SID.idunitprice,0)) + isnull(ocd.ioAmount,0)) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''61 - 90'' as Due  , ''PCI'' as type, ih.updatetime
FROM
	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
	Left outer join vwshopcreditinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopinvsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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.ihDepartmentID, IH.ihInvoiceID ,
	sID.idInvoiceID, IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno,
	ih.ihremarks, IH.ihDiscount, ocd.ioAmount
UNION ALL	--leo
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks,(sum(isnull(SID.idunitprice,0)) + isnull(ocd.ioAmount,0)) as InvAmt,
	isnull(max(IR.settledamt),0) + isnull(max(SD.AmtSettled),0) as AmtReceived,
	'' > 90'' as Due  , ''PCI'' as type, ih.updatetime
FROM
	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
	Left outer join vwshopcreditinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and  IH.ihInvoiceID = IR.posinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopinvsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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.ihDepartmentID, IH.ihInvoiceID ,
	sID.idInvoiceID, IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno,
	ih.ihremarks, IH.ihDiscount, ocd.ioAmount
union all
--4. SHOP SPECIAL INVOICE
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0)> 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks, isnull(sum(case when idratetype =1
	then -idunitprice else idunitprice end),0) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''0 - 30'' as Due  , ''PDI'' as type, ih.updatetime
FROM
	losSpecialInvoiceHeader IH
	Left outer join losSpecialInvoiceDetail SID
	on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype =0
	Left outer join vwspecialinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posspinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopsplsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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, SD.InvoiceID, IR.posspinvoiceid,
	IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, ir.receiptdate, iH.ihinvoiceno,
	ih.ihremarks,IH.ihDepartmentID, IH.ihDiscount
union all
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0)> 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks, isnull(sum(case when idratetype =1
	then -idunitprice else idunitprice end),0) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''31 - 60'' as Due  , ''PDI'' as type, ih.updatetime
FROM
	losSpecialInvoiceHeader IH
	Left outer join losSpecialInvoiceDetail SID
	on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype = 0
	Left outer join vwspecialinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posspinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopsplsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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, SD.InvoiceID, IR.posspinvoiceid,
	IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, ir.receiptdate, iH.ihinvoiceno,
	ih.ihremarks,IH.ihDepartmentID, IH.ihDiscount
union all
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0)> 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks, isnull(sum(case when idratetype =1
	then -idunitprice else idunitprice end),0) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	''61 - 90'' as Due  , ''PDI'' as type, ih.updatetime
FROM
	losSpecialInvoiceHeader IH
	Left outer join losSpecialInvoiceDetail SID
	on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype = 0
	Left outer join vwspecialinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posspinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopsplsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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, SD.InvoiceID, IR.posspinvoiceid,
	IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, ir.receiptdate, iH.ihinvoiceno,
	ih.ihremarks,IH.ihDepartmentID, IH.ihDiscount
union all
SELECT
	IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,
	IH.ihinvoicedate, case when isnull(max(IR.settledamt),0)> 0 then max(ir.receiptdate)
	when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	iH.ihinvoiceno, ih.ihremarks, isnull(sum(case when idratetype =1
	then -idunitprice else idunitprice end),0) as InvAmt,
	isnull(max(IR.settledamt),0)+ isnull(max(SD.AmtSettled),0) as AmtReceived,
	'' > 90''  as Due  , ''PDI'' as type, ih.updatetime
FROM
	losSpecialInvoiceHeader IH
	Left outer join losSpecialInvoiceDetail SID
	on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype = 0
	Left outer join vwspecialinvoicereceipt IR
	on IH.ihCompanyID = IR.CompanyID and IH.ihInvoiceID = IR.posspinvoiceid and IH.ihshopid=IR.shopid
	left outer join vwshopsplsettlementdetails SD
	on IH.ihCompanyID=SD.CompanyID and IH.ihInvoiceID =SD.InvoiceID and ih.ihshopid=sd.shopid
WHERE
	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, SD.InvoiceID, IR.posspinvoiceid,
	IH.ihcustomerid, IH.ihinvoicedate, ih.updatetime, ir.receiptdate, iH.ihinvoiceno,
	ih.ihremarks, IH.ihDepartmentID, IH.ihDiscount
union all
--5. debit note from hq
SELECT
	dcn.DCNCompanyid, null shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,
	dcn.DCNDate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	dcn.DCNNo, dcn.DCNDetails, DCNAmount as InvAmt, isnull(max(sd.amtsettled),0) as AmtReceived,
	''0 - 30''  as Due, ''HDN'' as type, dcn.updatetime
FROM
	debitcreditnote dcn
	left outer join vwHQDNSettlementDetails SD
	on dcn.dcnCompanyID=SD.CompanyID and dcn.dcniD =SD.dcnID
WHERE
	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.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount
union all
SELECT
	dcn.DCNCompanyid, null shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,
	dcn.DCNDate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	dcn.DCNNo, dcn.DCNDetails, DCNAmount as InvAmt, isnull(sum(sd.amtsettled),0) as AmtReceived,
	''31 - 60''  as Due, ''HDN'' as type, dcn.updatetime
FROM
	debitcreditnote dcn
	left outer join vwHQDNSettlementDetails SD
	on dcn.dcnCompanyID=SD.CompanyID and dcn.dcniD =SD.dcnID
WHERE
	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.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount
union all
SELECT 	
	dcn.DCNCompanyid, null shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,
	dcn.DCNDate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	dcn.DCNNo, dcn.DCNDetails, DCNAmount as InvAmt, isnull(max(sd.amtsettled),0) as AmtReceived,
	''61 - 90''  as Due, ''HDN'' as type, dcn.updatetime
FROM
	debitcreditnote dcn
	left outer join vwHQDNSettlementDetails SD
	on dcn.dcnCompanyID=SD.CompanyID and dcn.dcniD =SD.dcnID
WHERE
	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.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount
union all
SELECT
	dcn.DCNCompanyid, null shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,
	dcn.DCNDate, case when isnull(max(SD.AmtSettled),0) > 0 then max(sd.csdate) else null end settleddate,
	dcn.DCNNo, dcn.DCNDetails, DCNAmount as InvAmt, isnull(max(sd.amtsettled),0) as AmtReceived,
	'' > 90''  as Due, ''HDN'' as type, dcn.updatetime
FROM
	debitcreditnote dcn
	left outer join vwHQDNSettlementDetails SD
	on dcn.dcnCompanyID=SD.CompanyID and dcn.dcniD =SD.dcnID
WHERE
	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.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount
union all
-- payment to customer considered as invoice
select
	ph.phcompanyid, null shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,
	ph.phpaymentdate, null settleddate, ph.phpaymentno, ph.phremarks,
	ph.phcustomeramount, 0.0 settledamt , ''0 - 30'' due,  ''rf'' type, ph.updatetime
from
	ahqpaymentvoucherheader ph
where
	ph.phcancelled =0 and phcustomerid is not null and
	(getdate() - ph.phpaymentdate between 0 and 30)
union all
select
	ph.phcompanyid, null shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,
	ph.phpaymentdate, null settleddate, ph.phpaymentno, ph.phremarks,
	ph.phcustomeramount, 0.0 settledamt , ''31 - 60'' due,  ''rf'' type, ph.updatetime
from
	ahqpaymentvoucherheader ph
where
	ph.phcancelled =0 and phcustomerid is not null and
	(getdate() - ph.phpaymentdate between 31 and 60)
union all
select
	ph.phcompanyid, null shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,
	ph.phpaymentdate, null settleddate, ph.phpaymentno, ph.phremarks,
	ph.phcustomeramount, 0.0 settledamt ,''61 - 90'' due,  ''rf'' type, ph.updatetime
from
	ahqpaymentvoucherheader ph
where
	ph.phcancelled =0 and phcustomerid is not null and
	(getdate() - ph.phpaymentdate between 61 and 90)
union all
select
	ph.phcompanyid, null shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,
	ph.phpaymentdate, null settleddate, ph.phpaymentno, ph.phremarks,
	ph.phcustomeramount, 0.0 settledamt , '' > 90'' due,  ''rf'' type, ph.updatetime
from 	
	ahqpaymentvoucherheader ph
where
	ph.phcancelled =0 and phcustomerid is not null and
	(getdate() - ph.phpaymentdate > 90)
union all
-- just to make a record available always
SELECT
	1, null shopid, null, null, customerid, null, null settleddate, null, null, 0 InvAmt,
	0.0 AmtReceived, '' > 90''  as Due, ''dum'' as type, null
from
	acustomermaster
-- FOR RE EXPORT TRANSACTION INCLUSION FOR DEBTOR AGE ANALYSIS OF CUSTOMER
--22/12/2002
union all
SELECT
	IH.REHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,
	IH.rehExportDate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	 else null end settleddate,
	iH.rehExportNO, ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt,
	isnull(max(IR.settledamt),0) as AmtReceived,
	''0 - 30'' Due  ,
	''RE'' as type, ih.rehupdatetime
FROM
	losExportHeader IH
	Left outer join losExportDetail SID
	on IH.rehExportID = SID.redExportId and ih.rehshopid=sid.redshopid
	Left outer join vwreexportsettlements IR
	on IH.rehCompanyID = IR.CompanyID and IH.rehExportID = IR.invoiceid and IH.rehshopid=IR.shopid
WHERE
	IH.rehCashInvoice = 0 and IH.rehProforma = 0 and IH.rehCancelled = 0 and
	ih.rehtype =''i'' and (datediff(dd,IH.rehexportDate,getdate())  between 0 and 30) and
	rehcustomerid is not null
GROUP BY
	IH.rehCompanyID, IH.rehSHOPID, IH.rehDepartmentID, IH.rehExportID ,
	IH.rehcustomerid, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,
	ih.rehremarks, IH.rehDiscount
union all
SELECT
	IH.REHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,
	IH.rehExportDate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	else null end settleddate,
	iH.rehExportNO, ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt,
	isnull(max(IR.settledamt),0) as AmtReceived,
	''31 - 60'' Due  ,
	''RE'' as type, ih.rehupdatetime
FROM
	losExportHeader IH
	Left outer join losExportDetail SID
	on IH.rehExportID = SID.redExportId and ih.rehshopid=sid.redshopid
	Left outer join vwreexportsettlements IR
	on IH.rehCompanyID = IR.CompanyID and IH.rehExportID = IR.invoiceid and IH.rehshopid=IR.shopid
WHERE
	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.rehDepartmentID, IH.rehExportID ,
	IH.rehcustomerid, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,
	ih.rehremarks, IH.rehDiscount
union all
SELECT
	IH.REHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,
	IH.rehExportDate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	 else null end settleddate,
	iH.rehExportNO, ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt,
	isnull(max(IR.settledamt),0) as AmtReceived,
	''61 - 90'' Due  , ''RE'' as type, ih.rehupdatetime
FROM
	losExportHeader IH
	Left outer join losExportDetail SID
	on IH.rehExportID = SID.redExportId and ih.rehshopid=sid.redshopid
	Left outer join vwreexportsettlements IR
	on IH.rehCompanyID = IR.CompanyID and IH.rehExportID = IR.invoiceid and IH.rehshopid=IR.shopid
WHERE
	IH.rehCashInvoice = 0 and IH.rehProforma = 0 and IH.rehCancelled = 0 and
	ih.rehtype =''i'' and (datediff(dd,IH.rehexportDate,getdate())  between 61 and 90) and
	rehcustomerid is not null
GROUP BY
	IH.rehCompanyID, IH.rehSHOPID, IH.rehDepartmentID, IH.rehExportID ,
	IH.rehcustomerid, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,
	ih.rehremarks, IH.rehDiscount
union all
SELECT
	IH.REHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,
	IH.rehExportDate, case when isnull(max(IR.settledamt),0) > 0 then max(ir.receiptdate)
	 else null end settleddate, iH.rehExportNO, ih.rehremarks,
	isnull(sum(redunitprice),0) as InvAmt, isnull(max(IR.settledamt),0) as AmtReceived,
	''> 90'' Due  , ''RE'' as type, ih.rehupdatetime
FROM
	losExportHeader IH
	Left outer join losExportDetail SID
	on IH.rehExportID = SID.redExportId and ih.rehshopid=sid.redshopid
	Left outer join vwreexportsettlements IR
	on IH.rehCompanyID = IR.CompanyID and IH.rehExportID = IR.invoiceid and IH.rehshopid=IR.shopid
WHERE
	IH.rehCashInvoice = 0 and IH.rehProforma = 0 and IH.rehCancelled = 0 and
	ih.rehtype =''i'' and (datediff(dd,IH.rehexportDate,getdate())  >90) and
	rehcustomerid is not null
GROUP BY
	IH.rehCompanyID, IH.rehSHOPID, IH.rehDepartmentID, IH.rehExportID ,
	IH.rehcustomerid, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,
	ih.rehremarks, IH.rehDiscount'
GO
/****** Object:  View [dbo].[vwbookservinvoicesettle]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbookservinvoicesettle]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwbookservinvoicesettle]  as
select  h.companyid, serinvhdepartmentid departmentid, h. shopid, h.refno,
invoiceid,  invoiceno, invoicedate, serinvhduedate ,
h.customerid, serinvhamount ,sum(isnull(vwrec.settledamt,0)) settled, type
from vwbookingservinvoices h left outer join
vwbookservicesettlements vwrec on h.companyid = vwrec.companyid and
h.shopid = vwrec.shopid and h.invoiceid =  vwrec.serviceinvoiceid
group by h.companyid, h.shopid, h.serinvhdepartmentid, h.invoiceid, h.invoiceno,
h.invoicedate,h.serinvhduedate, h.customerid, h.serinvhamount, type,h.refno'
GO
/****** Object:  View [dbo].[vwbillspaymentformis]    Script Date: 10/06/2012 14:17:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwbillspaymentformis]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwbillspaymentformis    Script Date: 18/01/2003 9:45:40 PM ******/
--Last Modified on 	: 26/10/2002
--Modified by 		: leo
--created as second batch 0n 09/11/2002 by hariharan from fi-es10
--modified by  : hariharan
--modified date: 18/09/2002
CREATE view [dbo].[vwbillspaymentformis] as
-- with payable to suppliers and advance receipts done to customers
select max(a.pbhbillamount) billamount,
sum(a.paidamount) paidamount ,  max(a.pbhbillamount) - sum(isnull(a.paidamount,0)) balance, a.pbhvendorid ,
a.shopid,max(a.departmentid) departmentid,a.billsid,a.type,a.billsno,a.pbhbilldate,
a.pbhremarks,a.referenceno,a.currencyname, max(a.currencyid) currencyid, dp.departmentname, a.vendorname,a.symbol,
"Payables To Vendor" paytype from (SELECT vwbills.companyid, vwbills.shopid, vwbills.departmentid, vwbills.billsid,
vwbills.pbhVendorID, vwbills.billsno, vwbills.pbhremarks, vwbills.referenceno,
vwbills.pbhbilldate, vwbills.duedate, vwbills.pbhBillAmount, vwbills.Due,
vwbills.type, vwbills.updatetime,
isnull(vwpayments.PaidAmount,0) paidamount,
aVendorMaster.VendorName,
aCurrencyMaster.CurrencyName, aCurrencyMaster.Symbol, aVendorMaster.currencyid currencyid
FROM { oj ((Adminv2.dbo.vwbills vwbills INNER JOIN Adminv2.dbo.aVendorMaster
aVendorMaster ON vwbills.pbhVendorID = aVendorMaster.VendorID)
LEFT OUTER JOIN Adminv2.dbo.vwpayments vwpayments ON
vwbills.companyid = vwpayments.companyid AND
vwbills.billsid = vwpayments.billsid AND
vwbills.pbhVendorID = vwpayments.vendorid AND
vwbills.shopid = vwpayments.shopid and
vwbills.type = vwpayments.type)
INNER JOIN Adminv2.dbo.aCurrencyMaster aCurrencyMaster ON
aVendorMaster.CurrencyID = aCurrencyMaster.CurrencyID AND
aVendorMaster.CompanyID = aCurrencyMaster.CompanyID})  a, adepartmentmaster dp
where a.departmentid=dp.departmentid
group by a.pbhvendorid , a.shopid,a.departmentid, dp.departmentname, a.billsid,a.type,
a.due,a.billsno,a.pbhbilldate, a.pbhremarks,a.referenceno,a.currencyname,a.vendorname, a.symbol
having max(a.pbhbillamount) - sum(isnull(a.paidamount,0))>0
union all
select r.rptamt, r.settledamt, r.rptamt - r.settledamt balance,
r.customerid, 0 shopid, h.departmentid, r.receiptid ,''cusrcpt'', h.receiptno, h.receiptdate,
h.remarks, h.ReferenceNo, c.currencyname, c.currencyid, dp.departmentname, customername, c.symbol,
"Payables to Debtors" paytype from  vwadvancepaidreceiptsamounts r, receiptvoucherheader h,
acurrencymaster c, acustomermaster cm, adepartmentmaster dp where r.receiptid = h.receiptid and
r.companyid = h.companyid and h.customerid = cm.customerid and h.departmentid = dp.departmentid
and  r.rptamt - r.settledamt>0 and c.currencyid = cm.currencyid'
GO
/****** Object:  View [dbo].[vwtotalbillpaidamount]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalbillpaidamount]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/****** Object:  View dbo.vwtotalbillpaidamount    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on	: 25/07/02
--Modified by		: leo
--Last Modified on	: 27/08/03
--Modified by		: venki
--comment 		: given chk on debit credit
CREATE  view [dbo].[vwtotalbillpaidamount] as
select companyid, shopid, departmentid, billsid, billsno, referenceno, billdate, duedate, vendorid, billamount,
paidamount, Type from vwhqaccpaidbills
union all
select pbhcompanyid, shopid, pbhDepartmentid, pbhbillid, pbhbillno, pbhvendorrefno, pbhbilldate,
pbhduedate, pbhvendorid, pbhamount, paidamount, Type  from vwhqpurchasebillspaid
union all
select rh.companyid, 0, departmentid, rh.receiptid, receiptno, ReferenceNo, receiptdate,
receiptdate, vendorid, customeramount, isnull(sum(psettled),0)+ isnull(sum(vsettled),0) , ''REC''
from receiptvoucherheader rh left outer join
(select pdcompanyid, pdreceiptid, sum(pdpaidamount) psettled from ahqpaymentvoucherdetails pd,
ahqpaymentvoucherheader ph where phcompanyid = pdcompanyid and phpaymentid = pdpaymentid
and phcancelled =0 group by pdcompanyid, pdreceiptid) rsettled on rh.companyid = pdcompanyid and
rh.receiptid = pdreceiptid left outer join
(select vh.companyid , vd.receiptid, sum(settlementamount) vsettled from vendorsettlementdetail vd,
vendorsettlementheader vh where vh.companyid = vd.companyid and vh.vsid = vd.vsid and
vh.cancelled =0 group by vh.companyid, vd.receiptid) vsettled on rh.companyid = vsettled.companyid
and rh.receiptid = vsettled.receiptid where rh.cancelled =0 and rh.vendorid is not null group by
rh.companyid, departmentid, rh.receiptid, receiptno, ReferenceNo, receiptdate,
receiptdate, vendorid, customeramount
union all
select dcncompanyid, 0, dcndepartmentid, dcnid, dcnno, dcnReferenceNo, dcndate,
dcndate, dcnvendorid, dcnamount, isnull(sum(psettled),0)+ isnull(sum(vsettled),0), ''HDCN''
from debitcreditnote dcn left outer join
(select pdcompanyid, pddcnid, sum(pdpaidamount) psettled from ahqpaymentvoucherdetails pd,
ahqpaymentvoucherheader ph where phcompanyid = pdcompanyid and phpaymentid = pdpaymentid
and phcancelled =0 group by pdcompanyid, pddcnid) rsettled on dcncompanyid = pdcompanyid and
dcn.dcnid = pddcnid left outer join
(select vh.companyid , vd.dcnid vdcnid, sum(settlementamount) vsettled from vendorsettlementdetail vd,
vendorsettlementheader vh where vh.companyid = vd.companyid and vh.vsid = vd.vsid and
vh.cancelled =0 group by vh.companyid, vd.dcnid) vsettled on dcncompanyid = vsettled.companyid
and dcnid = vdcnid where dcncancelled =0 and dcn.dcndebit = 0  group by
dcncompanyid, dcndepartmentid, dcnid, dcnno, dcnReferenceNo, dcndate,
dcndate, dcnvendorid, dcnamount
union all
select lphcompanyid, shopid, lphDepartmentid, lphbillid, lphbillno, lphvendorbillno, lphbilldate,
lphduedate, lphvendorid, lphamount, paidamount, Type
from vwshoppurchasebillspaid
union all
select losdcncompanyid, losdcnshopid, losdcndepartmentid, losdcnid, losdcnno, losReferenceNo, losdcndate,
losdcndate, losdcnvendorid, losdcnamount, isnull(sum(psettled),0) + isnull(sum(vsettled),0), ''SDCN'' from
losdebitcreditnote dcn left outer join
(select pdcompanyid, pd.pdshopid, shopdcnid, sum(pdpaidamount) psettled from ahqpaymentvoucherdetails pd,
ahqpaymentvoucherheader ph where phcompanyid = pdcompanyid and phpaymentid = pdpaymentid
and phcancelled =0 group by pdcompanyid, pd.pdshopid, shopdcnid) rsettled on losdcncompanyid = pdcompanyid and
losdcnid = shopdcnid and losdcnshopid = rsettled.pdshopid left outer join
(select vh.companyid , vd.shopid, vd.losdcnid vdcnid, sum(settlementamount) vsettled from vendorsettlementdetail vd,
vendorsettlementheader vh where vh.companyid = vd.companyid and vh.vsid = vd.vsid and
vh.cancelled =0 group by vh.companyid, vd.shopid, vd.losdcnid) vsettled on losdcncompanyid = vsettled.companyid
and dcn.losdcnid = vdcnid and dcn.losdcnshopid = vsettled.shopid where losdcncancelled =0
and dcn.losdcndebit = 0 group by
losdcncompanyid, losdcnshopid, losdcndepartmentid, losdcnid, losdcnno, losReferenceNo, losdcndate,
losdcndate, losdcnvendorid, losdcnamount'
GO
/****** Object:  View [dbo].[vwtotalpayablevedorwise]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalpayablevedorwise]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwtotalpayablevedorwise    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwtotalpayablevedorwise]  as
select pay.companyid, pay.vendorid, pay.vendorname, c. currencyid, c.currencyname, Payable,
dpayable, cpayable from
(select vw.companyid, ven.vendorid, vendorname, min(ven.currencyid) currencyid,
sum( billamt - pmtamt) Payable, sum( dbillamt - dpmtamt) dPayable, sum( cbillamt - cpmtamt) cPayable
from vwsupplierledger vw, avendormaster ven
where vw.VendorID = ven.vendorid and vw.companyid = ven.companyid
group by vw.companyid, ven.vendorid, vendorname having sum( billamt - pmtamt)>0) pay,
acurrencymaster c where pay.companyid = c.companyid and pay.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwtotalpayable]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalpayable]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 25/01/03
-- Modified by   : leo
-- comments	: included the departmentid in the result
CREATE view [dbo].[vwtotalpayable]  as
select pay.companyid, pay.departmentid, c.currencyname, Payable from
(select vw.companyid, vw.departmentid, ven.currencyid, sum( billamt - pmtamt) Payable
from vwsupplierledger vw, avendormaster ven
where vw.VendorID = ven.vendorid and vw.companyid = ven.companyid
group by vw.companyid, vw.departmentid, ven.currencyid) pay,
acurrencymaster c where pay.companyid = c.companyid and pay.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vw_Report_service_CustomerLedger]    Script Date: 10/06/2012 14:17:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_Report_service_CustomerLedger]'))
EXEC dbo.sp_executesql @statement = N'
--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 [dbo].[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
/****** Object:  StoredProcedure [dbo].[spTotalTax]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTotalTax]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  procedure [dbo].[spTotalTax](@StrStartDate varchar(12), @StrEndDate  varchar(12)  ,  @DeptId int )  as
-- Modified by  : Jyothish S R
-- Date         : 17/11/2011
Begin
set nocount on
Declare  @dtStartDate as datetime,@dtEndDate as datetime
set @dtStartDate = CONVERT(DATETIME,@StrStartDate)
set @dtEndDate = CONVERT(DATETIME,@StrEndDate)
if @DeptId<>0
begin
select     t.companyid,
t.departmentid,
d.DepartmentName,
t.shopid,
s.ShopName,
t.poshBillNo,
t.billdate,
t.amount,
t.camount,
t.damount,
vw.Tamount  ,
t.TaxPercentage,
t.TaxAmount,
t.CTaxAmount,
t.DTaxAmount,
case when t.transtype=''p'' then
''cash sales''
else case when t.transtype=''d''  then
''special invoice''
else case when t.transtype=''C'' then
''Credit invoice''
else case when t.transtype=''I'' then
''invoice''
else case when t.transtype=''s'' or  t.transtype=''sbi'' then
''service invoice''
else case when t.transtype=''hs'' then
''service invoice''
else case when t.transtype=''sb'' then
''booking advance''
else case when t.transtype=''lp'' then
''service Booking''
else case when t.transtype=''e'' then
''goods exchange''
else t.transtype end end end  end end end end end end   transtype,
t.Type,
t.TrType,
t.posdItemTaxCategory,  case when TaxType=0 and posdItemTaxCategory=0 and TaxPercentage=0 then ''Sales Non Taxable'' else   ''Sales ''  + convert (varchar(50), convert(decimal(8,2), (TaxPercentage)) ) +  ''% Tax'' end as Taxhead
from  vwTotalTax t
left outer join   ashops  s  on t.shopid=s.ShopID
left outer join aDepartmentMaster d on d.DepartmentID=t.departmentid
inner join   (select departmentid,shopid,poshBillNo,transtype, SUM(camount) Tamount from vwTotalTax where   billdate between @dtStartDate and @dtendDate    and departmentid= @DeptId
group by departmentid,shopid,poshBillNo,transtype) vw  on vw.departmentid=t.departmentid and vw.shopid=t.shopid and vw.poshBillNo=t.poshBillNo and t.transtype=vw.transtype
where   billdate between @dtStartDate and @dtenddate   and t.departmentid= @DeptId
end
else
begin
select     t.companyid,
t.departmentid,
d.DepartmentName,
t.shopid,
s.ShopName,
t.poshBillNo,
t.billdate,
t.amount,
t.camount,
t.damount,
vw.Tamount  ,
t.TaxPercentage,
t.TaxAmount,
t.CTaxAmount,
t.DTaxAmount,
case when t.transtype=''p'' then
''cash sales''
else case when t.transtype=''d''  then
''special invoice''
else case when t.transtype=''C'' then
''Credit invoice''
else case when t.transtype=''I'' then
''invoice''
else case when t.transtype=''s'' or  t.transtype=''sbi'' then
''service invoice''
else case when t.transtype=''hs'' then
''service invoice''
else case when t.transtype=''sb'' then
'' booking advance''
else case when t.transtype=''lp'' then
''service Booking''
else case when t.transtype=''e'' then
''goods exchange''
else t.transtype end end end  end end end end end end   transtype,
t.Type,
t.TrType,
t.posdItemTaxCategory,  case when TaxType=0 and posdItemTaxCategory=0 and TaxPercentage=0 then ''Sales Non Taxable'' else   ''Sales ''  + convert (varchar(50), convert(decimal(8,2), (TaxPercentage)) ) +  ''% Tax'' end as Taxhead
from  vwTotalTax t
left outer join   ashops  s  on t.shopid=s.ShopID
left outer join aDepartmentMaster d on d.DepartmentID=t.departmentid
inner join   (select departmentid,shopid,poshBillNo,transtype, SUM(camount) Tamount from vwTotalTax where   billdate between @dtStartDate and @dtendDate
group by departmentid,shopid,poshBillNo,transtype) vw  on vw.departmentid=t.departmentid and vw.shopid=t.shopid and vw.poshBillNo=t.poshBillNo and t.transtype=vw.transtype
where   billdate between @dtStartDate and @dtenddate
end
set nocount off
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeGodownTransactions]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeGodownTransactions]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Regin T.
-- Create date: 28-07-2010
-- =============================================
-- Description:
--  This proc summarizes all godown transactions
--  done on or before given date.
-- =============================================
-- spSummarizeGodownTransactions ''20080531''
CREATE PROCEDURE [dbo].[spSummarizeGodownTransactions]
@strSummaryDate varchar(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @dtSummaryDate AS DATETIME
SET @dtSummaryDate = @strSummaryDate
-- Clear the summary table
DELETE FROM loiGodownTransactionsSummary
-- Compute and insert trans summary into loiGodownTransactionsSummary.
INSERT INTO
loiGodownTransactionsSummary
(SummaryDate, GodownId, ItemId, Stock, BadStock,
OpeningStock, OpeningBadStock, ShipmentId, ItemCostPrice)
-- Below part was copied from vwInquiryGodownStock
-- Date filtering was added to get only transaction done on or before summary date.
SELECT
@dtSummaryDate, gsGodownId, gsItemId, convert(numeric(18,3), sum(gsStock)) gsStock,
sum(gsBadStock) gsBadStock, sum(gsOpeningStock) gsOpeningStock,
sum(gsOpeningBadStock) gsOpeningBadStock,
1 shipmentid, max(gsItemCost) gsItemCost
FROM (
-- 1. Opening Stock
SELECT
gsGodownId, gsItemId, gsopeningstock gsStock, isnull(gsopeningbadstock,0) gsBadStock,
isnull(gsopeningstock,0 ) gsOpeningStock, isnull(gsopeningbadstock, 0) gsOpeningBadStock,
gsItemCost
FROM moigodownstock
WHERE gsStockDate<=@dtSummaryDate
UNION ALL
-- 2. Godown Bin Card For Good Stock
SELECT
godownid, itemid, transqty * mode gsstock, 0
, 0, 0, 0
FROM vwgdnbincard
WHERE gDate<=@dtSummaryDate
-- 3. Godown Bin Card For Bad Stock
UNION ALL
SELECT godownid, itemid, 0, badtransqty * mode gsbadstock
, 0, 0, 0
FROM vwgdnbincardbadqty
WHERE gDate<=@dtSummaryDate
) inqstock
GROUP BY gsGodownId, gsItemId
END -- End of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeTransactions]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSummarizeTransactions]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:  Regin T.
-- Create date: 28-07-2010
-- =============================================
-- Description:
-- This proc summarizes shop and godown transactions
-- to speed up calculating item stock.
-- =============================================
-- spSummarizeTransactions ''20080531''
CREATE PROCEDURE [dbo].[spSummarizeTransactions]
@strSummaryDate varchar(10) = ''''
AS
BEGIN
SET NOCOUNT ON;
DECLARE @dtSummaryDate AS DATETIME
-- If summary date is not specified, summarize all transactions in closed financial year.
IF @strSummaryDate = ''''
BEGIN
SELECT @dtSummaryDate=edate FROM vwFinYearPeriod
WHERE FinancialId=(SELECT max(FinancialId)-1 finid FROM aAccountFinYearOpening)
-- Convert date to ''yyyymmdd'' format
SELECT @strSummaryDate=convert(varchar(4),year(@dtSummaryDate))
+convert(varchar(2),month(@dtSummaryDate))
+convert(varchar(2),day(@dtSummaryDate))
END -- End of if
SET @dtSummaryDate=@strSummaryDate
-- Same Summary Date should be passed to both below SPs.
-- 1. Generate shop summary views
EXEC spMag_GenerateVwShopBincardAuditSummary @strSummaryDate
EXEC spMag_GenerateVwShopBincardBadQtySummary @strSummaryDate
EXEC spMag_GenerateVwInquiryShopStockSummary @strSummaryDate
-- 2. Generate godown summary views
EXEC spMag_GenerateVwGdnBinCardSummary @strSummaryDate
EXEC spMag_GenerateVwGdnBinCardBadQtySummary @strSummaryDate
EXEC spMag_GenerateVwInquiryGodownStockSummary @strSummaryDate
-- 3. Summarize shop and godown transactions
EXEC spSummarizeShopTransactions @strSummaryDate
EXEC spSummarizeGodownTransactions @strSummaryDate
-- Save that TransactionsSummary is enabled
UPDATE aPackageSettings SET TransactionsSummary=1
-- Save Summary Date in aPackageSettings table
UPDATE aPackageSettings SET TransactionsSummaryDate=@dtSummaryDate
END -- End of proc' 
END
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingGodownWise]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spStockBalancingGodownWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created by  :  Shinu
-- Created on  : 03/03/2008
-- Modified by :
-- Modified on :
-- Purpose     : To Get The Total Stock in a Shop
CREATE Proc [dbo].[spStockBalancingGodownWise] @intGodownID as Int,@strFromDate as Varchar(10),@strToDate as Varchar(10),@intActive as int AS
--declare  @strsql as nvarchar(4000)
--set @strFromDate = convert(datetime,@strFromDate,101)
--set @strToDate = convert(datetime,@strToDate,101)
if @intActive = 0
Begin
	if @intGodownID=0
		select ai.ItemID,ItemCode,ItemDescription,stock,Adjustments,itemcostprice from (
		 select gsitemid, convert(numeric(18,3), sum(stock)) stock, sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select gsitemid, isnull(sum(gsopeningstock),0) stock,0 Adjustments ,max(gsitemCost)itemcostprice
		 from moiGodownstock  group By gsitemid
		 union All
		 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0 from
		 vwgdnbincard where GDate < @strFromDate group by itemid
		 union All
		      select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0 from
		 vwgdnbincard where GDate between @strFromDate And @strToDate group by itemid
		 ) inqstock group by gsitemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.gsItemID=ai.ItemID
	else
		select ai.ItemID,ItemCode,ItemDescription,stock,Adjustments,itemcostprice from (
		 select gsitemid, convert(numeric(18,3), sum(stock)) stock, sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select gsitemid, isnull(sum(gsopeningstock),0) stock,0 Adjustments ,max(gsitemCost)itemcostprice
		 from moiGodownstock Where gsGodownID=@intGodownID group By gsitemid
		 union All
		 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0 from
		 vwgdnbincard where GDate < @strFromDate AND GodownID=@intGodownID group by itemid
		 union All
		      select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0 from
		 vwgdnbincard where GDate between @strFromDate And @strToDate AND GodownID=@intGodownID group by itemid
		 ) inqstock group by gsitemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.gsItemID=ai.ItemID
End
Else
Begin
	if @intGodownID=0
		 select ai.ItemID,ItemCode,ItemDescription,stock,Adjustments,itemcostprice from (
		 select gsitemid, convert(numeric(18,3), sum(stock)) stock, sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select gsitemid, isnull(sum(gsopeningstock),0) stock,0 Adjustments ,max(gsitemCost)itemcostprice
		 from moiGodownstock  group By gsitemid
		 union All
		 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0 from
		 vwgdnbincard where GDate < @strFromDate group by itemid
		 union All
		 select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0 from
		 vwgdnbincard where GDate between @strFromDate And @strToDate group by itemid
		 ) inqstock group by gsitemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.gsItemID=ai.ItemID
		 AND ai.Active=1
	else
		 select ai.ItemID,ItemCode,ItemDescription,stock,Adjustments,itemcostprice from (
		 select gsitemid, convert(numeric(18,3), sum(stock)) stock, sum(Adjustments) Adjustments,max(itemcostprice) itemcostprice from
		 (select gsitemid, isnull(sum(gsopeningstock),0) stock,0 Adjustments ,max(gsitemCost)itemcostprice
		 from moiGodownstock Where gsGodownID=@intGodownID group By gsitemid
		 union All
		 select itemid, convert(numeric(18,3), sum(transqty * mode)) stock,0, 0 from
		 vwgdnbincard where GDate < @strFromDate AND GodownID=@intGodownID group by itemid
		 union All
		 select itemid,0, convert(numeric(18,3), sum(transqty * mode)) stock, 0 from
		 vwgdnbincard where GDate between @strFromDate And @strToDate AND GodownID=@intGodownID group by itemid
		 ) inqstock group by gsitemid) TotalStock Left Outer JOIN Aitem ai ON TotalStock.gsItemID=ai.ItemID
		 AND ai.Active=1
End' 
END
GO
/****** Object:  View [dbo].[vwinvoicesettleformis]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinvoicesettleformis]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwinvoicesettleformis    Script Date: 18/01/2003 9:45:41 PM ******/
--Created By  : Hariharan
--Created on  : 08/01/2003
--Verified By : Hariharan
CREATE view [dbo].[vwinvoicesettleformis] as
SELECT  max(invamt) invamt,sum(isnull(settledamt,0)) settleamt , max(invamt) - sum(isnull(settledamt,0)) balance,
vwinvoices.companyid, vwinvoices.invoiceid,vwinvoices.departmentid,
vwinvoices.customerid,vwinvoices.shopid,due,invoicedate ,invoiceno,
vwinvoices.type,remarks,customername,currencyname, acustomermaster.currencyid, symbol,
max(debtortype) debtortype, departmentname, acustomermaster.customercategory FROM
{ oj ((Adminv2.dbo.vwinvoices vwinvoices INNER JOIN Adminv2.dbo.aCustomerMaster aCustomerMaster ON
vwinvoices.customerid = aCustomerMaster.CustomerID AND vwinvoices.CompanyID = aCustomerMaster.CompanyID)
LEFT OUTER JOIN Adminv2.dbo.vwsettlements vwsettlements ON vwinvoices.customerid = vwsettlements.customerid AND
vwinvoices.CompanyID = vwsettlements.companyid AND vwinvoices.InvoiceID = vwsettlements.invoiceid AND
vwinvoices.shopid = vwsettlements.shopid) INNER JOIN Adminv2.dbo.aCurrencyMaster aCurrencyMaster ON
aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = aCurrencyMaster.CompanyID},
adepartmentmaster where adepartmentmaster.departmentid = vwinvoices.departmentid group by vwinvoices.companyid,
vwinvoices.invoiceid, vwinvoices.departmentid,vwinvoices.customerid, vwinvoices.shopid,due ,invoicedate,
invoiceno,vwinvoices.type,remarks, customername,currencyname,acustomermaster.currencyid,symbol,
departmentname, acustomermaster.customercategory'
GO
/****** Object:  View [dbo].[vwtmpstock]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtmpstock]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwtmpstock] as
Select Distinct(ser.itemid),a.VendorId,a.VendorName,ser.ItemCode,ser.ItemDescription,IsNull(SStk.ShopStock,0)+IsNull(GStk.GdwnStock,0) CurStock,
ser.sizename,ser.brand,ser.itemrate,sp.sellingprice,vs.SoldQty,ImportedDate,pbdItemQuantity,pbdItemUnitPrice
From vwItemSearching ser
Left Outer Join (Select itemid,Sum(stock) ShopStock From vwInquiryShopStock
	 Group By itemid) SStk On SStk.itemid=SER.itemid
Left Outer Join (Select gsitemid,Sum(gsstock) GdwnStock From vwInquiryGodownStock
	Group By gsitemid) GStk On GStk.gsitemid=SER.itemid
Left Outer Join (Select itemid,Min(sellingprice) SellingPrice From losShopitemShipmentDetail Group By ItemId) SP On SP.itemid = SER.itemid
Left Outer Join (Select ItemId,Sum(Qty) SoldQty From vwItemDetailedSales   Group By ItemId) vs on vs.itemid=ser.itemid
Left Outer Join (Select pbditemid,max(pbhBilldate)ImportedDate,
	Sum(pbdItemQuantity) pbdItemQuantity,pbdItemUnitPrice,pbhVendorID vendorid ,av.Vendorname  vendorname
	 From lospPurchaseBillheader h,lospPurchaseBilldetail d,avendormaster av
	Where  h.pbhBillId=d.pbdBillId and pbhcancelled=0  and  pbhBilldate is not null
	and av.VendorID=h.pbhvendorID
	Group  By pbditemid,pbhVendorID,pbdItemUnitPrice,av.Vendorname ) a On
	a.pbditemid=ser.itemid
--print @strSql'
GO
/****** Object:  View [dbo].[vwstock]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstock]'))
EXEC dbo.sp_executesql @statement = N'
create view [dbo].[vwstock] as
(select  top 5 itemid,stock from vwInquiryShopStock)
union (select
top 5 gsitemid,gsstock from vwInquirygodownStock)'
GO
/****** Object:  View [dbo].[vwItemDetailsForStockReordering]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemDetailsForStockReordering]'))
EXEC dbo.sp_executesql @statement = N'
--Created By : Aneesh
--Purpose    : Stock Reordering
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE View [dbo].[vwItemDetailsForStockReordering] As
Select aitem.itemid,aitem.ItemCode,aItem.ItemRate,IsNull(SH.SStk,0) + IsNull(GStk,0) As CurrStock,
aitem.ItemDescription From aItem
Left Outer Join (Select itemid,sum(Stock) SStk From vwinquiryshopstock Group By itemid) SH
On aItem.ItemId=SH.ItemId
Left Outer Join (Select gsItemId,Sum(gsStock) GStk From vwinquirygodownstock Group by gsitemid) GD
On aItem.ItemId=GD.gsItemId  Where aitem.Active=1'
GO
/****** Object:  View [dbo].[VWDailyItemSalesWithStock]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VWDailyItemSalesWithStock]'))
EXEC dbo.sp_executesql @statement = N'
------------------------------------------------------------------------------------------------------------------------
--sp_helptext vwDailyItemSalesWithStock
--select * from VWDailyItemSalesWithStock where shopid=1 and poshBillDate =''20070101''
------------------------------------------------------------------------------------------------------------------------
-- Created On  : 24/11/2007
-- Created By  : Shinu
-- Comments    : Created for a new Report  [rptSalesAndStock]
------------------------------------------------------------------------------------------------------------------------
CREATE VIEW [dbo].[VWDailyItemSalesWithStock] AS
SELECT sd.poshShopid,posdItemId, sd.posdUnitPrice, sd.cUnitPrice, sd.dUnitPrice,
sum(sd.posdquantity) posdQuantity, sid.Stock,
sd.poshBillDate,a.ItemCode, a.ItemDescription,
costprice, cCostPrice, dCostPrice, z.SizeName, u.UnitCode, c.ColorName,
MIN(sid.sellingprice) SellingPrice,
MIN(sid.wholesaleprice) WholeSalePrice, MIN(sid.discountprice ) DiscountPrice,
SUM(Amount) Amount, SUM(cAmount) cAmount, SUM(dAmount) dAmount,
a.Brand, ic.CategoryNameDescription, cm.Symbol SpCurrencySymbol,a.part_code ,ShopName
FROM vwShopItemSales sd
LEFT Outer Join
(SELECT sd.ItemId, sd.Shopid, MIN(SellingPrice) SellingPrice,
MIN(WholeSalePrice) WholeSalePrice, MIN(DiscountPrice) DiscountPrice, CurrencyId ,sum(TotalStock.Stock)stock
FROM losShopItemShipmentDetail sd, vwitemretailpacking pd,
((select  itemid,stock from vwInquiryShopStock)
union all (select gsitemid,gsstock from vwInquirygodownStock))TotalStock
WHERE sd.itemid = pd.itemid
AND sd.Packingtypeid = pd.packingTypeId AND  sd.itemid=TotalStock.ItemID
GROUP BY Sd.ItemId, Sd.ShopId, sd.CurrencyId) sid
ON sd.posditemid = sid.itemid
AND (sd.poshshopid = sid.shopid OR sid.shopid IS NULL)
LEFT OUTER JOIN aCurrencyMaster cm
ON sid.CurrencyId = cm.CurrencyId,aShops s, aUnit u, aItem a
LEFT OUTER JOIN aColor c ON a.ColorID = c.ColorID
LEFT OUTER JOIN aSize z ON a.SizeID = z.SizeID, aItemCategory ic
WHERE sd.poshShopID = s.ShopID
AND a.UnitsID = u.UnitID
AND posdItemID = a.itemid
AND a.ItemCategoryId = ic.ItemCategoryId
GROUP BY sd.poshBilldate,
a.Brand, ic.CategoryNameDescription,  sid.Stock,
a.ItemCode, a.ItemDescription, z.SizeName,
u.UnitCode, c.ColorName, sd.posdunitprice, sd.cUnitPrice, sd.dUnitPrice,
sd.costprice, sd.cCostPrice, sd.dCostPrice, posditemid, cm.Symbol,a.part_code,sd.poshShopid,ShopName'
GO
/****** Object:  View [dbo].[vwcurrentstocksonee]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcurrentstocksonee]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwcurrentstocksonee] as(
SELECT I.ItemID,ItemCode,ItemDescription,Brand,sum(Stock) Stock, ItemRate,SellingPrice,categorynamedescription as Category FROM aitem I
INNER JOIN
	(SELECT Sum(Stock)Stock,ItemID FROM  vwInquiryShopStock GROUP By ItemID
	UNION
	SELECT Sum (gsStock)Stock,gsItemID FROM vwInquiryGodownStock GROUP By gsItemID )VG
ON I.ItemID=VG.ItemID
INNER JOIN (select los.ItemID,SellingPrice FROM losshopItemShipmentDetail los INNER JOIN aItemPackingDetail ap
		 ON  los.ItemID=ap.ItemID AND los.PackingTypeID =ap.PackingTypeID AND PackingSlNo=1 ) SP
ON I.ItemID=SP.ItemID
inner join aitemcategory on i.itemcategoryid= aitemcategory.itemcategoryid
GROUP BY  I.ItemID,ItemCode,ItemDescription,Brand,ItemRate,SellingPrice,categorynamedescription)'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPrice]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCostingMethodPrice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
--modified by  : hariharan, Hariharan ,jyothish
--modified Date : 07/01/2003, 28/04/2004,01/02/2012
--considered vwinquiryshopstock and vwinquirygodownstock.
--Verified by hariharan on 08/01/2003
--prevoius  prevoius  stock and costprice  insert to losCosAvlStock
CREATE proc [dbo].[spUpdateCostingMethodPrice] (@intItemID as int, @CostPrice as numeric(18,2),
@intBillID as int, @numWAVGAmt as numeric(18,2)  output
) as
begin
declare @IntCostingID as int
declare @numTotal numeric(18,3)
declare @numGdnQty numeric(18,3)
declare @numShopQty numeric(18,3)
declare @numTotalQty numeric(18,3)
declare @numBillQty numeric(18,3)
declare @numItemUP numeric(18,2)   -- from Item Master
declare @numnoncosteditems as numeric(18,3)
declare @numprocpendqtystock as numeric(18,3)
declare @numothershipments as numeric(18,3),
@numprevunreceivedqty as numeric(18,3),
@numprevunconfirmedqty as numeric(18,3),
@numnondespbillqty as numeric(18,3)
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
Select @numGdnQty = isnull(sum(isnull(gsstock,0)),0) from vwinquirygodownstock where
gsitemid = @intItemID
Select @numShopQty = isnull(sum(isnull(stock,0)),0) from vwinquiryshopstock where
itemid = @intItemID
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' 
END
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryTotalstock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquiryTotalstock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE proc [dbo].[sppandcinquiryTotalstock] @intitemid as int as
select sum(gsstock) as Totalstock,gsGodownid, godownname from vwInquiryGodownStock g, agodown a where gsitemid=
@intitemid  and g.gsgodownid=a.godownid GROUP BY gsgodownid,godownname,gsitemid
union
select sum(stock) as Totalstock,s.shopid, a.shopname from vwInquiryShopStock s, ashops a where itemid=
@intitemid  and s.shopid=a.shopid GROUP BY s.shopid,shopname,itemid' 
END
GO
/****** Object:  StoredProcedure [dbo].[splocalpurchasecosting]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[splocalpurchasecosting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryForecast]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------------------------
-- 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
-----------------------------------------------------------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCorrectCostPriceinDespatch]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCorrectCostPriceinDespatch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--CREATED BY	 : Hariharan
--Created Date	 : 13/02/2004
CREATE Proc [dbo].[spCorrectCostPriceinDespatch] as
set nocount on
Begin
Declare @intCount as int,
	@intItemId as int,
	@intGodownId as int,
	@intInvoiceId as int,
	@invDate as datetime,
	@CostPrice as numeric(18,2),
	@intCurrId as int,
	@NumCurCostPrice as numeric(18,2),
	@strDespatchNo as varchar(50),
	@intArrivalId as int,
	@intShopId as int,
	@ArrivalNo as varchar(50)
Create table #DespatchToShop
		(ispdnvoiceDate Datetime,
		ispdtemid int,
		ispdnvoiceId int,	
		spShopId int,
		spCorrected bit,
		ItemCostPr numeric(18, 2),
		InvoiceNo  varchar(50))
Insert #DespatchToShop
Select dhDespatchDate, ddItemId, ddDespatchID, ddGodownId, 0, Itemrate, dhDespatchNo from
MeiDespatchToShopDetail, MeiDespatchToShopHeader, aitem where
dhDespatchId = ddDespatchID and dhGodownId = ddGodownId and dhCancelled = 0 and
ddCostedPrice = 1 and dhDespatchDate >= ''20040101'' and dditemid = aitem.itemid
order by dhDespatchdate, ddGodownId, ddDespatchID, ddItemid
	Set @intCount = 0
	Set @intItemId = 0
	Set @intGodownId = 0
	Set @intInvoiceId = 0
Select @intCount = count(*) from #DespatchToShop where spCorrected = 0
While @intcount <> 0
	
	Begin
		
		Set @CostPrice = 0
		
		Select top 1 @invDate = ispdnvoiceDate, @intItemId = ispdtemID,
		@intInvoiceId = ispdnvoiceId, @intGodownId = spShopID,
		@NumCurCostPrice = ItemCostPr, @strDespatchNo = InvoiceNo from  #DespatchToShop
		where spCorrected = 0	
		Select top 1 @CostPrice = isnull(cdNewItemCostPrice,0) from
		loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
		and ChCancelled = 0 and isnull(chCostingDate, ''20030101'') <= @invDate
		and cdItemId = @intItemId order by cdCostingId desc
		set @CostPrice  = isnull(@CostPrice , 0)
		set @NumCurCostPrice = isnull(@NumCurCostPrice, 0)
		if @CostPrice = 0
			Select top 1 @CostPrice = isnull(cdOldItemCostPrice,0) from
			loaCostingDetail, loaCostingHeader where cdCostingId = chCostingId
			and ChCancelled = 0 and cdItemId = @intItemId order by cdCostingId
		set @CostPrice  = isnull(@CostPrice , 0)
		if @CostPrice <> 0
			Update MeiDespatchToShopDetail set ddCostedPrice = @Costprice
			where dditemid = @intItemID and ddDespatchID = @intinvoiceId and
			ddGodownId = @intGodownId
		else	--in case of item costprice not available in costing detail tables
			Update MeiDespatchToShopDetail set ddCostedPrice = @NumCurCostPrice
			where dditemid = @intItemID and ddDespatchID = @intinvoiceId and
			ddGodownId = @intGodownId
	
		Update #DespatchToShop set spCorrected = 1 where ispdnvoiceId = @intInvoiceId
		and spShopId = @intGodownId and ispdtemID = @intItemId
		Update MeiDespatchToShopHeader set dhPosted = 0, dhfuturevc =''u'' where
		dhDespatchno = @strDespatchNo and dhGodownId = @intGodownId and
		dhDespatchId = @intInvoiceId
		Update MoajournalHeader set Cancel = 1 where Referenceno = @strDespatchNo and
		Type = ''invdts'' and journaldate >=''20040101''
				
		Update LosGoodsarrivaltoshopdetail set gadCostPrice = ddCostedPrice 	
		from LosGoodsArrivaltoshopheader, meiDespatchtoshopheader,
		meiDespatchtoshopDetail where gadShopId = gahShopId and
		gahArrivalId = gadArrivalID and gahGodownDespatchId = dhDespatchId
		and gahDespatchedGodownId = dhGodownId and dhDespatcHId= dddespatchid
		and dhGodownId = ddGodownId and ddItemid = gadItemId
		and dditemid  = @intItemId and dhdespatchid = @intInvoiceId
		and dhGodownid = @intGodownId
		set @intArrivalId = 0
		set @intshopid = 0
		set @arrivalNo=  ''''
	
		Select @intArrivalId = gahArrivalId, @intShopId = gahSHopID,
		@arrivalNo= GahArrivalNo from
		LosGoodsArrivaltoshopheader, meiDespatchtoshopheader
		where gahGodownDespatchId = dhDespatchId
		and gahDespatchedGodownId = dhGodownId and dhDespatchId= @intInvoiceId
		and dhGodownId = @intGodownId	
		Update losGoodsarrivaltoshopheader set gahposted = 0, gahfuturevc =''u'' where
		gaharrivalid = @intArrivalId and gahShopId = @intShopId
		Update Moajournalheader set Cancel = 1 where referenceno = @Arrivalno
		and type = ''sga'' and journaldate >=''20040101''
		
		Select @intCount = count(*) from #DespatchToShop where spCorrected = 0
	End
End
set nocount oFF' 
END
GO
/****** Object:  View [dbo].[vwInquiryGodownStockSummary]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquiryGodownStockSummary]'))
EXEC dbo.sp_executesql @statement = N'
-- ===============================================
-- This view was automatically generated
-- by spMag_GenerateVwInquiryGodownStockSummary.
-- Alter above proc to make any change in this view.
-- ===============================================
-- Author      : Regin T.
-- Create Date : 28-07-2010
-- Description :
--   To compute godown stock using transactions summary.
--    This view is created based on vwInquiryGodownStock.
--    Godown Transactions Summary part is additionally added.
-- ===============================================
CREATE VIEW [dbo].[vwInquiryGodownStockSummary] AS
SELECT
GodownId gsGodownId, ItemId gsItemId
, isnull(convert(numeric(18,3), sum(stock)),0) gsStock
, sum(badstock) gsBadStock, sum(openingstock) gsOpeningStock
, sum(openingbadstock) gsOpeningBadStock
, 1 gsShipmentId, 1 gsLocationId
, max(itemcostprice) gsItemCost
FROM (
-- 1. Godown Transactions Summary
SELECT
GodownId, ItemId, Stock, BadStock
, OpeningStock, OpeningBadStock, ItemCostPrice
FROM loiGodownTransactionsSummary
UNION ALL
-- 2. Opening Stock
SELECT  gsgodownid, gsitemid
, gsopeningstock gsstock, isnull(gsopeningbadstock,0) gsbadstock
, isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost
FROM moigodownstock
WHERE gsStockDate>''20100803''
UNION ALL
-- 3. Godown Bin Card For Good Stock
SELECT godownid, itemid, transqty * mode gsstock, 0
, 0, 0, 0
FROM vwGdnBincardSummary
UNION ALL
-- 4. Godown Bin Card For Bad Stock
SELECT godownid, itemid, 0, badtransqty * mode gsbadstock
,0, 0, 0
FROM vwGdnBincardBadQtySummary
) inqstock
GROUP BY godownid, itemid'
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPriceSummary]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCostingMethodPriceSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---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' 
END
GO
/****** Object:  View [dbo].[vwInquirygodownStockDatewise]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwInquirygodownStockDatewise]'))
EXEC dbo.sp_executesql @statement = N'
CREATE view [dbo].[vwInquirygodownStockDatewise] as
select gsgodownid, gsitemid, isnull(convert(numeric(18,3), sum(gsstock)),0) gsstock,
sum(gsbadstock) gsbadstock, sum(gsopeningstock) gsopeningstock, sum(gsopeningbadstock)
gsopeningbadstock, 1 gsshipmentid, 1 gslocationid, max(gsitemcost) gsitemcost,gsStockDate from
(
select  gsgodownid, gsitemid, gsopeningstock gsstock, isnull(gsopeningbadstock,0) gsbadstock,
isnull(gsopeningstock,0 ) gsopeningstock, isnull(gsopeningbadstock, 0) gsopeningbadstock,
gsitemcost,gsStockDate  from moigodownstock
union all
select godownid, itemid, isnull(convert(numeric(18,3), sum(transqty * mode)),0) gsstock, 0, 0, 0, 0,GDate from
vwgdnbincard group by godownid,itemid,GDate
union all --for taking bad qty
select godownid,itemid,  0,  convert(numeric(18,3),sum(badtransqty * mode)) gsbadstock,
0, 0, 0,GDate  from vwgdnbincardbadqty group by godownid, itemid, GDate) inqstock
group by GSgodownid, GSitemid,gsStockDate
-------------------------------------------'
GO
/****** Object:  View [dbo].[vwinquirygodownstockalllocation]    Script Date: 10/06/2012 14:17:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwinquirygodownstockalllocation]'))
EXEC dbo.sp_executesql @statement = N'
--Modified on 	: 28/03/2003
--Modified by 	: R Harikrishnan
--Comments 	: Removed the Openrowset
CREATE  view [dbo].[vwinquirygodownstockalllocation] as
select gsgodownid, gsitemid,  gsstock, isnull(gsbadstock,0)gsbadstock, isnull(gsopeningstock,0) gsopeningstock,
isnull(gsopeningbadstock,0)gsopeningbadstock,  gsshipmentid,  gslocationid, gsitemcost
from (select gsgodownid, gsitemid,  gsstock, gsbadstock, gsopeningstock,
gsopeningbadstock,  gsshipmentid,  gslocationid, gsitemcost from
adminv2.dbo.vwinquirygodownstock) a'
GO
/****** Object:  StoredProcedure [dbo].[spMonthSalesShopWise]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthSalesShopWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[spMonthSalesShopWise] (@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitshopwise as int = 1, @intDepartmentid as int=0 ,@strShopID AS Varchar(20)='''') as
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@dtMonthStartDate as datetime,
@dtMonthEndDate as datetime,
@strShopName as varchar(100),
@strDate as varchar(10),
@strMonth as varchar(20),
@strYear as varchar(10),
@intMonth as int,
@intYear as int,
@intShopID as int,
@numTotalSales as numeric(18,2),
@numdTotalSales as numeric(18,2),
@numcTotalSales as numeric(18,2),
@strintcount as varchar(3),
@intcount as int, @intDepId as int,
@strShopCond as varchar (100)
declare @strSql as nvarchar(2000)
Create table #MonthSales(SlNo int, ShopName varchar(100), Months varchar(20),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2),
DepartmentID int)
set @intcount = 0
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
set @intMonth = datepart(m,@dtFromDate)
set @intYear = datepart(yyyy,@dtFromDate)
set @dtMonthStartDate = @dtFromDate
if @strShopID    <>''''
	set @strShopCond='' where shopname in (select ShopName from Ashops where shopID in (''+ @strShopId + ''))''
Else
	set @strShopCond=''''
if @intMonth = 12
begin
set @intMonth = 1
set @intYear = @intYear + 1
end
else
begin
set @intMonth = @intMonth + 1
end
set @dtMonthEndDate  = cast(@intyear as varchar(4))+''/''+cast(@intmonth as varchar(2))+''/''+''01''
set @dtMonthEndDate = @dtMonthEndDate - 1
if @dtMonthEndDate > @dtToDate
begin
set @dtMonthEndDate = @dtToDate
end
while @dtMonthEndDate  <= @dtToDate
begin
set @intcount = @intcount + 1
set @strintcount  = @intcount
set @strMonth = ''Month '' + @strintcount
set @strmonth = convert(varchar(4),year(@dtmonthenddate)) + ''-'' +
--  convert(varchar(2),month(@dtmonthenddate)) + '' - '' +
left(datename(month,@dtmonthenddate),3)
if @strType = ''CA''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) ,
isnull(sum(isnull(camount,0.0)),0.0), Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 1 and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 1 group by departmentID
end
end
else if @strType = ''CR''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0)),0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) ,
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 group by departmentID
end
end
else if @strType = ''TO''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0), Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
group by departmentID
end
end
open ShopCur
fetch next from ShopCur into @intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID
while @@fetch_status <> -1
begin
if (@bitshopwise = 1)
begin
select @strShopName = ShopName from ashops where shopid = @intshopID
insert into #MonthSales values( @intcount, @strShopName, @strMonth,
@numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID)
end
else
begin
select @strShopName = departmentName from adepartmentmaster where departmentid = @intshopID
insert into #MonthSales values( @intcount, @strShopName, @strMonth,
@numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID)
end
fetch next from ShopCur into @intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID
end
close ShopCur
Deallocate ShopCur
set @dtMonthStartDate = @dtMonthEndDate + 1
set @intMonth = datepart(m,@dtMonthStartDaTe)
if @intMonth = 12
begin
set @intMonth = 1
set @intYear = @intYear + 1
end
else
set @intMonth = @intMonth + 1
set @dtMonthEndDate  = cast(@intyear as varchar(4))+''/''+cast(@intmonth as varchar(2))+''/''+''01''
set @dtMonthEndDate = @dtMonthEndDate - 1
if @dtMonthEndDate > @dtToDate
begin
set @dtMonthEndDate = @dtToDate
end
if @dtmonthstartDate < @dtToDate
continue
else
break
End
if @intdepartmentid >0
select ShopName, Months, TotalSales, slno MonthNo, dTotalSales, cTotalSales
from #MonthSales where departmentId = @intDepartmentId order by slno
else
set  @strSql = N''select ShopName, Months, TotalSales, slno MonthNo, dTotalSales, cTotalSales
	from #MonthSales '' + @strShopCond + '' order by slno''
print @strSql
exec sp_executesql  @strSql
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMonthsalesall]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthsalesall]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--------------------------------------------------------------
--Modified on 		: 13/12/02
--Modified by		: leo
--Comments		: v3
----------------------------------------------
--Last Modified on 	: 09/04/2003
--Modified by		: R Harikrishnan
--Comments		: Added Department ID
----------------------------------------------
CREATE proc [dbo].[spMonthsalesall]
	(
		@strFromDate as varchar(10), @strToDate as varchar(10),
		@strType as varchar(2),@bitshopwise as bit =1,
		@intDepartmentID as int,@intCompanyID as int=0
	) as
set nocount on
begin
	Declare @dtFromDate as datetime,
		@dtToDate as datetime,
		@dtDateValue as datetime,
		@strShopName as varchar(100),
		@strWeek as varchar(23),
		@intWeekDay as int,
		@intShopID as int,
		@intReminingDays as int,
		@numTotalSales as numeric(18,2),
		@numdTotalSales as numeric(18,2),
		@numcTotalSales as numeric(18,2),
		@strintcount as varchar(3),
		@intcount as int,
		@dtweekenddate as datetime
	Create table #WeekSales
		(
			SlNo int,
			ShopName varchar(100),
			Weeks varchar(23),
			TotalSales numeric(18,2),
			dTotalSales numeric(18,2),
			cTotalSales numeric(18,2)
		)
	set @intcount = 0
	set @strintcount =''''
	set @dtFromDate = convert(datetime,@strFromDate)
	set @dtTodate = convert(datetime,@strToDate)
	set @dtdatevalue = @dtfromdate
	
	while @dtDateValue <= @dtToDate
		begin
			set @intcount = @intcount + 1
			set @strintcount  = @intcount
			/*set @strweek = convert(varchar(4),year(dateadd(d,1,@dtdatevalue)))+ ''/''+
			convert(varchar(2),month(dateadd(d,1,@dtdatevalue))) + ''/'' +
			convert(varchar(2),day(dateadd(d,1,@dtdatevalue))) + '' - ''
			+ convert(varchar(4),year(DateAdd(d, 7, @dtDateValue))) +''/''+
			convert(varchar(2),month(DateAdd(d, 7, @dtDateValue))) +
			''/'' + convert(varchar(2),day(DateAdd(d, 7, @dtDateValue)))*/
			set @strweek = convert(varchar(4),year(@dtdatevalue))+ ''/''+
			convert(varchar(2),month(@dtdatevalue)) + ''/'' +
			convert(varchar(2),day(@dtdatevalue)) + '' - ''
			+ convert(varchar(4),year(DateAdd(d, 6, @dtDateValue))) +''/''+
			convert(varchar(2),month(DateAdd(d, 6, @dtDateValue))) +
			''/'' + convert(varchar(2),day(DateAdd(d, 6, @dtDateValue)))
		set @dtweekenddate = DateAdd(d, 6, @dtDateValue)
		if @dtweekenddate > @dtToDate
			set @dtweekenddate = @dtToDate
			if @strType = ''CA''
				begin
				if (@bitshopwise =1)
					begin
						if @dtdatevalue = @dtfromdate
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
											isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and shopid is not null and companyID=@intCompanyID
										group by
											ShopID
								Else
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
											isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and shopid is not null and companyID=@intCompanyID
											and DepartmentId=@intDepartmentID
										group by
											ShopID									
							end
						else
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and shopid is not null  and companyID=@intCompanyID
										group by
											ShopID
								else
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and shopid is not null  and companyID=@intCompanyID
											and departmentID=@intDepartmentID
										group by
											ShopID
							end
					end
				else
					begin
						if @dtdatevalue  = @dtfromdate
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and companyID=@intCompanyID
										group by
											departmentID
								else
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and companyID=@intCompanyID
											and departmentid=@intDepartmentID
										group by
											departmentID
							end
						else
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and companyID=@intCompanyID
										group by
											departmentID
								else
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and cash = 1 and companyID=@intCompanyID
											and departmentID=@intDepartmentID
										group by
											departmentID
							end		
					end
				end
		else if @strType = ''CR''
			begin
				if (@bitshopwise =1)
					begin
						if @intDepartmentID =0
							declare ShopCur cursor for
								select
									ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
									isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
								from
									vwsalesanalysisbyweek
								where
									Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
									and cash = 0 and shopid is not null  and companyID=@intCompanyID
								group by
									ShopID
						else
							declare ShopCur cursor for
								select
									ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
									isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
								from
									vwsalesanalysisbyweek
								where
									Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
									and cash = 0 and shopid is not null  and companyID=@intCompanyID
									and departmentID=@intDepartmentID
								group by
									ShopID
					end
				else
					begin
						if @intDepartmentID =0
							declare ShopCur cursor for
								select
									departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
									isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
								from
									vwsalesanalysisbyweek
								where
									Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
									and cash = 0 and companyID=@intCompanyID
								group by
									departmentID
						else
							declare ShopCur cursor for
								select
									departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
									isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
								from
									vwsalesanalysisbyweek
								where
									Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
									and cash = 0 and companyID=@intCompanyID
									and departmentID=@intDepartmentID
								group by
									departmentID
					end
			end
		else if @strType = ''TO''
			begin
				if (@bitshopwise =1)
					begin
						if @dtdatevalue = @dtfromdate
							begin	
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and shopid is not null and companyID=@intCompanyID
										group by
											ShopID
								else
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and shopid is not null 	and companyID=@intCompanyID
											and DepartmentID=@intDepartmentID
										group by
											ShopID
							end
						else
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and shopid is not null 	and companyID=@intCompanyID
										group by
											ShopID
								else
									declare ShopCur cursor for
										select
											ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and shopid is not null 	and companyID=@intCompanyID
											and departmentID=@intDepartmentID
										group by
											ShopID
							end	
					end
				else
					begin
						if @dtdatevalue = @dtfromdate
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and companyid=@intCompanyID
										group by
											departmentID
								else
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and companyid=@intCompanyID and DepartmentID=@intDepartmentID
										group by
											departmentID
							end
						else
							begin
								if @intDepartmentID =0
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0)),0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and companyID =@intCompanyID
										group by
											departmentID
								else
									declare ShopCur cursor for
										select
											departmentID, isnull(sum(isnull(actamount,0)),0),
											isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
										from
											vwsalesanalysisbyweek
										where
											Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
											and companyID =@intCompanyID and departmentID=@intDepartmentID
										group by
											departmentID
							end
					end
			end
			open ShopCur
			fetch next from
				ShopCur
			into
				@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
			while @@fetch_status <> -1
				begin
					if (@bitshopwise =1)
						begin
							select
								@strShopName = ShopName
							from
								ashops
							where
								shopid = @intshopID
							insert into #WeekSales values
								( @intcount, @strShopName, @strweek, @numTotalSales
								, @numdTotalSales, @numcTotalSales)
						end
					else
						begin
							select
								@strShopName = departmentName
							from
								adepartmentmaster
							where
								departmentid = @intshopID
							insert into #WeekSales values
								( @intcount, @strShopName, @strweek, @numTotalSales
								, @numdTotalSales, @numcTotalSales)
						end
					fetch next from
						ShopCur
					into
						@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
				end
				close ShopCur
				Deallocate ShopCur
			        set @dtDateValue = DateAdd(d, 7, @dtDateValue)
				if @dtDateValue > @dtToDate
					break
				else
					continue
	end
	select
		ShopName, Weeks, TotalSales, slno weekno ,dTotalSales,cTotalSales
	from
		#WeekSales
	order by
		Slno
end
--------------------------------------------------------------' 
END
GO
/****** Object:  StoredProcedure [dbo].[spMonthSales]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMonthSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Modified By   : Hariharan
-- Modified Date : 13/01/2004
------------------------------------------------------------------------------------------
-- Modified by : Bijesh.B
-- Date        : 03/07/2011
-- RefNo       : RefNo-2
-- Comments    : PD Cheque feature added
--  exec spWeekSales ''20080707'',''20080707'',''pd'',1,0,1
------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spMonthSales] (@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2), @bitshopwise as bit = 1, @intDepartmentid as int=0 ) as
begin
set nocount on
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@dtMonthStartDate as datetime,
@dtMonthEndDate as datetime,
@strShopName as varchar(100),
@strDate as varchar(10),
@strMonth as varchar(20),
@strYear as varchar(10),
@intMonth as int,
@intYear as int,
@intShopID as int,
@numTotalSales as numeric(18,2),
@numdTotalSales as numeric(18,2),
@numcTotalSales as numeric(18,2),
@strintcount as varchar(3),
@intcount as int, @intDepId as int
Create table #MonthSales(SlNo int, ShopName varchar(100), Months varchar(20),
TotalSales numeric(18,2), dTotalSales numeric(18,2), cTotalSales numeric(18,2),
DepartmentID int)
set @intcount = 0
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
set @intMonth = datepart(m,@dtFromDate)
set @intYear = datepart(yyyy,@dtFromDate)
set @dtMonthStartDate = @dtFromDate
if @intMonth = 12
begin
set @intMonth = 1
set @intYear = @intYear + 1
end
else
begin
set @intMonth = @intMonth + 1
end
set @dtMonthEndDate  = cast(@intyear as varchar(4))+''/''+cast(@intmonth as varchar(2))+''/''+''01''
set @dtMonthEndDate = @dtMonthEndDate - 1
if @dtMonthEndDate > @dtToDate
begin
set @dtMonthEndDate = @dtToDate
end
while @dtMonthEndDate  <= @dtToDate
begin
set @intcount = @intcount + 1
set @strintcount  = @intcount
set @strMonth = ''Month '' + @strintcount
set @strmonth = convert(varchar(4),year(@dtmonthenddate)) + ''-'' +
--  convert(varchar(2),month(@dtmonthenddate)) + '' - '' +
left(datename(month,@dtmonthenddate),3)
if @strType = ''CA''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) ,
isnull(sum(isnull(camount,0.0)),0.0), Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 1 and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 1 group by departmentID
end
end
else if @strType = ''CR''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0)),0) , Departmentid
from vwsalesanalysisbymonth
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) ,
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 group by departmentID
end
end
--RefNo-2 start --------------------------------------------------------
-- PD Cheque Amount only
else if @strType = ''PD''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0)),0) , Departmentid
from vwsalesanalysisbymonth
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) ,
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and cash = 0 group by departmentID
end
end
--RefNo-2 end --------------------------------------------------------
else if @strType = ''TO''
begin
if (@bitshopwise = 1)
begin
declare ShopCur cursor for
select ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0) , Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
and shopid is not null group by Departmentid, ShopID
end
else
begin
declare ShopCur cursor for
select departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0), Departmentid
from vwsalesanalysisbymonth
where Billdate >= @dtMonthStartDate and Billdate <= @dtMonthEndDate
group by departmentID
end
end
open ShopCur
fetch next from ShopCur into @intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID
while @@fetch_status <> -1
begin
if (@bitshopwise = 1)
begin
select @strShopName = ShopName from ashops where shopid = @intshopID
insert into #MonthSales values( @intcount, @strShopName, @strMonth,
@numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID)
end
else
begin
select @strShopName = departmentName from adepartmentmaster where departmentid = @intshopID
insert into #MonthSales values( @intcount, @strShopName, @strMonth,
@numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID)
end
fetch next from ShopCur into @intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales, @intDepID
end
close ShopCur
Deallocate ShopCur
set @dtMonthStartDate = @dtMonthEndDate + 1
set @intMonth = datepart(m,@dtMonthStartDaTe)
if @intMonth = 12
begin
set @intMonth = 1
set @intYear = @intYear + 1
end
else
set @intMonth = @intMonth + 1
set @dtMonthEndDate  = cast(@intyear as varchar(4))+''/''+cast(@intmonth as varchar(2))+''/''+''01''
set @dtMonthEndDate = @dtMonthEndDate - 1
if @dtMonthEndDate > @dtToDate
begin
set @dtMonthEndDate = @dtToDate
end
if @dtmonthstartDate < @dtToDate
continue
else
break
End
if @intdepartmentid >0
select ShopName, Months, TotalSales, slno MonthNo, dTotalSales, cTotalSales
from #MonthSales where departmentId = @intDepartmentId order by slno
else
select ShopName, Months, TotalSales, slno MonthNo, dTotalSales, cTotalSales
from #MonthSales order by slno
end' 
END
GO
/****** Object:  View [dbo].[vwtotalreceivablecustwise]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalreceivablecustwise]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
--Verified by 	    	: Hariharan
--Verified Date     	: 04/05/2004 (verified From Dev Server(Fies))
CREATE view [dbo].[vwtotalreceivablecustwise] as
select rec.companyid, rec.departmentid, rec.departmentname, rec.customerid, rec.customername,
receivable, dreceivable, creceivable, c.currencyid, c.currencyname, rec.CustomerCategory from
(select vw.companyid, sum(InvAmt - pmtamt) receivable, sum(dInvAmt - dpmtamt) dreceivable,
sum(cInvAmt - cpmtamt) creceivable, vw.departmentid, dep.departmentname, cus.customerid,
cus.customername, min(cus.currencyid) currencyid, cus.CustomerCategory
from vwcustomerledger vw, acustomermaster cus, adepartmentmaster dep
where vw.customerid = cus.customerid and vw.companyid = cus.companyid and
dep.companyid = vw.companyid and dep.departmentid=vw.departmentid
group by vw.companyid, vw.departmentid, dep.departmentname, cus.customerid,
cus.customername,cus.CustomerCategory ) rec,
acurrencymaster c where rec.companyid = c.companyid and rec.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwtotalreceivable]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalreceivable]'))
EXEC dbo.sp_executesql @statement = N'
-- Last Modified : 25/01/03
-- Modified by   : leo
-- comments	: included the departmentid in the result
CREATE view [dbo].[vwtotalreceivable] as
select rec.companyid, rec.departmentid, c.currencyname , receivable from
(select vw.companyid, departmentid, cus.currencyid, sum(InvAmt - pmtamt) receivable
from vwcustomerledger vw, acustomermaster cus
where vw.customerid = cus.customerid and vw.companyid = cus.companyid
group by vw.companyid, vw.departmentid, cus.currencyid) rec, acurrencymaster c where
rec.companyid = c.companyid and rec.currencyid = c.currencyid'
GO
/****** Object:  View [dbo].[vwTotalInvoiceReceiptAmount]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwTotalInvoiceReceiptAmount]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
-- Modified On  : 04/09/2003, 08/10/2003, 06/04/2004
-- Modified By : R Harikrishnan, Hariharan R, Hariharan R
-- Comments : Added the types Room Billing and Utility Billing
--  : GIVEN cancelled condition
--Modified by :Nidheesh
--Modified on :20/03/10
--Comments : Added the type Fine Invoice
---------------------------------------------------------------------------------------
--Modified on :22-04-10
--Modified by :Sreejith G A
--comments: Commented the code written by Nidheesh for Fine Invoice
--   Intitially Only settled Fine invoices from Accounts Receipts and Customer Setttlements got populated
--   Written a new code snippet for Fine Invoice
--Modified on :26-11-10
--Modified by :jyothish
--- FANDBInvoice is added
----------------------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwTotalInvoiceReceiptAmount] as
select
companyid,shopid,aiinvoiceid invoiceid, aidepartmentid departmentid, convert (varchar(50), refno) refno,
invoiceno, aiinvoicedate invoicedate, duedate, aicustomerid customerid,
invoiceamt, settled, Type
from
vwshopserinvandrecamount
union all
select CompanyID,poshShopID,poshBillID,DepartmentID,'''' refno ,
poshBillNo,poshBillDate,duedate,poshcustomerid,
poshBillAmount,  settledamount,type from vwFANDBInvoice
union all
select
companyid,shopid,invoiceid, ihdepartmentid departmentid,convert (varchar(50), refno) refno,invoiceno,
invoicedate,ihduedate,customerid,amount,settled,Type
from
vwshopcreditinvrecamount
union all
select
companyid,shopid,invoiceid, departmentid, convert (varchar(50), ReferenceNo) ReferenceNo,invoiceno, invoicedate,duedate,
customerid,amount,settled,Type
from
vwhqserinvandrecamount
union all
select
companyid,shopid,invoiceid, ihdepartmentid departmentid, convert (varchar(50), refno) refno,invoiceno,
invoicedate,ihduedate,customerid,amount,settled,Type
from
vwspecialinvrecamount
union all
--for service module invoices
select
companyid,shopid,invoiceid, departmentid, convert (varchar(50), refno) refno,invoiceno, invoicedate,
serinvhduedate, customerid, serinvhamount, settled, Type
from
vwbookservinvoicesettle
UNION ALL
--for shop debit note
select
losdcncompanyid, losdcnshopid, losdcnid, losdcndepartmentid,convert (varchar(50), refno) refno,
losdcnno, losdcndate, duedate, losDCNCustomerID, losdcnamount, settled, type
from
vwshopdrcrinvandrecamount
UNION ALL
--for payment
select
phcompanyid, shopid, phpaymentid, phdepartmentid, convert (varchar(50), refno) refno, phpaymentno, phpaymentdate,
duedate, phCustomerID, phcustomeramount, settled, type
from
vwhqpaymentinvandrecamount
UNION ALL
--for payment
select
dcncompanyid, shopid, dcnid, dcndepartmentid,convert (varchar(50), refno) refno,  dcnno, dcndate,
duedate, dcnCustomerID, dcnamount, settled, type
from
vwhqdrcrinvandrecamount
UNION ALL
--for rexporting transactions - hari 020312
select
companyid,shopid,invoiceid, departmentid,convert (varchar(50), refno) refno, invoiceno, invoicedate, rehduedate,
customerid, rehexportamount, settled, Type
from
vwreexportinvoicesettled
UNION ALL
--for Room Billing -- R Harikrishnan 030904
select
abh.abhcompanyid, abh.abhshopid, abh.abhBillID, abh.abhdepartmentid departmentid,
convert(varchar(50), abh.abhReferenceNo) abhReferenceNo, abh.abhBillNo,
abh.abhBillDate, abh.abhDueDate, abh.abhcustomerid,
Avg(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn) BillAmount,
sum(isnull(stl.settledamt,0)) settled, ''RBI'' type
from
losApartmentBillHeader abh left outer join
(select
st.companyid, st.shopid, st.RoomBillID, st.customerid, 0.0 as invoiceamount,
max(receiptdate) receiptdate, sum(settledamt) settledamt
from
(select
rh.companyid, rd.shopid, rd.RoomBillID RoomBillID, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived)
settledamt
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and
rh.cancelled = 0 and rd.RoomBillID is not null
group by
rh.companyid, rd.shopid, rd.RoomBillID, rh.customerid
union all
select
ch.companyid, cd.shopid, cd.RoomBillID RoomBillID, ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt
from
customersettlementheader ch, customersettlementdetail cd
where
ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0 and
cd.RoomBillID is not null
group by
ch.companyid, cd.shopid, cd.RoomBillID, ch.customerid) st
group by
st.companyid, st.shopid, st.RoomBillID, st.customerid) stl
on abh.abhCompanyid = stl.companyid and abh.abhShopid = stl.shopid and
abh.abhBillID =  stl.RoomBillID
Where
(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)>0  and
abh.abhCashAccID is null and abh.abhCancelled = 0
group by
abh.abhcompanyid, abh.abhdepartmentid, abh.abhshopid, abh.abhReferenceNo,
abh.abhBillID,  abh.abhBillNo, abh.abhBillDate, abh.abhDueDate,
abh.abhcustomerid
UNION ALL
--Utility Billing for Manaam --R Harikrishnan 030904
select
tbh.tbhcompanyid, tbh.tbhshopid, tbh.tbhBillID, tbh.tbhdepartmentid departmentid,
convert(varchar(50), tbh.tbhReferenceNo) tbhReferenceNo, tbh.tbhBillNo, tbh.tbhBillDate, tbh.tbhDueDate, tbh.tbhcustomerid,
Avg(tbhAmount) BillAmount,
sum(isnull(stl.settledamt,0)) settled, ''UTB'' type
from
losTenantServiceBillHeader tbh left outer join
(select
st.companyid, st.shopid, st.UtilityBillID, st.customerid, 0.0 as invoiceamount,
max(receiptdate) receiptdate, sum(settledamt) settledamt
from
(select
rh.companyid, rd.shopid, rd.UtilityBillID, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived)
settledamt
from
receiptvoucherheader rh, receiptvoucherdetails rd
where
rh.companyid=rd.companyid and rh.receiptid = rd.receiptid and
rh.cancelled = 0 and rd.UtilityBillID is not null
group by
rh.companyid, rd.shopid, rd.UtilityBillID, rh.customerid
union all
select
ch.companyid, cd.shopid, cd.UtilityBillID UtilityBillID, ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt
from
customersettlementheader ch, customersettlementdetail cd
where
ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0 and
cd.UtilityBillID is not null
group by
ch.companyid, cd.shopid, cd.UtilityBillID, ch.customerid) st
group by
st.companyid, st.shopid, st.UtilityBillID, st.customerid) stl
on tbh.tbhCompanyid = stl.companyid and tbh.tbhShopid = stl.shopid and
tbh.tbhBillID =  stl.UtilityBillID
Where
(tbhAmount)>0  and tbh.tbhBankCashID is null and tbhCancelled = 0
group by
tbh.tbhcompanyid, tbh.tbhdepartmentid, tbh.tbhshopid, tbh.tbhReferenceNo,
tbh.tbhBillID,  tbh.tbhBillNo, tbh.tbhBillDate, tbh.tbhDueDate,
tbh.tbhcustomerid
union all
---FINE INVOICE----
--select stld.companyid, stld.shopid, stld.fineid,f.fhDepartmentID ,f.fhInvoiceNo,f.fhFineNo,fhInvoiceDate,'''',
--stld.customerid,f.fdFineAmount,settledamt,''FINE''type
--from
--(
--select
--st.companyid, st.shopid, st.fineid, st.customerid, 0.0 as invoiceamount,
--max(receiptdate) receiptdate, sum(settledamt) settledamt
--from
--(
--select rh.companyid, rd.shopid, rd.fineid, rh.customerid,
--0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived)settledamt
--from receiptvoucherdetails rd,receiptvoucherheader rh
--where rd.receiptid = rh.receiptid and rd.companyid = rh.companyid
--and cancelled = 0 and fineid is not null
--group by rh.companyid, rd.shopid, rd.fineid, rh.customerid
--
--union all
--
--select ch.companyid, cd.shopid, cd.fineid , ch.customerid, 0.0 as invoiceamt,
--max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt
--from customersettlementheader ch,customersettlementdetail cd where
--ch.CSID=cd.CSID and ch.CompanyID=cd.CompanyID and
--ch.cancelled=0 and cd.fineid is not null
--group by ch.companyid, cd.shopid, cd.fineid, ch.customerid
--)st
--group by
--st.companyid, st.shopid, st.fineid, st.customerid
--)stld
--left outer join
--(select fhDepartmentID ,fhInvoiceNo,fhFineNo,fhInvoiceDate,
--fhFineID,sum(fdFineAmount)fdFineAmount from afineheader h inner join afinedetail d on h.fhFineID =d.fdFineID
--group by fhDepartmentID ,fhInvoiceNo,fhFineNo,fhInvoiceDate,fhFineID )f
--on f.fhFineID=stld.fineid
select fhCompanyID, fhshopid,fhFineID,fhDepartmentID departmentid,fhInvoiceNo,fhFineNo,fhInvoiceDate
,fhLastFineCalDate,fhCustomerID,fdFineAmount,isnull(sum(settledamt),0),''FINE''type
from
(
select fhCompanyID,fhDepartmentID ,fhcustomerid,fhInvoiceNo,fhFineNo,fhshopid,fhInvoiceDate,fhTransactiontype,
fhFineID,sum(fdFineAmount)fdFineAmount,fhLastFineCalDate from afineheader h inner join afinedetail d on h.fhFineID =d.fdFineID
where     isnull(fhInvoiceCancelled,0)=0
group by fhCompanyID,fhDepartmentID ,fhcustomerid,fhInvoiceNo,fhFineNo,fhshopid,fhInvoiceDate,fhTransactiontype,fhFineID,fhLastFineCalDate
)v
left outer join
(
select rh.companyid, rd.shopid, rd.fineid, rh.customerid,
0.0 as invoiceamt, max(rh.receiptdate) receiptdate, sum(amountreceived)settledamt
from receiptvoucherdetails rd,receiptvoucherheader rh
where rd.receiptid = rh.receiptid and rd.companyid = rh.companyid
and cancelled = 0 and fineid is not null
group by rh.companyid, rd.shopid, rd.fineid, rh.customerid
union all
select ch.companyid, cd.shopid, cd.fineid , ch.customerid, 0.0 as invoiceamt,
max(ch.CSDATE) receiptdate, sum(cd.SettlementAmount) settledamt
from customersettlementheader ch,customersettlementdetail cd where
ch.CSID=cd.CSID and ch.CompanyID=cd.CompanyID and
ch.cancelled=0 and cd.fineid is not null
group by ch.companyid, cd.shopid, cd.fineid, ch.customerid
)v1  on
v.fhCompanyID=v1.companyid and v.fhfineid=v1.fineid and v.fhcustomerid=v1.customerid
group by fhCompanyID,fhshopid,fhFineID,fhDepartmentID ,fhInvoiceNo,fhFineNo,fhInvoiceDate
,fhLastFineCalDate,fhCustomerID,fdFineAmount'
GO
/****** Object:  View [dbo].[vwstockout]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwstockout]'))
EXEC dbo.sp_executesql @statement = N'
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----
--Last Modified on  : 12/12/02
--Modified by  : leo
--Comments  : v3
--comments          : 130803 brandcolumn added by venki
--Verified by       : Hariharan
--Verified Date      : 04/05/2004 (verified From Dev Server(Fies))
--Modified By :Nidheesh
--Modified on :16-09-09
--Comments : included the condition while stock is equal to itemreorderlevel
CREATE view [dbo].[vwstockout] as
select stock.itemid, stock.itemcode, stock.itemdescription, stock.itemreorderlevel,
stock.reorderquantity, stock.godownid, stock.colorname, stock.sizename,
stock.categorynamedescription, stock.itemcategoryid,  stock.Stock,stock.brand
from (select d.itemid,itemcode,itemdescription,itemreorderlevel,d.reorderquantity,d.godownid,
isnull(C.COLORNAME,'''') colorname ,isnull(z.sizename,'''') sizename, ic.categorynamedescription,
ic.itemcategoryid,a.brand,  isnull(gsStock, 0.0) Stock
from aitem  a left outer join acolor c on
a.colorid=c.colorid left outer join asize z on a.sizeid=z.sizeid,aGodownDetail d
left outer join vwinquirygodownstock stock on stock.gsgodownid = d.godownid
and stock.gsitemid = d.itemid , aitemcategory ic
where a.itemid=d.itemid and a.itemcategoryid=ic.itemcategoryid ) stock
where stock.itemreorderlevel>=stock.stock'
GO
/****** Object:  View [dbo].[vwCreditorAgeSum]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCreditorAgeSum]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwCreditorAgeSum    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on 	: 26/10/2002
--Modified by 		: leo
--created as second batch 0n 09/11/2002 by hariharan from fi-es10
CREATE view [dbo].[vwCreditorAgeSum] as
select companyid, shopid, departmentid, billsid, billsno, referenceno, billdate, duedate,
vendorid, billamount, paidamount, type, '' 0 - 30 '' as due
from vwtotalbillpaidamount
where (getdate() - billDate between 0 and 30)
union all
select companyid, shopid, departmentid, billsid, billsno, referenceno, billdate, duedate,
vendorid, billamount, paidamount, type, '' 31 - 60 '' as due
from vwtotalbillpaidamount
where (getdate() - billDate between 31 and 60)
union all
select companyid, shopid, departmentid, billsid, billsno, referenceno, billdate, duedate,
vendorid, billamount, paidamount, type, '' 61 - 90 '' as due
from vwtotalbillpaidamount
where (getdate() - billDate between 61 and 90)
union all
select companyid, shopid, departmentid, billsid, billsno, referenceno, billdate, duedate,
vendorid, billamount, paidamount, type, '' > 90 '' as due
from vwtotalbillpaidamount
where (getdate() - billDate > 90)'
GO
/****** Object:  View [dbo].[vwnetcreditsales]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwnetcreditsales]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwnetcreditsales    Script Date: 18/01/2003 9:45:42 PM ******/
/****** Object:  View dbo.vwnetcreditsales    Script Date: 14/09/2002 12:48:12 AM ******/
/****** Object:  View dbo.vwnetcreditsales    Script Date: 31/07/2002 2:00:33 PM ******/
/****** Object:  View dbo.vwnetcreditsales    Script Date: 20/11/2001 9:59:10 AM ******/
/****** Object:  View dbo.vwnetcreditsales    Script Date: 17/11/2001 9:22:10 PM ******/
-- Last Modified on: 24/10/2001
-- Modified by     : leo
CREATE view [dbo].[vwnetcreditsales] as
select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, convert(numeric(18,2),Amount) Amount,
"1" as type , "Credit Sales" As Trans
from vwcreditsales, acustomermaster
where ihcashinvoice=0 and ihcustomerid=customerid
--group by ihcompanyid, ihshopid, customerid, customername, ihinvoicedate
union all
select drcompanyid, drshopid, customername, drchequeno refereneceno, drdate,
convert(numeric(18,2),drAmount) amount, "2" as type,
"Receipts Details" Trans
from losDummyReceiptHeader rh, acustomermaster cm where drcancelled=0 and rh.drcustomerid=
cm.customerid and rh.drcompanyid=cm.companyid
union all
select phcompanyid, phshopid, phRemarks, phpaymentno referenceno, phPaymentDate,
convert(numeric(18,2),phAmount) amount, "3" as type,
"Payment Details" Trans
from LOsPaymentVoucherHeader ph where phcancelled=0'
GO
/****** Object:  StoredProcedure [dbo].[spcustomerbalanceasondate]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spcustomerbalanceasondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spcustomerbalanceasondate    Script Date: 18/01/2003 9:45:49 PM ******/
/****** Object:  Stored Procedure dbo.spcustomerbalanceasondate    Script Date: 14/09/2002 12:48:19 AM ******/
/****** Object:  Stored Procedure dbo.spcustomerbalanceasondate    Script Date: 31/07/2002 2:00:40 PM ******/
/****** Object:  Stored Procedure dbo.spcustomerbalanceasondate    Script Date: 20/11/2001 9:59:20 AM ******/
/****** Object:  Stored Procedure dbo.spcustomerbalanceasondate    Script Date: 17/11/2001 9:22:41 PM ******/
--created by leo
--to get the customer balance as on any date supplied, if not date passed then
-- it is assumed that the balance is till date
CREATE proc [dbo].[spcustomerbalanceasondate] @intcompanyid int, @intcustomerid int,
@strtilldate varchar(10) as
begin
	declare @dttilldate as datetime,
		@bitason as bit
	if @strtilldate =''''
		set @bitason =1
	else
	begin
		set @bitason =0
		set @dttilldate = convert(datetime,@strtilldate,101)
	end
	if (@bitason =0)	-- till the date supplied
		select isnull(sum(invamt) - sum(pmtamt),0) balance from vwcustomerledger where companyid =
		@intcompanyid and customerid = @intcustomerid and tdate <= @dttilldate
	else
		select isnull(sum(invamt) - sum(pmtamt),0) balance from vwcustomerledger where companyid =
		@intcompanyid and customerid = @intcustomerid 		
	
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff_ServerBackup]    Script Date: 10/06/2012 14:17: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].[spCustomerArriveExDiff_ServerBackup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Modified on		: 14/06/2005
--Modified by 		: Hariharan R
--Comments		: Modified the vendor selection
--			: Removed the currencyid filteration and allowed all
--			: customers to undergo checking, Incorporated vwCustomerledger in temp1 insertion to increase speed
/*
This SP modified and send to SIMDI as emergency before testing. So to keep a back up I changed name of SP and placed in same server.
*/
CREATE proc [dbo].[spCustomerArriveExDiff_ServerBackup]
		@intcompanyid as int, @strexrates as varchar(250),
		@strcurdate as varchar(10),@intDepartmentID as int=0, @Depwise as char(1) =''d'' as
begin
set nocount on
set ansi_warnings off
declare @intcount as int,
	@intcustomerid as int,
	@numdepbal as numeric(18,2),
	@numconsbal as numeric(18,2),
	@numresbal as numeric(18,2),
	@strcustomername as varchar(250),
	@intDepCurrID as int,
	@intcusCurrID as int,
	@intConsCurrID as int,
	@numdepamount as numeric(18,2),
	@numConsamount as numeric(18,2)	,
	@straccounttype as char(1),
	@bitjournalcredit as bit,
	@numdiffamt as numeric(18,2)
CREATE table #temp1(
	companyid int,
	customerid int,
	customername varchar(250),
	CurrencyID int,
	resbal numeric(18,2),
	consbal numeric(18,2)
	)
CREATE table #temp2(
	companyid int,
	customerid int,
	customername varchar(250),
	DepBalance numeric(18,2),
	consbalance numeric(18,2),
	resbalance numeric(18,2),
	depamount  numeric(18,2),
	consamount  numeric(18,2),
	journalcredit bit
	)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
	where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the customer other than company currency are taken into the temp table
if @DepWise =''d''
Begin
	insert into #temp1
	select C.companyid, C.customerid, customername, currencyID,
	sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
	sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0))  from acustomermaster c,
	ashopCustomerDetails s, vwcustomerledger V
	where c.companyid =@intcompanyid --and currencyid <> @intDepCurrID	
	and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from
	ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)
	AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId
	and c.Companyid = v.CompanyId group by C.companyid, C.customerid,
	customername, currencyID
End
Else
Begin
	insert into #temp1
	select c.companyid, c.customerid, customername, currencyID,
	sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
	sum(isnull(cinvamt,0)) - sum(isnull(cpmtamt,0)) from acustomermaster c,
	ashopCustomerDetails s, vwCustomerLedger V
	where c.companyid =@intcompanyid -- and currencyid <> @intConsCurrID	
	and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from
	ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)
	AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId
	and c.Companyid = v.CompanyId group by C.companyid, C.customerid,
	customername, currencyID
End
select @intcount = count(*) from #temp1
while @intcount <> 0
begin	-- for while
	set @numconsbal =0.0
	set @numresbal = 0.0
	set @numdepbal = 0.0
	select @intcustomerid = customerid, @strcustomername = customername,
	@intcusCurrID=CurrencyID, @numresbal = resbal, @numdepbal = consbal from #temp1
	if @DepWise =''d''
	exec spConvertequiamount @intcusCurrID, ''m'', @intDepCurrID,
		''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
	else
	exec spConvertequiamount @intcusCurrID, ''m'', @intConsCurrID,
		''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
	if abs(@numdepbal - @numdepamount) >= 1 -- this has the exchange difference
	begin
		if (@numdepamount > @numDepbal)
			set @bitjournalcredit =0
		if (@numdepamount < @numDepbal)
			set @bitjournalcredit =1
	set @numdiffamt  = abs(@numdepamount - @numDepbal)
	if @DepWise =''d''	-- department currency
	Begin
		exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
		''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
		insert into #temp2 values
		(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,
		@numConsbal,@numresbal,@numdepamount, @numConsamount, @bitjournalcredit)
	End
	else -- Consolidation Currency
	Begin
		exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
		''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
		insert into #temp2 values
		(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,
		@numConsbal,@numresbal, @numConsamount ,@numdepamount, @bitjournalcredit)
	End
	end
	delete from #temp1 where customerid = @intcustomerid
	select @intcount = count(*) from #temp1
end	-- for while
select * from #temp2
set nocount off
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff]    Script Date: 10/06/2012 14:17: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].[spCustomerArriveExDiff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
-Modified on  : 14/06/2005
--Modified by   : Hariharan R
--Comments  : Modified the vendor selection
--   : Removed the currencyid filteration and allowed all
--   : customers to undergo checking, Incorporated vwCustomerledger in temp1 insertion to increase speed
----modified by      : jyothish
--modified Date     : 15/12/2011
------------------------------------------------------------------
Reference   No : 01	
Modified	By : Shine Das
Modified	On : 13.04.2012
Comments	   : Customer Adjustment entry was wrong.
*/
CREATE  proc [dbo].[spCustomerArriveExDiff]
@intcompanyid as int, @strexrates as varchar(250),
@strcurdate as varchar(10),@intDepartmentID as int=0, @Depwise as char(1) =''d'' as
begin
set nocount on
set ansi_warnings off
declare @intcount as int,
@intcustomerid as int,
@numdepbal as numeric(18,2),
@numconsbal as numeric(18,2),
@numresbal as numeric(18,2),
@strcustomername as varchar(250),
@intDepCurrID as int,
@intcusCurrID as int,
@intConsCurrID as int,
@numdepamount as numeric(18,2),
@numConsamount as numeric(18,2) ,
@straccounttype as char(1),
@bitjournalcredit as bit,
@numdiffamt as numeric(18,2),
@numResBalInConsCurrency as numeric(18,2)         --- -- Reference   No : 01 Added new field
-- Reference   No : 01 Commented	
--CREATE table #temp1(
-- companyid int,
-- customerid int,
-- customername varchar(250),
-- CurrencyID int,
-- resbal numeric(18,2),
-- consbal numeric(18,2)
-- )
----- Reference   No : 01 Added
	CREATE table #temp1(
	 companyid int,
	 customerid int,
	 customername varchar(250),
	 CurrencyID int,
	 resbal numeric(18,2),
	 consbal numeric(18,2),
	 depbal numeric(18,2)      -- Reference   No : 01 Added new field to store Department amount
	 )
CREATE table #temp2(
companyid int,
customerid int,
customername varchar(250),
DepBalance numeric(18,2),
consbalance numeric(18,2),
resbalance numeric(18,2),
depamount  numeric(18,2),
consamount  numeric(18,2),
journalcredit bit
)
select @intDepCurrID =depcurrencyid from aDepartmentMaster
where companyid =@intcompanyid and departmentID= @intDepartmentID
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID
-- all the customer other than company currency are taken into the temp table
if @DepWise =''d''
Begin
insert into #temp1
select C.companyid, C.customerid, customername, currencyID,
sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0)),
sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0))  -- Reference   No : 01 Find Department Balance
from acustomermaster c,
vwcustomerledger V
where c.companyid =@intcompanyid --and currencyid <> @intDepCurrID
AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId
and c.Companyid = v.CompanyId and tdate <= @strcurdate group by C.companyid, C.customerid,
customername, currencyID
--select C.companyid, C.customerid, customername, currencyID,
--sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
--sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0))  from acustomermaster c,
--ashopCustomerDetails s, vwcustomerledger V
--where c.companyid =@intcompanyid --and currencyid <> @intDepCurrID
--and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from
--ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)
--AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId
--and c.Companyid = v.CompanyId group by C.companyid, C.customerid,
--customername, currencyID
--Jyothish commeted this code15/12/2011
End
Else
Begin
insert into #temp1
			 select c.companyid, c.customerid, c.customername, c.currencyID,
			 sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
			 sum(isnull(cinvamt,0)) - sum(isnull(cpmtamt,0)),
			 sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0)) -- Reference   No : 01 Find Department Balance
			 from vwCustomerLedger v inner join
			 acustomermaster c on c.CustomerID = v.customerid
			 where c.customerId = v.customerid and v.departmentid =@intDepartmentId
			 group by c.companyid, c.customerid, c.customername, c.currencyID
			
			 -- Reference   No : 01 Commented; Result was wrong when run the below qry. So change made and
			 -- placed above.
				 --select c.companyid, c.customerid, customername, currencyID,
				 --sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),
				 --sum(isnull(cinvamt,0)) - sum(isnull(cpmtamt,0)) from acustomermaster c,
				 --ashopCustomerDetails s, vwCustomerLedger V
				 --where c.companyid =@intcompanyid -- and currencyid <> @intConsCurrID
				 --and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from
				 --ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)
				 --AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId
				 --and c.Companyid = v.CompanyId group by C.companyid, C.customerid,
				 --customername, currencyID
End
select @intcount = count(*) from #temp1
while @intcount <> 0
begin -- for while
set @numconsbal =0.0
set @numresbal = 0.0
set @numdepbal = 0.0
-- Reference   No : 01 Commented
--select @intcustomerid = customerid, @strcustomername = customername,
--@intcusCurrID=CurrencyID, @numresbal = resbal, @numdepbal = consbal from #temp1
			 -- -- Reference   No : 01 Added Below
			  select @intcustomerid = customerid, @strcustomername = customername,
			 @intcusCurrID=CurrencyID, @numresbal = resbal, @numdepbal = depbal, @numconsbal = consbal from #temp1
			
-- SD if @DepWise =''d''
	exec spConvertequiamount @intcusCurrID, ''m'', @intDepCurrID,
	''m'', @strexrates , @numresbal, @numdepamount output,  ''r''
-- SD else
	exec spConvertequiamount @intcusCurrID, ''m'', @intConsCurrID,
	''m'', @strexrates , @numresbal, @numResBalInConsCurrency output,  ''r''
	
/* --     -- Reference   No : 01 Commented
if abs(@numdepbal - @numdepamount) >= 1 -- this has the exchange difference
begin
if (@numdepamount > @numDepbal)
set @bitjournalcredit =0
if (@numdepamount < @numDepbal)
set @bitjournalcredit =1
*/
-- Reference   No : 01 Added Below
if abs(@numconsbal - @numResBalInConsCurrency) >= 1 -- this has the exchange difference
begin
if (@numResBalInConsCurrency > @numconsbal)
set @bitjournalcredit =0
if (@numResBalInConsCurrency < @numconsbal)
set @bitjournalcredit =1
--set @numdiffamt  = abs(@numdepamount - @numDepbal)
set @numdiffamt  = abs(@numResBalInConsCurrency - @numconsbal)
if @DepWise =''d'' -- department currency
Begin
exec spConvertequiamount @intDepCurrID, ''m'', @intConsCurrID,
''m'', @strexrates , @numdiffamt, @numConsamount output,  ''r''
insert into #temp2 values
(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,
@numConsbal,@numresbal,@numdiffamt, @numConsamount, @bitjournalcredit)
End
else -- Consolidation Currency
Begin
exec spConvertequiamount @intConsCurrID, ''m'', @intDepCurrID,
''m'', @strexrates , @numdiffamt, @numdepamount output,  ''r''
-- Reference   No : 01 Commented
--insert into #temp2 values
--(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,
--@numConsbal,@numresbal, @numConsamount ,@numdepamount, @bitjournalcredit)
-- Reference   No : 01 Added Below
	  insert into #temp2 values
(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,
@numConsbal,@numresbal, @numdepamount,@numdiffamt, @bitjournalcredit)
End
end
delete from #temp1 where customerid = @intcustomerid
select @intcount = count(*) from #temp1
end -- for while
select * from #temp2
set nocount off
set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerLedger]    Script Date: 10/06/2012 14:17: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].[spCustomerLedger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---spCustomerLedger 1,''20110101'',''20111124'','''',1,0,'''',''''
--Modified By :-Benzigar S D
--Modified On :-06/10/2010
--Comment     :-If Customer statement is taking Dep wise, if from date changing balace also will change.
--              Because else part is no there. So if dep wise report is taking. company wise balance will show
--Ref         :-Ref:-1
--------------------------------------------------------------------------------------------------------------------
--Modified By : Nidheesh P V
--Modified On : 01/06/2011
--Reason   : There was some error while loading customer statement report for ''SONEE''.Customer advance is taken in the
--sub report''rptdebtoragesum'' in the customerstatement report.
--So advance is taken in the main report itself, in order to do this modified the sp ''spCustomerLedger''.
--Modifications : Added the customer advance in the sp.
--Modified Area : rptcustomerledgerall
--Ref         : Ref:-2
--------------------------------------------------------------------------------------------------------------------
CREATE  proc [dbo].[spCustomerLedger] @intCompanyID as int,
@strFromdate as varchar(8),
@strToDate as varchar(8),
@strcustomerid as varchar(2000),
@intdepartmentid as int ,@intShopId as int =0,
@strCatName as Varchar(30)='''', @strGroupName as Varchar(30)=''''
as
begin
set nocount on
Set ansi_warnings off
create table #temp(
companyid  int,
customerid  int,
opdebitamt  numeric(18,2),
opcreditamt  numeric(18,2)
)
declare @dtFromdate as datetime,
@dtTodate as datetime,
@intcustid as int,
@dtfinstartdate as datetime,
@numopeningcredit as numeric(18,2),
@numopeningdebit as numeric(18,2),
@strsql as nvarchar(4000),
@bitason as bit,
@strCatCond as Varchar(300),
@strGroupCond as Varchar(300)
set @strCatCond=''''
set @strGroupCond=''''
if @strCatName<>''''
set @strCatCond = ''And vw.CustomerCategory = '''''' + @strCatName + ''''''''
if @strGroupName<>''''
set @strGroupCond = '' And vw.CustGroupName = '''''' + @strGroupName + ''''''''
if @strcustomerid <> '''' -- hari included to handle all customers
set @strcustomerid = '' and vw.customerid in ('' + @strcustomerid + '') ''
if (@strfromdate <>'''')
begin
set @dtfromdate = convert(datetime,@strfromdate,101)
set @bitason =0
end
else
begin
set @bitason =1
end
set @dttodate = convert(datetime,@strtodate,101)
if (@bitason =0)
begin -- if the statement is for a period
set @strsql =N''declare opcur cursor for
SELECT customerid FROM vwcustomerledger vw
WHERE vw.companyid ='' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and
vw.tdate <='''''' + convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid
+  @strCatCond  + @strGroupCond
+ '' group by customerid''
---print @strsql
exec sp_executesql @strsql
open opcur
fetch next from opcur into @intcustid
while @@fetch_status =0
begin
set @numOpeningCredit =0.0
set @numOpeningDebit  =0.0
if @intdepartmentid<>0
begin
SELECT  @numOpeningCredit = (SELECT isnull(sum(pmtamt),0)  FROM
vwcustomerledger vw
WHERE vw.departmentid=@intdepartmentid and vw.companyid = @intcompanyid
and tdate < @dtFROMDate and customerid = @intcustid )
SELECT  @numOpeningDebit = (SELECT isnull(sum(invamt),0)  FROM
vwcustomerledger c
WHERE c.departmentid=@intdepartmentid and c.companyid = @intcompanyid
and c.customerid = @intcustid and tdate < @dtfromdate)
end
else if @intShopId<>0
begin
SELECT  @numOpeningCredit = (SELECT isnull(sum(pmtamt),0)  FROM
vwcustomerledger vw
WHERE vw.Shopid=@intShopId and vw.companyid = @intcompanyid
and tdate < @dtFROMDate and customerid = @intcustid )
SELECT  @numOpeningDebit = (SELECT isnull(sum(invamt),0)  FROM
vwcustomerledger c
WHERE c.Shopid=@intShopId and c.companyid = @intcompanyid
and c.customerid = @intcustid and tdate < @dtfromdate)
end
else   -- Ref:-1
begin
SELECT  @numOpeningCredit = (SELECT isnull(sum(pmtamt),0)  FROM
vwcustomerledger vw
WHERE vw.companyid = @intcompanyid and tdate < @dtFROMDate and
customerid = @intcustid )
SELECT  @numOpeningDebit = (SELECT isnull(sum(invamt),0)  FROM
vwcustomerledger c
WHERE c.companyid = @intcompanyid and c.customerid = @intcustid
and tdate < @dtfromdate)
end
insert into #temp values (@intcompanyid, @intcustid, @numopeningdebit,
@numopeningcredit)
fetch next from opcur into @intcustid
end -- end for while
close opcur
deallocate opcur
end -- end for opening balance calculation
if (@intdepartmentid = 0)  and @intShopId = 0
Begin
if (@bitason =0)
begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, #temp.OpCreditAmt, #temp.OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond --Ref:-2
end
else -- for with out from date
begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and  vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond  --Ref:-2
end
End
else if @intdepartmentid<> 0   -- FOR department
Begin
if (@bitason =0)
begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, #temp.OpCreditAmt, #temp.OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond  + '' and
vw.departmentid ='' + convert(varchar(3),@intdepartmentid) --Ref:-2
end
else --for with out from date
Begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond  + '' and
vw.departmentid ='' + convert(varchar(3),@intdepartmentid)  --Ref:-2
End
End
else if @intShopid<>0
begin
if (@bitason =0)
begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, #temp.OpCreditAmt, #temp.OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate >='''''' +
convert(varchar(10),@dtfromdate,101) + '''''' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond  + '' and
vw.Shopid ='' + convert(varchar(3),@intShopId)    --Ref:-2
end
else --for with out from date
Begin
set @strsql = ''select one.CustomerName, one.Address1, one.Address2, one.Address3,
one.CreditLimit, vw.*, 0.0 OpCreditAmt, 0.0 OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomerledger vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.tdate <='''''' +
convert(varchar(10),@dttodate,101) + '''''''' + @strcustomerid +  @strCatCond  + @strGroupCond  + '' and
vw.Shopid ='' + convert(varchar(3),@intShopId)  --Ref:-2
End
end
----Ref:-2--------
--print @strsql
set @strsql = @strsql + ''
UNION ALL
select distinct one.CustomerName, one.Address1, one.Address2, one.Address3,one.CreditLimit,
vw.companyid,
case when '' + convert(varchar(3),@intdepartmentid) + '' =0 then
0
else
vw.departmentid end departmentid,
vw.customerid,'''''''' as invoicedate,'''''''' as secref,'''''''' as tno,'''''''' as cr,''''Advance'''' as type,'''''''' as remarks,
0.00 as invamt,
case when '' + convert(varchar(3),@intdepartmentid) + '' =0 then
sum(isnull(vw.advance,0))over(partition by vw.customerid)
else
sum(isnull(vw.advance,0))over(partition by vw.customerid,vw.departmentid)end advance ,
'''''''' as duedate,0 as age,'''''''' as updatetime,'''''''' as setdate,
0.00 as cinvamt,
case when '' + convert(varchar(3),@intdepartmentid) + '' =0 then
sum(isnull(vw.advance,0))over(partition by vw.customerid)
else
sum(isnull(vw.advance,0))over(partition by vw.customerid,vw.departmentid)end advance ,
0 as financialid,'''''''' as chequedetails,0 as debtoraccid,
0.00 as dinvamt,
case when '' + convert(varchar(3),@intdepartmentid) + '' =0 then
sum(isnull(vw.advance,0))over(partition by vw.customerid)
else
sum(isnull(vw.advance,0))over(partition by vw.customerid,vw.departmentid)end advance ,            CustomerCategory as customercategory, custgroupname as custgroupname,'''''''' as exchangerates,0 as SettledAmt,0 as shopid,
0.0 OpCreditAmt, 0.0 OpDebitAmt, one.CurrencyName, one.Symbol
from vwcustomersummaryasdate vw
left outer join #temp on vw.companyid = #temp.companyid and vw.customerid = #temp.customerid
left outer join (select c.companyid, customerid, customername, currencyname, symbol, address1, address2,
address3, creditlimit from acustomermaster c, acurrencymaster cur where c.companyid =
cur.companyid and c.currencyid = cur.currencyid ) one on vw.companyid = one.companyid and
vw.customerid = one.customerid
where vw.companyid = '' + convert(varchar(5),@intcompanyid) + '' and vw.invoicedate <= '''''' + convert(varchar(10),@dttodate,101) + ''''''
and (vw.departmentid ='' + convert(varchar(3),@intdepartmentid) + '' or '' + convert(varchar(3),@intdepartmentid) + ''=0)
and (vw.Shopid ='' + convert(varchar(3),@intShopId) + '' or '' + convert(varchar(3),@intShopId) + '' =0) and isnull(vw.advance,0)<>0 ''
+ @strcustomerid +  @strCatCond  + @strGroupCond  + '' order by  one.customername,vw.tdate, vw.updatetime''
-----Ref:-2-------
exec sp_executesql @strsql
set nocount off
Set ansi_warnings on
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquirygodownstock]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sppandcinquirygodownstock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.sppandcinquirygodownstock    Script Date: 18/01/2003 9:45:49 PM ******/
/****** Object:  Stored Procedure dbo.sppandcinquirygodownstock    Script Date: 14/09/2002 12:48:19 AM ******/
/****** Object:  Stored Procedure dbo.sppandcinquirygodownstock    Script Date: 31/07/2002 2:00:40 PM ******/
-- created on	: 21/07/2002
-- Created by	: leo
CREATE proc [dbo].[sppandcinquirygodownstock] @intitemid as int as
select sum(gsstock) as Totalstock,gsGodownid, godownname from vwInquiryGodownStock g, agodown a where gsitemid=
@intitemid  and g.gsgodownid=a.godownid GROUP BY gsgodownid,godownname,gsitemid' 
END
GO
/****** Object:  StoredProcedure [dbo].[spopeningCustomerbalancewithAge]    Script Date: 10/06/2012 14:17:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spopeningCustomerbalancewithAge]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spopeningCustomerbalancewithAge    Script Date: 18/01/2003 9:45:49 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments		: v3
CREATE proc [dbo].[spopeningCustomerbalancewithAge] (@intcompanyid as int, @intcustomerid as int,
@strfromdate as varchar(10), @intdepartmentid as int) as
begin
	declare @dtfromdate as datetime
	declare @numbalance as numeric(18,2)
	
	set @dtfromdate = convert(datetime, @strfromdate)
	set @numbalance = 0.0
	if @intdepartmentid > 0 						--GOODSRETURN INCLUDED						
	select @numbalance = @numbalance + (sum(invamt) - isnull(sum(pmtamt),0))
	from vwcustomerledger
	where tdate < @dtfromdate and companyid = @intcompanyid
	and customerid = @intcustomerid and departmentid =@intdepartmentid
	group by companyid, customerid
	else									--GOODSRETURN INCLUDED
	select @numbalance = @numbalance + (sum(invamt) - isnull(sum(pmtamt),0))
	from vwcustomerledger
	where tdate < @dtfromdate and companyid = @intcompanyid
	 and customerid = @intcustomerid
	group by companyid, customerid
	select @numbalance Balance
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCustomerOpeningBalance]    Script Date: 10/06/2012 14:17:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateCustomerOpeningBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 10/12/2002
-- Modified by      	: leo
-- Comments		: v3
-- financialid hardcoded as it should be only 1
--------------------------------------------------------------------------------------------
-- Modified by		: Kishore
-- Modified on		: 13/06/2003
-- Comments		: sp corrected to take the correct opening financialid
--                        rather than taking the current financialid
--                        (On comparison with v2)
--------------------------------------------------------------------------------------------
-- Modified by		: R Harikrishnan
-- Modified on		: 04/08/2003
-- Comments		: Corrected the Actual by converting it into the Account Currency
--------------------------------------------------------------------------------------------
CREATE PROC [dbo].[spUpdateCustomerOpeningBalance]
	@intCompanyId as int,
	@intCustomerId as int
AS
--Commented for testing R Harikrishan
--set @intCompanyId=1
--set @intCustomerId =1
begin
	declare @dtfinstartdate as datetime,
		@numcustomerbalance as numeric(18,2),
		@numcustomercbalance as numeric(18,2),
		@intdepid as int,
		@intcount as int,
		@intfinid as int,
		@intdebtorid as int,
		@numamount as numeric(18,2),
		@numactualamount as numeric(18,2),
		@numdepamount as numeric(18,2),
		@intInvCustomerID as int,
		@strExRates as varchar(250),
		@strsql as nvarchar(2000),
		@debtoraccids as varchar(250)
		set @numcustomerbalance = 0.0
		set @numcustomercbalance = 0.0
		create table #temp
		(
			debtorid  int,
			amount numeric(18,2),
			depamount numeric(18,2),
			actualamount numeric(18,2)
		)
	
		set nocount on
		-- balance of respective customer
		select
			@numcustomercbalance = isnull(isnull(sum(cinvamt),0) - isnull(sum(cpmtamt),0),0),
			@numcustomerbalance = isnull(isnull(sum(invamt),0) - isnull(sum(pmtamt),0),0)
		from
			vwcustomerledger
		where
			companyid = @intcompanyid and customerid = @intcustomerid and
			financialid = 0
		-- updating the customer balance comp cur in opdr, and resp in opcr
		update acustomermaster set
			OpeningdebitBalance = @numcustomercbalance,
			Openingcreditbalance = @numcustomerbalance
		where
			companyid = @intcompanyid and customerid = @intcustomerid
		select
			@intfinid = Min(financialid)
		from
			afinancialyear
		where
			financialid > 0 -- curfinancialyear=1
		select @debtoraccids =  debtorsaccid   from asettings
		IF isnull(@debtoraccids,'''')=''''
			set @debtoraccids=''0''
		set @strsql = ''update aaccountfinyearopening set
					Openingamount= 0,
					Openingactualamount = 0, openingdepamount = 0
		where accountid in ('' + @debtoraccids +'')''
		exec sp_Executesql @strsql
					
		declare cur_cust cursor for
		select
			isnull(isnull(sum(cinvamt),0) - isnull(sum(cpmtamt),0),0),
			isnull(isnull(sum(invamt),0) - isnull(sum(pmtamt),0),0),
			isnull(isnull(sum(dinvamt),0) - isnull(sum(dpmtamt),0),0),
			departmentid, debtoraccid, CustomerID, exchangerates
		from
			vwcustomerledger
		where
			companyid = @intcompanyid and financialid = 0
		group by
			departmentid, debtoraccid,CustomerID,exchangerates
		open cur_cust
		fetch next from
			cur_cust
		into
			@numamount, @numactualamount, @numdepamount, @intdepid,
			@intdebtorid,@intInvCustomerID, @strExRates
		while @@FETCH_STATUS=0
		begin
			set @intcount = 0
			select
				@intcount=count(*)
			from
				aaccountfinyearopening
			where
				departmentid=@intdepid and accountid= @intdebtorid and
				financialid=@intfinid and companyid = @intcompanyid
			exec spConvertequiamount @intInvCustomerID, ''c'', @intdebtorid,
				''a'', @strExRates, @numactualamount, @numactualamount output,''''
			if @intcount>0
				update aaccountfinyearopening set
					Openingamount= Openingamount + @numamount,
					Openingactualamount = Openingactualamount +
					@numactualamount, openingdepamount =
					openingdepamount + @numdepamount
				where
					departmentid=@intdepid and accountid= @intdebtorid and Financialid=@intfinid
					and companyid = @intcompanyid
			else
				insert into
					aaccountfinyearopening
				values
					(@intcompanyid,	@intdebtorid, @intfinid, @intdepid,
					@numamount, @numactualamount, @numdepamount)
			--balance of all customer, assumed that the trade debtor id will be in dep currency
			insert into
				#temp
			values
				(@intdebtorid,@numamount,@numdepamount,@numactualamount)
		
			fetch next from
				cur_cust
			into
				@numamount, @numactualamount, @numdepamount, @intdepid,
				@intdebtorid,@intInvCustomerID,@strExRates
		end
		close cur_cust
		deallocate cur_cust
		-- updating the trade receivable control account
		update aaccountmaster set
			Openingamount = a.amount,
			openingdepamount = a.depamount,
			openingactualamount = a.actualamount
		from
			(select
				sum(isnull(amount,0)) amount, sum(isnull(depamount,0)) depamount,
				sum(isnull(actualamount,0)) actualamount,debtorid
			from
				#temp
			group by
				debtorid) a
		where
			companyid = @intcompanyid and accountid = debtorid
	return 0
	drop table #temp
	set nocount off
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spWeekSalesShopWise]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spWeekSalesShopWise]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--spWeekSalesShopWise ''20080101'',''20081231'',''TO'',1,0,1,''1,2,3,4''
CREATE proc [dbo].[spWeekSalesShopWise]
(
@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2),@bitshopwise as int =1,
@intDepartmentID as int,@intCompanyID as int=0 ,@strShopId as varchar(20) =''''
) as
set nocount on
begin
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@dtDateValue as datetime,
@strShopName as varchar(100),
@strWeek as varchar(23),
@intWeekDay as int,
@intShopID as int,
@intReminingDays as int,
@numTotalSales as numeric(18,2),
@numdTotalSales as numeric(18,2),
@numcTotalSales as numeric(18,2),
@strintcount as varchar(3),
@intcount as int,
@dtweekenddate as datetime,
@strShopCond as varchar(100)
declare @strSql as nvarchar(2000)
CREATE table #WeekSales
(
SlNo int,
ShopName varchar(100),
Weeks varchar(23),
TotalSales numeric(18,2),
dTotalSales numeric(18,2),
cTotalSales numeric(18,2)
)
set @intcount = 0
set @strintcount =''''
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
set @dtdatevalue = @dtfromdate
if @strShopID    <>''''
	set @strShopCond='' where shopname in (select ShopName from Ashops where shopID in (''+ @strShopId + ''))''
Else
	set @strShopCond=''''
while @dtDateValue <= @dtToDate
begin
set @intcount = @intcount + 1
set @strintcount  = @intcount
--dheena Modifies this code dd/mm/yyyy
set @strweek =convert(varchar(2),day(dateadd(d,1,@dtdatevalue)))+ ''/''+
convert(varchar(2),month(dateadd(d,1,@dtdatevalue))) + ''/'' +
convert(varchar(4),year(dateadd(d,1,@dtdatevalue)))+ '' - ''
+  convert(varchar(2),day(DateAdd(d, 7, @dtDateValue)))+''/''+
convert(varchar(2),month(DateAdd(d, 7, @dtDateValue))) +
''/''+ convert(varchar(4),year(DateAdd(d, 7, @dtDateValue)))
/* dheena comment this code
set @strweek = convert(varchar(4),year(@dtdatevalue))+ ''/''+
convert(varchar(2),month(@dtdatevalue)) + ''/'' +
convert(varchar(2),day(@dtdatevalue)) + '' - ''
+ convert(varchar(4),year(DateAdd(d, 6, @dtDateValue))) +''/''+
convert(varchar(2),month(DateAdd(d, 6, @dtDateValue))) +
''/'' + convert(varchar(2),day(DateAdd(d, 6, @dtDateValue)))*/
set @dtweekenddate = DateAdd(d, 6, @dtDateValue)
if @dtweekenddate > @dtToDate
set @dtweekenddate = @dtToDate
if @strType = ''CA''
begin
if (@bitshopwise =1)
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null and companyID=@intCompanyID
group by
ShopID
Else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null and companyID=@intCompanyID
and DepartmentId=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
end
else
begin
if @dtdatevalue  = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
and departmentid=@intDepartmentID
group by
departmentID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
departmentID
end
end
end
else if @strType = ''CR''
begin
if (@bitshopwise =1)
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
departmentID
end
end
else if @strType = ''TO''
begin
if (@bitshopwise =1)
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
and DepartmentID=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
end
else
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyid=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyid=@intCompanyID and DepartmentID=@intDepartmentID
group by
departmentID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0)),0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyID =@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0)),0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyID =@intCompanyID and departmentID=@intDepartmentID
group by
departmentID
end
end
end
open ShopCur
fetch next from
ShopCur
into
@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
while @@fetch_status <> -1
begin
if (@bitshopwise =1)
begin
select
@strShopName = ShopName
from
ashops
where
shopid = @intshopID
insert into #WeekSales values
( @intcount, @strShopName, @strweek, @numTotalSales
, @numdTotalSales, @numcTotalSales)
end
else
begin
select
@strShopName = departmentName
from
adepartmentmaster
where
departmentid = @intshopID
insert into #WeekSales values
( @intcount, @strShopName, @strweek, @numTotalSales
, @numdTotalSales, @numcTotalSales)
end
fetch next from
ShopCur
into
@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
end
close ShopCur
Deallocate ShopCur
set @dtDateValue = DateAdd(d, 7, @dtDateValue)
if @dtDateValue > @dtToDate
break
else
continue
end
set  @strSql = N''select
ShopName, Weeks, TotalSales, slno weekno ,dTotalSales,cTotalSales
from
#WeekSales '' + @strShopCond + '' order by   Slno''
print @strSql
exec sp_executesql  @strSql
end
--spMonthSalesShopWise ''20080101'',''20090101'',''TO'',1,0,''1,2''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spWeekSales]    Script Date: 10/06/2012 14:17:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spWeekSales]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Modified on   : 13/12/02
--Modified by  : leo
--Comments  : v3
----------------------------------------------
--Last Modified on  : 09/04/2003
--Modified by  : R Harikrishnan
--Comments  : Added Department ID
----------------------------------------------
--Last Modified on  : 13/03/2004
--Modified by  : A.Dheena
--Comments  : Modifed date format
--Verified by      : Hariharan
--Verified Date     : 03/05/2004 (verified From Dev Server(Fies))
------------------------------------------------------------------------------------------
-- Modified by : Bijesh.B
-- Date        : 03/07/2011
-- RefNo       : RefNo-2
-- Comments    : PD Cheque feature added
--  exec spWeekSales ''20080707'',''20080707'',''pd'',1,0,1
------------------------------------------------------------------------------------------
CREATE proc [dbo].[spWeekSales]
(
@strFromDate as varchar(10), @strToDate as varchar(10),
@strType as varchar(2),@bitshopwise as bit =1,
@intDepartmentID as int,@intCompanyID as int=0
) as
set nocount on
begin
Declare @dtFromDate as datetime,
@dtToDate as datetime,
@dtDateValue as datetime,
@strShopName as varchar(100),
@strWeek as varchar(23),
@intWeekDay as int,
@intShopID as int,
@intReminingDays as int,
@numTotalSales as numeric(18,2),
@numdTotalSales as numeric(18,2),
@numcTotalSales as numeric(18,2),
@strintcount as varchar(3),
@intcount as int,
@dtweekenddate as datetime
CREATE table #WeekSales
(
SlNo int,
ShopName varchar(100),
Weeks varchar(23),
TotalSales numeric(18,2),
dTotalSales numeric(18,2),
cTotalSales numeric(18,2)
)
set @intcount = 0
set @strintcount =''''
set @dtFromDate = convert(datetime,@strFromDate)
set @dtTodate = convert(datetime,@strToDate)
set @dtdatevalue = @dtfromdate
while @dtDateValue <= @dtToDate
begin
set @intcount = @intcount + 1
set @strintcount  = @intcount
--dheena Modifies this code dd/mm/yyyy
set @strweek =convert(varchar(2),day(dateadd(d,1,@dtdatevalue)))+ ''/''+
convert(varchar(2),month(dateadd(d,1,@dtdatevalue))) + ''/'' +
convert(varchar(4),year(dateadd(d,1,@dtdatevalue)))+ '' - ''
+  convert(varchar(2),day(DateAdd(d, 7, @dtDateValue)))+''/''+
convert(varchar(2),month(DateAdd(d, 7, @dtDateValue))) +
''/''+ convert(varchar(4),year(DateAdd(d, 7, @dtDateValue)))
/* dheena comment this code
set @strweek = convert(varchar(4),year(@dtdatevalue))+ ''/''+
convert(varchar(2),month(@dtdatevalue)) + ''/'' +
convert(varchar(2),day(@dtdatevalue)) + '' - ''
+ convert(varchar(4),year(DateAdd(d, 6, @dtDateValue))) +''/''+
convert(varchar(2),month(DateAdd(d, 6, @dtDateValue))) +
''/'' + convert(varchar(2),day(DateAdd(d, 6, @dtDateValue)))*/
set @dtweekenddate = DateAdd(d, 6, @dtDateValue)
if @dtweekenddate > @dtToDate
set @dtweekenddate = @dtToDate
if @strType = ''CA''
begin
if (@bitshopwise =1)
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null and companyID=@intCompanyID
group by
ShopID
Else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0), isnull(sum(isnull(damount,0.0)),0.0),
isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null and companyID=@intCompanyID             and DepartmentId=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
end
else
begin
if @dtdatevalue  = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
and departmentid=@intDepartmentID
group by
departmentID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 1 and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
departmentID
end
end
end
else if @strType = ''CR''
begin
if (@bitshopwise =1)
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype <> ''PD CHEQUE'' and   --RefNo-2
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
departmentID
end
end
--RefNo-2 start --------------------------------------------------------
-- PD Cheque Amount only
else if @strType = ''PD''
begin
if (@bitshopwise =1)
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0), isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
transtype = ''PD CHEQUE'' and
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and cash = 0 and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
departmentID
end
end
--Refno-2 ends  ---------------------------------------------------------
else if @strType = ''TO''
begin
if (@bitshopwise =1)
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
and DepartmentID=@intDepartmentID
group by
ShopID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
group by
ShopID
else
declare ShopCur cursor for
select
ShopID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and shopid is not null  and companyID=@intCompanyID
and departmentID=@intDepartmentID
group by
ShopID
end
end
else
begin
if @dtdatevalue = @dtfromdate
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyid=@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0.0)),0.0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyid=@intCompanyID and DepartmentID=@intDepartmentID
group by
departmentID
end
else
begin
if @intDepartmentID =0
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0)),0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyID =@intCompanyID
group by
departmentID
else
declare ShopCur cursor for
select
departmentID, isnull(sum(isnull(actamount,0)),0),
isnull(sum(isnull(damount,0.0)),0.0) , isnull(sum(isnull(camount,0.0)),0.0)
from
vwsalesanalysisbyweek
where
Billdate >= @dtDateValue  and Billdate <= @dtweekenddate
and companyID =@intCompanyID and departmentID=@intDepartmentID
group by
departmentID
end
end
end
open ShopCur
fetch next from
ShopCur
into
@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
while @@fetch_status <> -1
begin
if (@bitshopwise =1)
begin
select
@strShopName = ShopName
from
ashops
where
shopid = @intshopID
insert into #WeekSales values
( @intcount, @strShopName, @strweek, @numTotalSales
, @numdTotalSales, @numcTotalSales)
end
else
begin
select
@strShopName = departmentName
from
adepartmentmaster
where
departmentid = @intshopID
insert into #WeekSales values
( @intcount, @strShopName, @strweek, @numTotalSales
, @numdTotalSales, @numcTotalSales)
end
fetch next from
ShopCur
into
@intshopID, @numTotalSales, @numdTotalSales, @numcTotalSales
end
close ShopCur
Deallocate ShopCur
set @dtDateValue = DateAdd(d, 7, @dtDateValue)
if @dtDateValue > @dtToDate
break
else
continue
end
select
ShopName, Weeks, TotalSales, slno weekno ,dTotalSales,cTotalSales
from
#WeekSales
order by
Slno
end' 
END
GO
/****** Object:  View [dbo].[vwVendorSummaryAsDate]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSummaryAsDate]'))
EXEC dbo.sp_executesql @statement = N'
-- View
-- Modified on   : 25/12/02
-- Modified by   : Hariharan R
-- Comments   : v3
---------------------------------------------------------------------------------
-- Modified on  : 05/09/2003
-- Modified by  : Kishore
-- Comments  : Added query to take the lc payemnts
---------------------------------------------------------------------------------
-- Modified on  : 19/09/2003
-- Modified by  : Kishore
-- Comments  : Replaced pddAmount with pddCustomerAmount in Lc
-----------------------------------------------------------------------------------
-- Modified on  : 28/05/2008
-- Modified by  : Shinu
-- Comments  : Added "" and  vw.Type<>''REC'' ""  to First Select Statement.Because Receipts cannot be consider as Billed
-----------------------------------------------------------------------------------
--RefNo-01
-- Modified on  : 27/10/2010
-- Modified by  : VinothMurugan V
-- Comments  : adding Confirmed bit
-----------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwVendorSummaryAsDate] AS
select v.CompanyID, v.vendorid, vw.departmentid, v.currencyid,
vw.billdate tdate, 0 as opening, 0 as advance,
isnull(sum(vw.billAmount),0) as billed, 0 as settled, 0 as paid
from vwtotalbillpaidamount vw, avendormaster v
where  v.CompanyID = vw.CompanyID
and v.vendorid = vw.vendorid   and  vw.Type<>''REC''
group by v.companyid, v.vendorid, vw.departmentid, v.currencyid, vw.billdate
union all
-- advance paid
select v.companyid, v.vendorid, ph.phdepartmentid,
v.currencyid,phpaymentdate,  0 as opening,
isnull(sum(phcustomeramount),0) as advance,
0 as billed, 0 as settled, 0 as paid
from aHqPaymentVoucherHeader ph, avendormaster v, vwadvancepaidpayments vwap
where ph.phpaymentid = vwap.paymentid
and ph.phcompanyid = vwap.companyid
and ph.phcancelled = 0
and ph.phcompanyid = v.companyid
and ph.phvendorid = v.vendorid  and ph.phConfirmed =1 --RefNo-01
group by v.companyid, v.vendorid, ph.phdepartmentid, v.currencyid, phpaymentdate
union all
-- deducting the advance payments used in settlements
select v.companyid, v.vendorid, vsh.departmentid, v.currencyid, vsh.vsdate, 0 as opening,
- isnull(sum(settlementamount),0) as advance, 0 as invoiced,
0 as settled, 0 as paid
from vendorsettlementheader vsh, avendormaster v, vendorsettlementdetail vsd
where vsh.vsid = vsd.vsid
and vsh.companyid = vsd.companyid
and vsh.cancelled = 0
and vsh.companyid = v.companyid
and vsh.vendorid = v.vendorid
and vsh.paymentid is not null
group by v.companyid, v.vendorid ,vsh.departmentid, v.currencyid, vsdate
union all
-- considering the debit notes as advance
select v.CompanyID, v.vendorid, dc.dcndepartmentid,
v.currencyid, dc.dcndate, 0 as opening,
isnull(sum(DCNAmount),0) as advance, 0 as billed, 0 as settled, 0 as paid
from debitcreditnote dc, avendormaster v
where dc.dcnCompanyID = v.CompanyID
and dc.dcncancelled = 0
and v.vendorid = dc.dcnvendorid
and dc.dcndebit = 1  and dc.DCNConfirmed = 1 --RefNo-01
group by v.companyid, v.vendorid, dc.dcndepartmentid, v.currencyid, dc.dcndate
union all
-- deducting the advance payments used in settlements
select v.companyid, v.vendorid, vsh.departmentid, v.currencyid, vsh.vsdate, 0 as opening,
- isnull(sum(settlementamount),0) as advance, 0 as invoiced,
0 as settled, 0 as paid
from vendorsettlementheader vsh, avendormaster v, vendorsettlementdetail vsd
where vsh.vsid = vsd.vsid
and vsh.companyid = vsd.companyid
and vsh.cancelled = 0
and vsh.companyid = v.companyid
and vsh.vendorid = v.vendorid
and vsh.dcnid is not null
group by v.companyid, v.vendorid ,vsh.departmentid,  v.currencyid, vsh.vsdate
union all
-- considering the debit notes as advance
select v.CompanyID, v.vendorid, dc.losdcndepartmentid, v.currencyid,
dc.losdcndate, 0 as opening,
isnull(sum(losDCNAmount),0) as advance, 0 as billed, 0 as settled, 0 as paid
from losdebitcreditnote dc, avendormaster v
where dc.losdcnCompanyID = v.CompanyID
and dc.losdcncancelled =0
and v.vendorid = dc.losdcnvendorid and dc.losdcndebit = 1
group by v.companyid, v.vendorid, dc.losdcndepartmentid, v.currencyid, dc.losdcndate
union all
-- deducting the advance payments used in settlements
select v.companyid, v.vendorid, vsh.departmentid, v.currencyid, vsh.vsdate, 0 as opening,
- isnull(sum(settlementamount),0) as advance, 0 as invoiced, 0 as settled, 0 as paid
from vendorsettlementheader vsh, avendormaster v, vendorsettlementdetail vsd
where vsh.vsid = vsd.vsid and vsh.companyid = vsd.companyid and
vsh.cancelled = 0 and vsh.companyid = v.companyid and vsh.vendorid = v.vendorid
and vsh.losdcnid is not null
group by v.companyid, v.vendorid ,vsh.departmentid,  v.currencyid, vsh.vsdate
union all
-- payments bill settled
select v.companyid, v.vendorid, ph.phdepartmentid, v.currencyid, ph.phpaymentdate,
0 as opening, 0 as advance, 0 as billed,
isnull(sum(pd.pdpaidamount),0) as settled, 0 as paid
from aHqPaymentVoucherHeader ph, avendormaster v, ahqpaymentvoucherdetails pd
where ph.phpaymentid = pd.pdpaymentid and ph.phcompanyid = pd.pdcompanyid and
ph.phcancelled = 0 and ph.phcompanyid = v.companyid and ph.phvendorid = v.vendorid
and ph.phConfirmed = 1 --RefNo-01
group by v.companyid, v.vendorid, ph.phdepartmentid, v.currencyid, ph.phpaymentdate
Union All
-- take LC
select pdd.pddCompanyId CompanyId, phVendorId, ph.phDepartmentId DepartmentId,
CurrencyId, ph.phpaymentdate, 0 Opening, 0 Advance, 0 Billed,
isnull(sum(pdd.pddCustomerAmount), 0) as Settled, 0 as Paid
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
lospPurchaseBillHeader b, aVendorMaster v, MiscSettings s
where pdd.pddPaymentID = ph.phPaymentID
and pdd.pddCompanyId = ph.phCompanyId
and pdd.pddHqPoId = b.pbhPoid
and ph.phVendorId = v.VendorId
and ph.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0 and  ph.phConfirmed = 1  --RefNo-01
and ph.phLcPayment in (''LCM'', ''LCO'')
group by pdd.pddCompanyId, phVendorId, ph.phdepartmentid,
v.currencyid, ph.phpaymentdate
union all
-- settled via vendor settlement
select v.companyid, v.vendorid, vsh.departmentid, v.currencyid,
vsh.vsdate, 0 as opening, 0 as advance, 0 as invoiced,
isnull(sum(vsd.settlementamount),0) as settled, 0 as paid
from vendorsettlementheader vsh, avendormaster v, vendorsettlementdetail vsd
where vsh.vsid = vsd.vsid and vsh.companyid = vsd.companyid and
vsh.cancelled = 0 and vsh.companyid = v.companyid and vsh.vendorid = v.vendorid
group by v.companyid, v.vendorid , vsh.departmentid, v.currencyid, vsh.vsdate
union all
-- receipt from suppliers
select v.companyid, v.vendorid, rh.departmentid, v.currencyid,
rh.receiptdate, 0 as opening, 0 as advance, 0 as billed,
0 as settled, isnull(sum(customeramount),0) as paid
from receiptvoucherheader rh, avendormaster v
where rh.companyid = v.companyid
and rh.cancelled = 0
and rh.vendorid = v.vendorid  and rh.Confirmed = 1  --RefNo-01
group by v.companyid, v.vendorid, rh.departmentid, v.currencyid, rh.receiptdate
union all
-- FOR REXPORTING DETAILS DONE FOR VENDOR TO CONSIDER AS ADVANCE - hari 021225
select rehcompanyid, rehvendorid, rehdepartmentid, currencyid, rehexportdate,
0 opening, rehexportamount - settled advance, 0 billed, 0 settled, 0 paid
from vwreexportvendorsettle'
GO
/****** Object:  View [dbo].[vwVendorSummary]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwVendorSummary]'))
EXEC dbo.sp_executesql @statement = N'
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Last Modified on 	: 10/12/02
-- Modified by 		: leo
-- Comments 		: v3
-----------------------------------------------------------------------
-- Modified by		: Kishore
-- Modified on		: 06/09/2003
-- Comments		: Added query to take LC Payment entries
-----------------------------------------------------------------------
CREATE VIEW [dbo].[vwVendorSummary] AS
--opening
select companyid, vendorid, currencyid,
case when (openingdebitbalance is not null) then -openingdebitbalance
when (openingcreditbalance is not null) then openingcreditbalance
else 0 end as opening, 0 as advance, 0 as billed, 0 as settled, 0 as paid
from avendormaster
union all
-- advance paid
select v.companyid, v.vendorid, v.currencyid, 0 as opening, isnull(sum(phamount),0) as advance,
0 as billed, 0 as settled, 0 as paid from
ahqpaymentvoucherheader ph, avendormaster v, vwadvancepaidpayments vwap where
ph.phpaymentid = vwap.paymentid and ph.phcompanyid = vwap.companyid and
ph.phcancelled = 0 and ph.phcompanyid = v.companyid and ph.phvendorid = v.vendorid
group by v.companyid, v.vendorid, v.currencyid
union all
--billed total
select v.CompanyID, v.vendorid, v.currencyid, 0 as opening, 0 as advance,
isnull(sum(vw.billAmount),0) as billed, 0 as settled, 0 as paid  from vwtotalbillpaidamount vw,
avendormaster v where  v.CompanyID = vw.CompanyID and v.vendorid = vw.vendorid
group by v.companyid, v.vendorid, v.currencyid
union all
-- payments bill settled
select v.companyid, v.vendorid, v.currencyid, 0 as opening, 0 as advance, 0 as billed,
isnull(sum(pd.pdpaidamount),0) as settled, 0 as paid
from ahqpaymentvoucherheader ph, avendormaster v, ahqpaymentvoucherdetails pd
where ph.phpaymentid = pd.pdpaymentid
and ph.phcompanyid = pd.pdcompanyid
and ph.phcancelled = 0
and ph.phcompanyid = v.companyid
and ph.phvendorid = v.vendorid
group by v.companyid, v.vendorid, v.currencyid
Union All
-- Take LC Payments
select v.Companyid, v.VendorId, v.CurrencyId,
0 as Opening, 0 as Advance, 0 as Billed,
isnull(sum(pdd.pddAmount),0) as settled, 0 as paid
from aHQPaymentVoucherDebitDetails pdd, aHQPaymentVoucherHeader ph,
lospPurchaseBillHeader b, MiscSettings s, aVendorMaster v
Where pdd.pddPaymentID = ph.phPaymentID
and pdd.pddCompanyId = ph.phCompanyId
and pdd.pddHqPoId = b.pbhPoid
and b.pbhVendorId = v.VendorId
and ph.phCancelled = 0
and b.pbhBillId is not null
and s.LcToAccount = 0
and ph.phLcPayment in (''LCM'', ''LCO'')
group by v.companyid, v.vendorid, v.currencyid
union all
-- settled via vendor settlement
select v.companyid, v.vendorid, v.currencyid, 0 as opening, 0 as advance, 0 as invoiced,
isnull(sum(vsd.settlementamount),0) as settled, 0 as paid from
vendorsettlementheader vsh, avendormaster v, vendorsettlementdetail vsd where
vsh.vsid = vsd.vsid and vsh.companyid = vsd.companyid and
vsh.cancelled = 0 and vsh.companyid = v.companyid and vsh.vendorid = v.vendorid
group by v.companyid, v.vendorid , v.currencyid
union all
--credited through credit note
select v.CompanyID, v.vendorid, v.currencyid, 0 as opening, 0 as advance,
isnull(sum(DCNAmount),0) as billed, 0 as settled, 0 as paid  from debitcreditnote dc,
avendormaster v where dc.dcnCompanyID = v.CompanyID and dc.dcncancelled =0
and v.vendorid = dc.dcnvendorid and dc.dcndebit = 0
group by v.companyid, v.vendorid, v.currencyid
union all
-- payments through debit note
select v.CompanyID, v.vendorid, v.currencyid, 0 as opening, 0 as advance,
0 as billed, isnull(sum(DCNAmount),0) as settled, 0 as paid
from debitcreditnote dc, avendormaster v
where dc.dcnCompanyID = v.CompanyID
and dc.dcncancelled =0
and v.vendorid = dc.dcnvendorid
and dc.dcndebit = 1
group by v.companyid, v.vendorid, v.currencyid
union all
-- receipt from suppliers
select v.companyid, v.vendorid, v.currencyid, 0 as opening, 0 as advance, 0 as billed,
0 as settled, isnull(sum(amount),0) as paid from receiptvoucherheader rh, avendormaster v
where rh.companyid = v.companyid
and rh.cancelled = 0
and rh.vendorid = v.vendorid
group by v.companyid, v.vendorid, v.currencyid'
GO
/****** Object:  View [dbo].[vwPandCInquiryGodownStock]    Script Date: 10/06/2012 14:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPandCInquiryGodownStock]'))
EXEC dbo.sp_executesql @statement = N'
-- Created On : 09/06/2006
-- Created By : Aneesh
Create View [dbo].[vwPandCInquiryGodownStock] As
Select gsitemid,sum(gsstock) As Totalstock,gsGodownid,godownname
From vwInquiryGodownStock g, agodown a
Where g.gsgodownid=a.godownid
GROUP BY gsgodownid,godownname,gsitemid'
GO
/****** Object:  View [dbo].[vwgodownwisevalue]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwgodownwisevalue]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwgodownwisevalue    Script Date: 18/01/2003 9:45:41 PM ******/
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwgodownwisevalue] as
select "All Godowns" gvalue, godownname, S.gsgodownid ,s.gsitemid, vw.itemdescription,
a.itemdescription itemdesc, convert(numeric(18,3), sum(isnull(s.gsstock,0))) stock,
itemrate cost, convert(numeric(18,2), sum(isnull(s.gsstock,0))*itemrate) as stockvalue,
0.0 salesprice, 0.0 wholesaleprice, 0.0 discountprice, vw.code from vwinquirygodownstock s
left outer join vwitemdescription vw on s.gsitemid=vw.itemid
left outer join aitem a on s.gsitemid=a.itemid, agodown gd
where gd.godownid=gsgodownid group by godownname, s.gsgodownid, vw.itemdescription,
s.gsitemid, a.itemdescription, vw.code, itemrate having sum(isnull(s.gsstock,0.0))>0.0'
GO
/****** Object:  StoredProcedure [dbo].[spIssueStockBlock]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spIssueStockBlock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--modified By   : Hariharan
--Modified Date : 17/10/2002, 19/11/2003
--replaced moigodownstock with vwinquirygodownstock
--modified removing the gslocationid, indlocationid --joins as locationid on stock table
--Verified By  : Hariharan
--Verified Date : 30/04/2004(updated from Devl Db)
--have no relevance in v3
-----------------------------------------------------------------------
--RefNo-1
--Updated By : Yogesh Joe
--Updated On : 25-01-2010
--modification : Added the condition inh.inhCancelled=0
--Purpose : To avoid the cancelled issue note.
-----------------------------------------------------------------------
CREATE proc [dbo].[spIssueStockBlock] (@issuenotemainid int,@intgodownid int, @intLocationid int,
@intItemid int) as
begin
set nocount on
select gsgodownid, gslocationid, gsshipmentid, gsitemid, gsstock, gsbadstock from
(select gsgodownid, gslocationid, gsshipmentid, gsitemid,
(gsstock - isnull(tb.issuedgood,0)) gsstock ,
(gsbadstock - isnull(tb.issuedbad,0)) gsbadstock from vwinquirygodownstock gs left outer join
(select ind.indgodownid,ind.indlocationid, ind.inditemid,
ind.indshipmentid, isnull(sum(ind.indqty),0) as issuedgood,
isnull(sum(ind.indbadqty),0) as issuedbad from ahqissuenotedetail ind,ahqIssueNoteHeader inh ,
ahqIssuenoteMain inm where ind.indissuenoteid=inh.inhissuenoteid and
ind.indgodownid=inh.inhgodownid and inh.inhissuenotemainid=inm.inmissuenoteid and
inm.inmCancel=0 and inh.inhused=0  and inh.inhissuenotemainid <> @issuenotemainid  and inh.inhCancelled=0--RefNo-1
group by ind.indgodownid,ind.indlocationid, ind.indshipmentid,
ind.inditemid) tb
on gs.gsgodownid = tb.indgodownid
and gs.gsshipmentid = tb.indshipmentid and gs.gsitemid = tb.inditemid where
gsgodownid=@intgodownid and gsitemid=@intItemid) one
where gsstock >0 or gsbadstock >0  order by gsshipmentid
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spgetgodownstockasondate]    Script Date: 10/06/2012 14:17:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spgetgodownstockasondate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spgetgodownstockasondate    Script Date: 18/01/2003 9:45:44 PM ******/
/****** Object:  Stored Procedure dbo.spgetgodownstockasondate    Script Date: 03/10/2002 5:07:00 PM ******/
/****** Object:  Stored Procedure dbo.spgetgodownstockasondate    Script Date: 14/09/2002 12:48:18 AM ******/
/****** Object:  Stored Procedure dbo.spgetgodownstockasondate    Script Date: 31/07/2002 2:00:39 PM ******/
CREATE proc [dbo].[spgetgodownstockasondate] @strdate as varchar(11),@intgodownid int as
begin
	declare @openingstock as numeric(18,3),@itemid int,
	@curstock as numeric(18,3)
	
	create table #temp (
	itemid int,
	godownid int,
	stockdate datetime,
	openingstock numeric(18,3),
	closingstock numeric(18,3)
	)
	set nocount on
	declare cur_stock cursor for
	select distinct gsitemid from moigodownstock where gsgodownid=@intgodownid --and gsitemid=8195
	open cur_stock
	fetch next from cur_stock into @itemid
	while @@fetch_status=0
	begin
		set @openingstock=1
		exec spopeningstockondate @itemid , @strdate , @intgodownid , @openingstock output
		select @curstock=isnull(sum(isnull(transqty,0)*mode),0) from vwgdnbincard where
		GDate=@strdate and
		godownid=@intgodownid and itemid=@itemid
		--print @curstock
		insert into #temp values(@itemid,@intgodownid,@strdate,@openingstock,
		@openingstock+@curstock)
		fetch next from cur_stock into @itemid
	end
	close cur_stock
	deallocate cur_stock
	select * from #temp
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDayendReportBackupAsOn07062011]    Script Date: 10/06/2012 14:17: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].[spDayendReportBackupAsOn07062011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--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.
-------------------------------------
CREATE proc [dbo].[spDayendReportBackupAsOn07062011](@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
union all
select drcompanyid, drshopid, customername, drchequeno refereneceno, drdate, drAmount amount,
drAmount * drdepexrate damount, drAmount * drexchangerate  camount,
3 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,
5 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,
6 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,
7 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,
8 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, 9 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,
10 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
select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, Amount,
dAmount, cAmount, 11 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, 12 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
--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
select lh.GrnCompanyID,lh.grnhShopid,CustomerName,lh.GrnhGoodsreturnnoteNO reference,
lh.GrnhGoodsreturnnoteDate, vw.goodsreturnamt amount, vw.goodsreturnamt* grnhdepexrate damount,
vw.goodsreturnamt*grnhexchangerate camount,14 as type, ''Goods Return'' as Trans, 0.0 as mode,
0.0 as dmode, 0.0 as cmode, 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,
15 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
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 ,''''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_Sonee]    Script Date: 10/06/2012 14:17: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].[spDayendReport_Sonee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--Last Modified by      : Bijesh.B as on 22/03/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
CREATE proc [dbo].[spDayendReport_Sonee](@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 , '''' accountdesc, '''',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
UNION ALL
--RefNo-1
--FOR PD Cheque Total Amount
select cs.companyid , cs.shopid, accountdesc, ''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.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
union all
select drcompanyid, drshopid, customername, drchequeno refereneceno, drdate, drAmount amount,
drAmount * drdepexrate damount, drAmount * drexchangerate  camount,
4 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
--added to show  the labels after the groups
select s.companyid, s.shopid, '''' accountdesc, '''', billdate, 0.0 amount, 0.0 damount, 0.0 camount,
5 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,
6 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,
7 as type, ''Payments Deducted'' 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, 8 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,
9 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
select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, Amount,
dAmount, cAmount, 10 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
union all
select lh.GrnCompanyID,lh.grnhShopid,CustomerName,lh.GrnhGoodsreturnnoteNO reference,
lh.GrnhGoodsreturnnoteDate, vw.goodsreturnamt amount, vw.goodsreturnamt* grnhdepexrate damount,
vw.goodsreturnamt*grnhexchangerate camount, 11 as type, ''Goods Return'' as Trans, 0.0 as mode,
0.0 as dmode, 0.0 as cmode, 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,
12 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
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 ,''''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_BackupAsOn_22032011]    Script Date: 10/06/2012 14:17: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].[spDayendReport_BackupAsOn_22032011]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--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.
-------------------------------------
CREATE proc [dbo].[spDayendReport_BackupAsOn_22032011](@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
union all
select drcompanyid, drshopid, customername, drchequeno refereneceno, drdate, drAmount amount,
drAmount * drdepexrate damount, drAmount * drexchangerate  camount,
3 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,
5 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,
6 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,
7 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,
8 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, 9 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,
10 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
select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, Amount,
dAmount, cAmount, 11 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, 12 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
--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
select lh.GrnCompanyID,lh.grnhShopid,CustomerName,lh.GrnhGoodsreturnnoteNO reference,
lh.GrnhGoodsreturnnoteDate, vw.goodsreturnamt amount, vw.goodsreturnamt* grnhdepexrate damount,
vw.goodsreturnamt*grnhexchangerate camount,14 as type, ''Goods Return'' as Trans, 0.0 as mode,
0.0 as dmode, 0.0 as cmode, 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,
15 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
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 ,''''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport]    Script Date: 10/06/2012 14:17: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].[spDayendReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--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 ,''''' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDepUsed]    Script Date: 10/06/2012 14:17:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDepUsed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spDepUsed    Script Date: 18/01/2003 9:45:49 PM ******/
--Created by 	: Hariharan
--Created date	: 19/12/2002
--This sp is written to check the usage of department in the system
--to decide whether to allow the edition of currency provided there is
--no subgroups
CREATE procedure [dbo].[spDepUsed] @intdepid as int,@intcompanyid as int
as
begin
	set nocount on
	select isnull(count(*),0) from
	(select departmentid  from ashops
	where companyid = @intcompanyid and departmentid= @intdepid
	union all
	select departmentid  from aGodown	
	where companyid = @intcompanyid and departmentid= @intdepid
	union all
	select daDepartmentID from aDeptAccounts  g where daDepartmentID = @intdepid and
	daCompanyID= @intcompanyid
	Union All
	select distinct departmentid from vwcustomerledger where
	departmentid = @intDepID and companyid = @intCompanyID
	Union All
	select distinct departmentid from vwsupplierledger where
	departmentid = @intDepID and companyid = @intCompanyID
	Union All
	select distinct departmentid from contra where departmentid =@intDepid
	and companyid = @intCompanyID
	Union All
	select distinct departmentid from forex where departmentid =@intDepid
	and companyid = @intCOmpanyid) DEPUSED
	set nocount OFF
end' 
END
GO
/****** Object:  View [dbo].[vwGdnInventoryValue]    Script Date: 10/06/2012 14:17:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwGdnInventoryValue]'))
EXEC dbo.sp_executesql @statement = N'
--Last Modified on 	: 12/12/02
--Modified by		: leo
--Comments		: v3
--------------------------------------------------------------------------------
-- Modified by          : Kishore
-- Modified on          : 11/06/2003
-- Comments             : Removed vwItemShipmentDetailPu and used
--                        losShopItemShipmentDetail instead
--                        (On comparison with v2)
--------------------------------------------------------------------------------
CREATE  VIEW [dbo].[vwGdnInventoryValue] AS
select S.gsgodownid ,s.gsitemid, vw.itemdescription, a.itemdescription itemdesc,
convert(numeric(18,3), sum(isnull(s.gsstock,0.0))) stock, itemrate cost,
sum(isnull(s.gsstock,0.0))*itemrate as stockvalue, max(sp.salesprice) salesprice,
max(sp.wholesaleprice) wholesaleprice, max(sp.discountprice) discountprice,vw.vunitcode unitcode
from vwinquirygodownstock s
left outer join (select itemid, max(Sellingprice) salesprice,
		max(wholesaleprice) wholesaleprice, max(discountprice) discountprice
		from losShopItemShipmentDetail
		group by ItemId) sp on
s.gsitemid = sp.itemid
left outer join vwitemdescription vw on s.gsitemid = vw.itemid
left outer join aitem a on s.gsitemid = a.itemid
group by vw.ItemDescription, s.gsItemId, a.ItemDescription, s.gsGodownId,
itemrate ,vw.vunitcode
having sum(isnull(s.gsStock, 0.0)) > 0'
GO
/****** Object:  View [dbo].[vwtotalinventory]    Script Date: 10/06/2012 14:17:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwtotalinventory]'))
EXEC dbo.sp_executesql @statement = N'
/****** Object:  View dbo.vwtotalinventory    Script Date: 18/01/2003 9:45:42 PM ******/
--Last Modified on 	: 09/12/02
--Modified by		: leo
--Comments		: v3
CREATE view [dbo].[vwtotalinventory] as
select itemid, itemdescription, itemdesc , sum(stock) stock, cost, sum(stock) * cost stockvalue,
max(salesprice) salesprice , sum(stock) * max(salesprice) salevalue
, max(wholesaleprice) wholesaleprice, max(discountprice) discountprice
from
(select itemid, itemdescription, itemdesc,  stock, cost, salesprice, wholesaleprice, discountprice
from vwshopinventoryvalue
union all
select gsitemid, itemdescription, itemdesc, stock, cost,  salesprice, wholesaleprice, discountprice
from vwgdninventoryvalue) stockcombined
group by  stockcombined.itemdescription, stockcombined.itemid, stockcombined.itemdesc,
stockcombined.cost
having sum(stock)>0'
GO
/****** Object:  StoredProcedure [dbo].[spTotalInventory]    Script Date: 10/06/2012 14:17:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spTotalInventory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
--Modified on   : 13/12/02
--Modified by  : leo
--Comments  : v3
-------------------------------------------
-- Modified on          : 07/06/2033,. 26/04/2004, 29/04/2004
-- Modified by          : Kishore, Hariharan R
-- Comments             : Added the @intCompanyId, @intDepartmentId, @intShopId and @intGodownId
--                        parameters. Now the sp shows amounts in department currency,
--     if department is not zero. Otherwise it shows in inventory currency
--                        Also, this sp can be used for godown, inventory and company inventory values
--                        To get company wise values, give godownid and shopid zero
--   : To department wise data filteration in case of departmentid >0
-- modified by   : venkitesh 06/07/04
-- comments  : added unitcode
-- comments  : Prasanth Joseph
--             While taking selling price, grouping has some problem, So showing stock
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[spTotalInventory] (@intCompanyId as Int, @intDepartmentId as Int,
@intShopId as int, @intGodownId as int) AS
begin
Declare @intDepCurrency as int
Declare @intInvCurrency as int
Declare @numExchangeRate as Numeric(18, 8)
--as it was not allowing to keep more tables in query
-- it is decided to keep temporary table
-- get the inventory currency id
select @intInvCurrency = currencyid from aAccountMaster
where AccountId = (select InventoryID from aPackageSettings)
and CompanyId = @intCompanyId
Set @numExchangeRate = 0
-- if department id is not 0
If @intDepartmentId <> 0
Begin
-- get the department currency
Select @intDepCurrency = DepCurrencyId from aDepartmentMaster
Where DepartmentId = @intDepartmentId
And CompanyId = @intCompanyId
-- get the exchange rate
Exec spGetExchangeRate @intCompanyId, @intInvCurrency, @intDepCurrency,
@numExchangeRate OUTPUT
End
Else
Begin
-- get the department currency
Select @intDepCurrency = CurrencyId from aCompanyMaster
Where CompanyId = @intCompanyId
-- get the exchange rate
Exec spGetExchangeRate @intCompanyId, @intInvCurrency, @intDepCurrency,
@numExchangeRate OUTPUT
End
If @intShopId <> 0
Begin
select distinct(s.itemid) ItemId, S.ShopId, 0 GodownId, vw.ItemDescription,
a.Itemdescription ItemDesc,
convert(numeric(18,3), sum(isnull(s.stock,0))) Stock,
convert(numeric(18,8),itemrate * @numExchangeRate) Cost,
convert(numeric(18,2),sum(isnull(s.stock,0)) * itemrate * @numExchangeRate) as StockValue,
avg(isnull(sd.sellingprice,0)  * @numExchangeRate) SalesPrice,
avg(isnull(sd.sellingprice,0)) * sum(isnull(s.stock,0) * @numExchangeRate) SaleValue,
isnull(sd.wholesaleprice, 0) * @numExchangeRate WholeSalePrice,
isnull(sd.discountprice,0) * @numExchangeRate DiscountPrice,
Min(ac.CategoryNameDescription) CategoryNameDescription,
Convert(VarChar(200), Min(aColor.ColorName)) ColorName,
Min(aSize.SizeName) SizeName,
Min(a.ItemCode) ItemCode,
Min(Convert(int, Active)) Active,
Min(a.Brand) Brand,
Min(a.ItemCategoryId) ItemCategoryId,
Min(a.dId) dId,vw.vunitcode unitcode
from vwinquiryshopstock s
left outer join vwitemdescription vw on s.itemid = vw.itemid
left outer join aitem a on s.itemid = a.itemid
Left Outer Join aColor On a.ColorId = aColor.ColorId
Left Outer Join aSize On a.SizeId = aSize.SizeId
left outer join vwshopitemshipmentdetailPU sd
on s.itemid = sd.itemid
and s.shopid = sd.shopid
and currencyid = @intInvCurrency, aItemCategory ac
Where s.ShopId = @intShopId
And a.ItemCategoryId = ac.ItemCategoryId
group by vw.itemdescription, s.itemid, a.itemdescription,
s.shopid, itemrate, sd.sellingprice,
sd.wholesaleprice, sd.discountprice ,vw.vunitcode
having sum(isnull(s.stock,0)) <> 0
End
Else If @intGodownId <> 0
Begin
select s.gsitemid ItemId, 0 ShopId, s.gsGodownId GodownId, vw.ItemDescription,
a.itemdescription ItemDesc,
convert(numeric(18,3), sum(isnull(s.gsstock,0.0))) Stock,
convert(numeric(18,2),itemrate * @numExchangeRate) Cost,
convert(numeric(18,2), sum(isnull(s.gsstock,0.0)) * itemrate * @numExchangeRate) as StockValue,
max(sp.salesprice) * @numExchangeRate SalesPrice,
0 SaleValue,
max(sp.wholesaleprice) * @numExchangeRate WholeSalePrice,
max(sp.discountprice) * @numExchangeRate DiscountPrice,
Max(ac.CategoryNameDescription) CategoryNameDescription,
Convert(VarChar(200), Max(aColor.ColorName)) ColorName,
Max(aSize.SizeName) SizeName,
Max(a.ItemCode) ItemCode,
Max(Convert(int, Active)) Active,
Max(Brand) Brand,
Max(a.ItemCategoryId) ItemCategoryId,
Max(dId) dId ,vw.vunitcode unitcode
from vwInquiryGodownStock s left outer join (select itemid,
max(Sellingprice) salesprice,
max(wholesaleprice) wholesaleprice,
max(discountprice) discountprice
from vwshopitemshipmentdetailpu
where currencyid = @intInvCurrency
group by itemid) sp
on s.gsitemid = sp.itemid
left outer join vwitemdescription vw on s.gsitemid = vw.itemid
left outer join aitem a on s.gsitemid = a.itemid
Left Outer Join aColor On a.ColorId = aColor.ColorId
Left Outer Join aSize On a.SizeId = aSize.SizeId, aItemCategory ac
Where gsGodownId = @intGodownId
And a.ItemCategoryId = ac.ItemCategoryId
group by vw.itemdescription, s.gsitemid, a.itemdescription,
s.gsgodownid, itemrate ,vw.vunitcode
having sum(isnull(s.gsstock,0.0)) <> 0
End
Else -- shop id and godown id are zero, then return company report
Begin
-- create the temporary table
create table #invValue
(itemid  int,
itemdescription varchar(250),
itemdesc varchar(250),
stock numeric(18,3),
cost numeric(28,2),
salesprice numeric(18,2),
wholesaleprice numeric(18,2),
discountprice numeric(18,2),
unitcode varchar(50))
if @intDepartmentId = 0
Begin
-- insert values into the temporary table
insert into #invValue
select ItemId, ItemDescription, ItemDesc,
convert(numeric(18,3), stock) Stock,
convert(numeric(18,2), cost * @numExchangeRate) Cost,
salesprice * @numExchangeRate SalesPrice,
wholesaleprice * @numExchangeRate WholeSalePrice,
discountprice * @numExchangeRate DiscountPrice,unitcode
from vwshopinventoryvalue
union all
select gsitemid, itemdescription, itemdesc,
convert(numeric(18,3), stock) stock,
convert(numeric(18,2), cost * @numExchangeRate) Cost,
salesprice * @numExchangeRate SalesPrice,
wholesaleprice * @numExchangeRate WholeSalePrice,
discountprice * @numExchangeRate DiscountPrice ,unitcode
from vwgdninventoryvalue
union all
select a.itemid, vw.itemdescription, a.itemdescription,
convert(numeric(18,3), sum(isnull(transqty,0))),
convert(numeric(18,2),a.itemrate * @numExchangeRate) Cost,
min(isnull(sellingprice,0)) * @numExchangeRate SellingPrice,
min(isnull(wholesaleprice,0)) * @numExchangeRate WholeSalePrice,
min(isnull(discountprice,0)) * @numExchangeRate DiscountPrice,vw.vunitcode unitcode
from vwquantityunprocessed qup, vwitemdescription vw,aitem a left outer join
(select itemid,currencyid,min(sellingprice)sellingprice,min(wholesaleprice)wholesaleprice,min(discountprice)discountprice from
vwshopitemshipmentdetailpu group by itemid,currencyid ) spu on a.itemid = spu.itemid
and currencyid = @intInvCurrency
where qup.itemid = a.itemid and
a.itemid = vw.itemid
group by a.itemid, vw.itemdescription, a.itemdescription, a.itemrate,vw.vunitcode
End
Else
Begin
-- insert values into the temporary table
insert into #invValue
select ItemId, ItemDescription, ItemDesc,
convert(numeric(18,3), stock) Stock,
convert(numeric(18,2), cost) Cost,
salesprice * @numExchangeRate SalesPrice,
wholesaleprice * @numExchangeRate WholeSalePrice,
discountprice * @numExchangeRate DiscountPrice,unitcode
from  vwshopinventoryvalue v, ashops s where
v.shopid = s.shopid and s.departmentId = @intDepartmentId
union all
select gsitemid, itemdescription, itemdesc,
convert(numeric(18,3), stock) stock,
convert(numeric(18,2), cost) Cost,
salesprice * @numExchangeRate SalesPrice,
wholesaleprice * @numExchangeRate WholeSalePrice,
discountprice * @numExchangeRate DiscountPrice,unitcode
from vwgdninventoryvalue v, aGodown G where
v.gsgodownid = g.Godownid and g.departmentId = @intDepartmentId
union all
select a.itemid, vw.itemdescription, a.itemdescription,
convert(numeric(18,3), sum(isnull(transqty,0))),
convert(numeric(18,2),a.itemrate) Cost,
min(isnull(sellingprice,0)) * @numExchangeRate SellingPrice,
min(isnull(wholesaleprice,0)) * @numExchangeRate WholeSalePrice,
min(isnull(discountprice,0)) * @numExchangeRate DiscountPrice,
au.unitcode
from vwquantityunprocessed qup Left outer join aShopS s on
qup.LocationId = s.ShopID AND qup.LocationType =''s''
Left outer join aGodown G on qup.LocationId = g.GodownId and
Qup.LocationType=''g'', vwitemdescription vw, aunit au , aitem a
left outer join
vwshopitemshipmentdetailpu spu on a.itemid = spu.itemid
and currencyid = @intInvCurrency
where qup.itemid = a.itemid and
a.itemid = vw.itemid and
isnull(s.Departmentid, g.Departmentid) = @intDepartMentId
and a.unitsid = au.UnitID
group by a.itemid, vw.itemdescription, a.itemdescription,
a.itemrate, au.unitcode
End
-- select (return) the values from temporary tables
select StockCombined.ItemId, 0 ShopId, 0 GodownId,
StockCombined.ItemDescription,
StockCombined.ItemDesc ,
convert(numeric(18,3), sum(isnull(stock,0))) Stock, Cost* @numExchangeRate,
convert(numeric(28,2), sum(isnull(stock,0) * cost * @numExchangeRate)) StockValue,
max(isnull(salesprice, 0)) SalesPrice ,
convert(numeric(18,2),
sum(isnull(stock,0)) * max(isnull(salesprice,0))) SaleValue,
max(isnull(wholesaleprice,0)) WholeSalePrice,
max(isnull(discountprice,0)) DiscountPrice,
CategoryNameDescription, Convert(VarChar(200), isnull(colorname, '''')) ColorName,
isnull(sizename,'''') SizeName,
ItemCode, max(convert(int,ai.active)) Active, Brand, ai.ItemCategoryId, dId,unitcode
from #invValue StockCombined,
aitem ai left outer join acolor c on ai.colorid=c.colorid
left outer join  asize z on ai.sizeid = z.sizeid, aitemcategory ac
where StockCombined.itemid = ai.itemid
and ai.itemcategoryid = ac.itemcategoryid
group by  ai.itemcategoryid, categorynamedescription, brand,
StockCombined.itemdescription, StockCombined.itemid, StockCombined.itemdesc,
StockCombined.cost, itemcode, colorname, sizename,  did ,unitcode
having sum(isnull(stock, 0)) <> 0
-- drop temporary table
drop table #invValue
End
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[SPPopulateShopInvoiceDetails_vw]    Script Date: 10/06/2012 14:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPPopulateShopInvoiceDetails_vw]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Created By : Vinoth Murugan
-- Created On : 16-02-2010
-- EXEC SPPopulateShopInvoiceDetails_vw ''243'',''1'',''1''
-- Modified by Sreejith
-- Modified On - 23-04-2010
-- Purpose - To include fine invoices generated from Shop Invoices.
--------------------------------------------------------------------------------
-- Modified on  :  30/11/2011
-- Modified by  :  MANUNADH.U
-- Purpose      :  Avoid the department wise filtration when company login is enabled.
--				   Other wise pending invoice created from other department will not list
--				   in the customer settlement
-- Reference    :  RefNo-1
--------------------------------------------------------------------------------
CREATE  PROC [dbo].[SPPopulateShopInvoiceDetails_vw](@customerid as int,@companyid as int,@departmentid as int)
AS
DECLARE @ID  INT,@INDEX  INT,@RECCOUNT  INT,@AMT  NUMERIC(18,5),@AMT1  NUMERIC(18,5),
@dblamt NUMERIC(18,5),@billdate datetime,@billno int,
@billamt NUMERIC(18,5),@Discount NUMERIC(18,5),@shopid int ,@INVAMT NUMERIC(18,5),@product int,
@invtype VARCHAR(50),@Companylogin int     --<<RefNo-1>>
BEGIN
set nocount on
set @Companylogin = (select isnull(Companylogin,0) from apackagesettings)--<<RefNo-1>>
CREATE TABLE #temp1 (Location varchar(50),InvoiceNo varchar(50),InvoiceDate  datetime,
	InvoiceAmount numeric(18,5),SettleAmount numeric(18,5),InvoiceID int,InvoiceType  varchar(20),
	ShopID int)
create table #TEMPIDS(id int identity(1,1),InvoiceID int,shopid int,invtype varchar(20) )
If @departmentid = 0
	begin
	  insert into #TEMPIDS
		select invoiceid, vw.shopid,Type from vwTotalInvoiceReceiptAmount vw, ashops s
		where s.accountable is not null and vw.shopid = s.shopid and vw.CustomerID = @customerid
		order by vw.shopid
	end
Else
	begin
	  if @Companylogin = 1 --<<RefNo-1>>
		begin
		  insert into #TEMPIDS
			select invoiceid, vw.shopid,Type from vwTotalInvoiceReceiptAmount vw, ashops s
			where s.accountable is not null and vw.shopid = s.shopid --and vw.DepartmentID=@departmentid
			  and vw.CustomerID = @customerid
			order by vw.shopid
		end
	  else
		begin
		  insert into #TEMPIDS
			select invoiceid, vw.shopid,Type from vwTotalInvoiceReceiptAmount vw, ashops s
			where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID   =@departmentid
			  and vw.CustomerID = @customerid
			order by vw.shopid
		end
	End
SET @INDEX = 1
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPIDS)
WHILE (@INDEX <= @RECCOUNT)
BEGIN
	SET @ID = (SELECT InvoiceID FROM #TEMPIDS WHERE ID= @INDEX)
	SET @shopid = (SELECT shopid FROM #TEMPIDS WHERE ID= @INDEX)
	SET @invtype = (SELECT invtype FROM #TEMPIDS WHERE ID= @INDEX)
if @invtype = ''PDI''
begin
	  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 cd.shopid = @shopid  and cd.losSpInvoiceId = @ID and  @invtype =''PDI'' )
	  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.shopid = @shopid and rd.posspinvoiceid  = @ID and  @invtype =''PDI'')
	  insert into #temp1
		select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
		  ''SSPECIAL'',vw.shopid
		from vwTotalInvoiceReceiptAmount vw, ashops s
		where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID   =@departmentid
		  and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
		  vw.shopid=@shopid and vw.Type=''PDI''
		order by vw.shopid
	END
IF @invtype = ''PCI''
	  BEGIN
		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 cd.shopid = @shopid  and cd.losinvoiceid = @ID and  @invtype =''PCI'' )
		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.shopid = @shopid and rd.posinvoiceid  = @ID and  @invtype =''PCI'' )
		
		if @Companylogin = 1 --<<RefNo-1>>
		  begin
			insert into #temp1
			select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			  ''SSALES'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
			where s.accountable is not null and vw.shopid = s.shopid --and vw.DepartmentID=@departmentid
			  and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
			  vw.shopid=@shopid and vw.Type=''PCI''
			order by vw.shopid
		  end
		else
		  begin
			insert into #temp1
			select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			  ''SSALES'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
			where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID =@departmentid
			  and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
			  vw.shopid=@shopid and vw.Type=''PCI''
			order by vw.shopid
		  end
	  END
	IF @invtype = ''PSI''
	  BEGIN
		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 cd.shopid = @shopid  and cd.LosAccInvoiceID = @ID and  @invtype =''PSI'' )
		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.shopid = @shopid and rd.posaccountsInvoiceID  = @ID and
		  @invtype =''PSI'' )
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''SSERVICE'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
			and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
			vw.shopid=@shopid and vw.Type=''PSI'' order by vw.shopid
	  END
	IF @invtype = ''SDEBIT''
BEGIN
		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
		  cd.shopid = @shopid  and cd.losdcnid = @ID and  @invtype =''SDEBIT'' )
		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.shopid = @shopid and rd.losdcnid  = @ID and  @invtype =''SDEBIT'' )
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''SDEBIT'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
			and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
			vw.shopid=@shopid and vw.Type=''SDEBIT'' order by vw.shopid
	  END
	IF @invtype=''SBI''
BEGIN
		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
		  cd.shopid = @shopid  and cd.losserinvoiceid = @ID and  @invtype =''SBI'' )
		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.shopid = @shopid and rd.Posserviceinvoiceid  = @ID and  @invtype =''SBI'')
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''BOOKINVOICE'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID =@departmentid
			and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id and
			vw.shopid=@shopid and vw.type=''SBI'' order by vw.shopid
	  END
	IF @invtype = ''RE''
BEGIN
		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 cd.shopid = @shopid  and cd.losexportid = @ID and  @invtype =''RE'' )
		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.shopid = @shopid and rd.posexportid  = @ID and  @invtype =''RE'')
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''RE'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
			and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id and
			vw.shopid=@shopid and vw.type=''RE'' order by vw.shopid
	  END
IF @invtype = ''RBI''
BEGIN
		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 cd.shopid = @shopid  and cd.RoomBillID = @ID and  @invtype =''RBI'' )
		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.shopid = @shopid and rd.RoomBillID  = @ID and  @invtype =''RBI'')
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''RBI'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
			and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id and
			vw.shopid=@shopid and vw.type=''RBI'' order by vw.shopid
	  END
	IF @invtype = ''UTB''
BEGIN
		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 cd.shopid = @shopid  and cd.UtilityBillID = @ID and  @invtype =''UTB'' )
		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.shopid = @shopid and rd.UtilityBillID  = @ID and  @invtype =''UTB'')
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''UTB'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
		    and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
		    vw.shopid=@shopid and vw.type=''UTB'' order by vw.shopid
	  END
	---Shop Fine Invoices
	IF @invtype = ''FINE''
BEGIN
		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 cd.shopid = @shopid  and cd.fineid = @ID and  @invtype =''FINE'' )
		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.shopid = @shopid and rd.fineid  = @ID and  @invtype =''FINE'')
		insert into #temp1
		  select shopname,InvoiceNo,InvoiceDate,isnull(invoiceamt-(@amt+@amt1),0),''0.00'',InvoiceID,
			''FINE'',vw.shopid from vwTotalInvoiceReceiptAmount vw, ashops s
		  where s.accountable is not null and vw.shopid = s.shopid and vw.DepartmentID=@departmentid
		    and (@amt+@amt1)< invoiceamt and vw.CustomerID = @customerid and invoiceid = @id  and
		    vw.shopid=@shopid and vw.type=''FINE'' order by vw.shopid
	  END
set @index = @index + 1
END
SELECT * FROM #TEMP1
DROP TABLE #TEMP1
DROP TABLE #TEMPIDS
END' 
END
GO
/****** Object:  View [dbo].[vwcustomersummaryasdate]    Script Date: 10/06/2012 14:17:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwcustomersummaryasdate]'))
EXEC dbo.sp_executesql @statement = N'
--modified by venki   070603 included customer grouping
--modified by venki 010903 added multicustomeramt also
--modified by venki 181203 added specialinvoice transfinished chking
CREATE view [dbo].[vwcustomersummaryasdate] as
select VW.companyid, VW.customerid,isnull(vw.shopid,0) as Shopid, vw.invoicedate, M.currencyid, 0 as opening,
0 as advance, convert(numeric(18,2),isnull(sum(invoiceamt),0)) as invoiced,
0 settled, 0 as paid,departmentid, m.CustomerCategory,isnull(m.custgroupname,'''')custgroupname
from  vwtotalinvoicereceiptamount vw, acustomermaster m
where vw.type <> ''PAYMENT'' and  vw.customerid=m.customerid group by VW.companyid,
VW.customerid,vw.shopid,m.CustomerCategory, invoicedate, M.currencyid,departmentid,m.custgroupname
union all
-- receipts advance received
select c.companyid, c.customerid,0,rh.receiptdate, c.currencyid, 0 as opening,
convert(numeric(18,2),isnull(sum(customeramount),0)) as advance, 0 as invoiced,
0 as settled, 0 as paid,DepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from receiptvoucherheader rh, acustomermaster c, vwadvancepaidreceipts vwar where
rh.receiptid = vwar.receiptid and rh.companyid = vwar.companyid and
rh.receiptcustomerid is null and rh.customerid is not null and
rh.cancelled = 0 and rh.companyid = c.companyid and rh.customerid = c.customerid
group by c.companyid, c.customerid,c.CustomerCategory, rh.receiptdate, c.currencyid,
departmentid ,c.custgroupname
union all
select distinct  c.companyid, cd.customerid,0,rh.receiptdate, c.currencyid, 0 as opening,
convert(numeric(18,2),isnull(sum(vwar.amount),0)) as advance, 0 as invoiced,
0 as settled, 0 as paid,DepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from receiptvoucherheader rh, acustomermaster c, vwadvancepaidreceipts vwar,
receiptvouchercustomerdetails cd where
rh.companyid = vwar.companyid and rh.cancelled = 0 and rh.companyid = c.companyid and
rh.receiptcustomerid is not null and rh.customerid is null and
cd.customerid=vwar.customerid and rh.receiptid=vwar.receiptid
and rh.receiptid = cd.receiptid and rh.companyid = cd.companyid
and cd.customerid = c.customerid
group by c.companyid, cd.customerid,c.CustomerCategory, rh.receiptdate, c.currencyid,
departmentid ,c.custgroupname
--deduct the amount used in settlement
union all
-- deducted the receipts used in settlement
select c.companyid, c.customerid,isnull(csh.shopid,0), csh.csdate as tdate, c.currencyid, 0 as opening,
convert(numeric(18,2),-isnull(sum(csd.settlementamount),0)) as advance, 0 as invoiced,
0.0 as settled, 0 as paid,DepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
and csh.receiptid is not null
group by c.companyid, c.customerid,c.CustomerCategory,csh.csdate, c.currencyid,
departmentid,c.custgroupname,csh.shopid
union all
-- credited through debit credit note
select c.CompanyID, c.customerid, 0,dc.dcndate, c.currencyid, 0 as opening,
convert(numeric(18,2),isnull(sum(DCNAmount),0)) as advance, 0 as invoiced,
0 as settled, 0 as paid,dcndepartmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from  debitcreditnote dc,acustomermaster c
where dc.dcnCompanyID = c.CompanyID and dc.dcncancelled =0
and c.customerid = dc.dcncustomerid and dc.dcndebit = 0
group by c.companyid,c.CustomerCategory, c.customerid, dc.dcndate, c.currencyid,
dcndepartmentid,c.custgroupname
union all
--deducting used in settlement
-- deducting the credit note given to customer a
select c.companyid, c.customerid,isnull(csh.shopid,0), csh.csdate as tdate, c.currencyid, 0 as opening,
convert(numeric(18,2),-isnull(sum(csd.settlementamount),0)) as advance, 0 as invoiced,
0.0 as settled, 0 as paid,departmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
and csh.dcnid is not null
group by c.companyid,c.CustomerCategory, c.customerid,csh.csdate, c.currencyid, departmentid,
c.custgroupname ,c.custgroupname,csh.shopid
union all
-- credited through shop credit note
select c.CompanyID, c.customerid,isnull(losDCNShopid,0), dc.losdcndate, c.currencyid, 0 as opening,
convert(numeric(18,2),isnull(sum(losDCNAmount),0)) as advance,
0 as invoiced, 0 as settled, 0 as paid,dc.losdcndepartmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from  losdebitcreditnote dc,acustomermaster c
where dc.losdcnCompanyID = c.CompanyID and dc.losdcncancelled =0
and c.customerid = dc.losdcncustomerid and dc.losdcndebit = 0
group by c.companyid,c.CustomerCategory, c.customerid, dc.losdcndate,
c.currencyid,dc.losdcndepartmentid,c.custgroupname ,losDCNShopid
union all
-- deducting used in settlement
-- deducting the credit note given to customer a
select c.companyid, c.customerid, isnull(csh.shopid,0),csh.csdate as tdate, c.currencyid, 0 as opening,
convert(numeric(18,2),-isnull(sum(csd.settlementamount),0)) as advance, 0 as invoiced,
0.0 as settled, 0 as paid,departmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
and csh.losshopdcnid is not null
group by c.companyid,c.CustomerCategory,
c.customerid,csh.csdate, c.currencyid, departmentid,c.custgroupname ,csh.shopid
union all
-- assuming the goods return as one credit note
select gh.grncompanyid, gh.GrnhCustomerID, isnull(gh.grnhshopid,0),gh.GrnhGoodsreturnnoteDate, c.currencyid, 0 opening,
convert(numeric(18,2),isnull(sum(GRNDunitprice),0)) advance, 0 invoiced, 0 settled,
0 paid,grnhDepartmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from  LosGoodsReturnNoteHeader gh, LosGoodsReturnNotedetail gd, acustomermaster c
where gh.grncompanyid = c.companyid and gh.grnhcustomerid = c.customerid and GrnhCancel =0 and
gh.GrnhGoodsreturnnoteID = gd.GRNdReturnNoteID and gh.grnhshopid = gd.grndshopid
group by gh.grncompanyid,c.CustomerCategory, gh.GrnhCustomerID, gh.GrnhGoodsreturnnoteDate, c.currencyid,
grnhdepartmentid ,c.custgroupname,gh.grnhshopid
union all
-- deducting the goods return used in customersettlement
select c.companyid, c.customerid,isnull(csh.shopid,0), csh.csdate as tdate, c.currencyid, 0 as opening,
convert(numeric(18,2),-isnull(sum(csd.settlementamount),0)) as advance, 0 as invoiced,
0.0 as settled, 0 as paid,departmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
and losGoodsreturnnoteID is not null
group by c.companyid,c.CustomerCategory, c.customerid,csh.csdate,
c.currencyid, departmentid ,c.custgroupname,csh.shopid
union all
-- receipts invoice settled
select c.companyid,  c.customerid,0,rh.receiptdate, c.currencyid, 0 as opening, 0 as advance, 0 as invoiced,
convert(numeric(18,2),isnull(sum(rd.amountreceived),0)) as settled,
0 as paid,DepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname from
receiptvoucherheader rh, acustomermaster c, receiptvoucherdetails rd where
rh.receiptid = rd.receiptid and rh.companyid = rd.companyid and
rh.cancelled = 0 and rh.companyid = c.companyid and rh.customerid = c.customerid
group by c.companyid,c.CustomerCategory, c.customerid, rh.receiptdate,
c.currencyid ,departmentid ,c.custgroupname
union all
-- settled via customer settlement
select c.companyid, c.customerid, isnull(csh.shopid,0),csh.csdate, c.currencyid, 0 as opening, 0 as advance, 0 as invoiced,
convert(numeric(18,2),isnull(sum(csd.settlementamount),0)) as settled, 0 as paid,
DepartmentID,c.CustomerCategory ,isnull(c.custgroupname,'''')custgroupname from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
group by c.companyid,c.CustomerCategory, c.customerid, csh.csdate, c.currencyid ,
departmentid ,c.custgroupname,csh.shopid
union all
-- payment done to customers
select c.companyid, c.customerid,0, ph.phpaymentdate, c.currencyid, 0 as opening, 0 as advance,
0 as invoiced, 0 as settled, convert(numeric(18,2),isnull(sum(phcustomeramount),0)) as paid,phDepartmentID,
c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname from
ahqpaymentvoucherheader ph, acustomermaster c where
ph.phcompanyid = c.companyid and ph.phcancelled = 0 and ph.phcustomerid = c.customerid
group by c.companyid,c.CustomerCategory, c.customerid, ph.phpaymentdate,
c.currencyid ,phdepartmentid ,c.custgroupname
union all
-- gettting special invoice returnes which are not settled from
--customer settlement to consider it as advance reecived from customer
select gh.ihcompanyid, gh.ihcustomerid, isnull(gh.ihshopid,0),gh.ihinvoicedate, c.currencyid, 0 opening,
convert(numeric(18,2),isnull(sum(returnamount),0)) advance, 0 invoiced, 0 settled,
0 paid, departmentid,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from  vwspecialreturninvoicetosettle gh ,acustomermaster c,ashops s
where gh.ihcompanyid = c.companyid and gh.ihcustomerid = c.customerid  and ihshopid=s.ShopID
group by gh.ihcompanyid, gh.ihCustomerID,c.CustomerCategory, gh.ihinvoicedate, c.currencyid,
departmentid ,c.custgroupname,gh.ihshopid
Union All
-- deducted the special invoice returnes used in settlement
select c.companyid, c.customerid,isnull(csh.shopid,0), csh.csdate as tdate, c.currencyid, 0 as opening,
convert(numeric(18,2),-isnull(sum(csd.settlementamount),0)) as advance, 0 as invoiced,
0.0 as settled, 0 as paid,DepartmentID,c.CustomerCategory,isnull(c.custgroupname,'''')custgroupname
from
customersettlementheader csh, acustomermaster c, customersettlementdetail csd where
csh.csid = csd.csid and csh.companyid = csd.companyid and
csh.cancelled = 0 and csh.companyid = c.companyid and csh.customerid = c.customerid
and csh.losdcnid is not null
group by c.companyid, c.customerid,c.CustomerCategory,csh.csdate, c.currencyid,
departmentid,c.custgroupname,csh.shopid'
GO
/****** Object:  StoredProcedure [dbo].[spVendorAdvanceasonDate]    Script Date: 10/06/2012 14:17:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spVendorAdvanceasonDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/****** Object:  Stored Procedure dbo.spVendorAdvanceasonDate    Script Date: 18/01/2003 9:45:49 PM ******/
--Last Modified on 	: 10/12/02
--Modified by 		: leo
--Comments 		: v3
CREATE proc [dbo].[spVendorAdvanceasonDate] @intcompanyid int, @intvendorid int,
@strtodate varchar(10), @intdepid int as
begin
declare @dttodate as datetime
set @dttodate = convert(datetime,@strtodate,101)
if @intdepid =0
select isnull(sum(advance),0) advance from vwvendorsummaryasdate where
companyid = @intcompanyid and vendorid = @intvendorid and tdate <= @dttodate
else
select isnull(sum(advance),0) advance from vwvendorsummaryasdate where
companyid = @intcompanyid and vendorid = @intvendorid and tdate <= @dttodate and departmentid = @intdepid
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 10/06/2012 14:17: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].[spCustomerSettlement]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
-------------------------------------------------------------------------------------------
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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerAdvanceAsOnDate]    Script Date: 10/06/2012 14:17: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].[spCustomerAdvanceAsOnDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----
--Last Modified on  : 10/12/02
--Modified by   : leo
--Verified By  : Hariharan
--Verified Date : 30/04/2004(updated from Devl Db)
--Comments   : v3
CREATE PROC [dbo].[spCustomerAdvanceAsOnDate] @intcompanyid int,
@intcustomerid int,
@strtodate varchar(10),
@intdepid int as
begin
declare @dttodate as datetime
set @dttodate = convert(datetime,@strtodate)
select * into #tempvwcustomersummaryasdate from vwcustomersummaryasdate
if @intdepid = 0
Begin
select isnull(sum(advance),0) advance
from #tempvwcustomersummaryasdate
where companyid = @intcompanyid
and customerid = @intcustomerid
and invoicedate <= @dttodate
End
else
Begin
select isnull(sum(advance),0) advance
from #tempvwcustomersummaryasdate
where companyid = @intcompanyid
and customerid = @intcustomerid
and invoicedate <= @dttodate
and departmentid = @intdepid
end
drop table #tempvwcustomersummaryasdate
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumDetailed]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSumDetailed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--***************************************************************************************************
-- 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 [dbo].[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' 
END
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumWithAdvance]    Script Date: 10/06/2012 14:17: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].[spDebtorAgeSumWithAdvance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--***************************************************************************************************
-- 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.
--Ref No : Ref-No1
--***************************************************************************************************
-- spDebtorAgeSumWithAdvance '''',''20101231'',''306'',0,0,0,'''',''''
create PROCEDURE [dbo].[spDebtorAgeSumWithAdvance] (@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,
Advance numeric(18,2)
)
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 = ''vwinvoiceswithAdvance.customerid in ('' + @intcustid + '') and''
End
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0,0 from vwinvoiceswithAdvance where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar)
else
set @strquery =''insert #tmpInvoices
Select *,0,0 from vwinvoiceswithAdvance where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery =''insert #tmpInvoices
Select *,0,0 from vwinvoiceswithAdvance where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''''''' +
'' and departmentid = '' + cast(@intdepartid as varchar) +
'' and invoicedate >='''''' + @dtstartdate + ''''''''
else
set @strquery =''insert #tmpInvoices
Select *,0,0 from vwinvoiceswithAdvance where '' + @Invcustid + @strCatCond + @strGroupCond +
'' invoicedate <='''''' + @dtinvdate + '''' +
'''''' and invoicedate >='''''' + @dtstartdate + ''''''''
End
exec sp_Executesql @strquery
--select * from #tmpInvoices
------------------------
select distinct ad.companyid,ad.Shopid,ad.departmentid,ad.invoicedate,ad.customerid,ad.CustomerCategory,ad.custgroupname,
case when @intdepartid=0 and @intShopID=0 then
sum(isnull(ad.advance,0))over (partition by ad.companyid,ad.customerid)
when @intdepartid<>0 and @intShopID=0 then
sum(isnull(ad.advance,0))over (partition by ad.companyid,ad.customerid,ad.departmentid)
when @intdepartid=0 and @intShopID<>0 then
sum(isnull(ad.advance,0))over (partition by ad.companyid,ad.customerid,ad.Shopid)
when @intdepartid<>0 and @intShopID<>0 then
sum(isnull(ad.advance,0))over (partition by ad.companyid,ad.customerid,ad.departmentid,ad.Shopid)
end Advance
into #tempvwcustomersummaryasdate
from vwcustomersummaryasdate ad
where
(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='''')
--group by customerid
------------------------
--select * from #tempvwcustomersummaryasdate
UPDATE #tmpInvoices SET #tmpInvoices.Advance=ad.Advance FROM
#tempvwcustomersummaryasdate ad
LEFT OUTER JOIN
#tmpInvoices inv
ON ad.customerid=inv.customerid
------------------------
-------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
'''',
0, ---ad.advance,
0, --due
'''',
'''', --debtrtype
'''',
ad.CustomerCategory,
'''',1,1,1,
'''',  --custtype
1,   --dutyamnt
1,   --costprice
ad.custgroupname,
0,
ad.advance
from #tempvwcustomersummaryasdate ad
LEFT OUTER JOIN #tmpInvoices inv ON ad.customerid=inv.customerid
where inv.customerid is null
-----------------------------------------------------------------
if @dtstartdate =''''
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * from vwsettlements where '' + @SettleCustId +
'' settleddate <='''''' + @dtinvdate + ''''''''
End
Else
Begin
if @intdepartid >0
set @strquery  = '' insert #tmpSettlements Select * from vwsettlements where '' + @SettleCustId +
'' departmentid = '' + cast(@intdepartid as varchar) +
'' and settleddate <='''''' + @dtinvdate +  '''' +
'''''' and settleddate >='''''' + @dtstartdate + ''''''''
else
set @strquery  = ''insert #tmpSettlements  Select * 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,isnull(sum(#tmpInvoices.Advance),0)Advance 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))''
---select * from #tmpInvoices
---select * from #tmpSettlements
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,isnull(#tmpInvoices.Advance,0)Advance 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,#tmpInvoices.Advance''
--having isnull(sum(invamt),0)-isnull(sum(settledamt),0)<>0 and isnull(sum(#tmpInvoices.Advance),0)<>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
drop table #tempvwcustomersummaryasdate
end
set nocount off
set ansi_Warnings on' 
END
GO
